I'm dealing with legacy code and I constantly see method calls with multiple attributes from the same object being passed into a method:
update(user.getID(), user.getLanguage() etc...)
Is there a distinct advantage or disadvantage to doing it this way or would I just be as well to pass in the user object (in this case) and deal with attributes within the method called?
Follow Up:
Lots of excellent answers, thank you. Apologies for the lack of exact detail in the question but as I said this is seen all over the system I am working on and this seemed like a nice simple example. Please feel free to turn this question into a community wiki question as no one answer can possibly be accepted over others as they're all good and have valid points.
Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below. And we have a simple program with a generic method to swap two objects, the class looks like below.
No, that is not possible in Java. In Java, all arguments to methods are passed by value. Note that variables of non-primitive type, which are references to objects, are also passed by value: in that case, a reference is passed by value. Note that passing a reference by value is not the same as passing by reference.
A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value. “Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.
Java is officially always pass-by-value. The question is, then, “what is passed by value?” As we have said in class, the actual “value” of any variable on the stack is the actual value for primitive types (int, float, double, etc) or the reference for reference types.
Both have their advantages. I'd decide for each method depending on what it is supposed to do. For legacy code, though, I'd prefer to not change anything unless there is actually a problem.
Pro several values, con object reference:
Pro passing a single user object:
As you see a property can be considered an advantage or disadvantage depending on your needs.
In fact, it would be much, much better to pass a reference to the object, for two reasons:
To avoid excessively long parameter lists, the recommended refactoring is to create a object that contains all the data - aren't you lucky that you already have such an object?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With