-1

I was asked the question below and I am stuck. I understand the difference between value & reference, but do not know when I would use each in a method.

If you were writing a method, which parameter passing method would you choose, if any? Why?

I found this below to help me get a grasp of the differences.

"If I tell you the URL, I'm passing by reference. You can use that URL to see the same web page I can see. If that page is changed, we both see the changes. If you delete the URL, all you're doing is destroying your reference to that page - you're not deleting the actual page itself.

If I print out the page and give you the printout, I'm passing by value. Your page is a disconnected copy of the original. You won't see any subsequent changes, and any changes that you make (e.g. scribbling on your printout) will not show up on the original page. If you destroy the printout, you have actually destroyed your copy of the object - but the original web page remains intact."

coggicc
  • 245
  • 2
  • 5
  • 13

1 Answers1

0

Keep in mind, passing by value makes a copy. There might be two reasons not to do this. First, if the value you are passing is some large data structure (or anything else that uses a lot of memory), it is probably inefficient and unnecessary to copy the entire thing. Second, if you want any changes to the parameter to be mirrored in the calling function, you must pass by reference. That way, the original value gets modified, not a copy.

When neither of those cases apply, passing by value is usually simpler and a better option.

There's one other thing to consider. Passing by value, since it creates a copy, protects the value in the original function from accidental modification. However, you may want the performance benefits from passing by reference. In this case, it is good practice to pass by reference, but mark the parameter as const (or whatever is appropriate in your language).

Dominick Pastore
  • 4,177
  • 2
  • 17
  • 29