I have a beginners question. I searched a lot for the answer but can't seem to find the exact answer so maybe somebody of more experienced developers can help me with this one.
So, let's say you have a following situation in code (this is simplified version of the situation):
SomeObject a1 = new SomeObject();
a1 = someMethod(a1);
public SomeObject someMethod(SomeObject a1) {
a1.changeVariable();
return a1;
}
now I heard from several people saying that passing a reference to an object to a method and catching the return value is bad coding practice. Unfortunately nobody can exactly explain to me why it is bad coding practice, and my search for the reason came up with nothing. Can some explain why it is bad practice to do this? I can not think of a situation where something for this can go wrong.
Thanks in advance, you nice people have already helped me with answers to other people countless times, this is a first time I actually needed to post a question :)
1) Yes, it returns a reference to the object. 2) If the method is private, then it can only be called from within the class itself.
It is necessary to return the object if it was passed by reference to a function. Explanation: Having the address being passed to the function, the changes are automatically made to the main function. In all the cases if the address is being used, the same memory location will be updated with new values.
Java doesn't pass objects. It passes object references - so if anyone asks how does Java pass objects, the answer is: "it doesn't". In the case of primitive types, once passed, they get allocated a new space in the stack and thus all further operations on that reference are linked to the new memory location.
When passing an argument by reference, the method gets a reference to the object. A reference to an object is the address of the object in memory. Now, the local variable within the method is referring to the same memory location as the variable within the caller.
In the scenario you've shown, there isn't much obvious benefit. However, as a pattern it can be useful in my experience - particularly if the method performs validation.
Guava's Preconditions.checkNotNull
method is a great example of this. It means I can write code like this:
public class Player {
private final String name;
public Player(String name) {
this.name = Preconditions.checkNotNull(name);
}
}
... instead of having to split the assignment and the validation. It also allows validation to exist as part of another call, e.g. to another constructor:
super(Preconditions.checkNotNull(name));
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