If a method populates/modifies an object, would it be preferable to return the object or to keep the return type as void and the method would modify the Object through its reference?
public Obj populate(Obj o)
{
....
return o;
}
public void populate(Obj o)
{
....
}
I know this is a trivial question, but which one is the most preferred?
"In order to return an object from a Java method, you must first declare a variable to hold a reference to the object." So in this case, Ball is a variable that is a reference to the object. Correct? redBall is a reference to the object created by the new Ball("red") statement.
Generally, collections with some kind of internal structure don't watch for changes in their elements, and their structure will be destroyed if you modify the elements (in ways that change the property that the structure is based on). This holds for TreeSet as well.
Method is returning the reference of the object When we are writing the following code Cube obj2 = obj1. getObject(); in the above example, the called method getObject() of obj1 object is returning the reference of the newly created object. So, obj2 is getting the reference of the newly created object.
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.
I depends on your style, but one advantage of returning: you could call populate(o).doSomethingElse();
, i.e. you can chain method calls.
Have a look at how StringBuilder
does that for example, which allows things like this new StringBuilder().append("a").append("b")....
I would go with Command-Query separation generally.
That is to say, if the method mutates the argument, it should not also return the argument.
There are however (as noted in the wikipedia article above) situations where violating this general principle is appropriate.
I would say the "first" option, to return the object. This has no disadvantages, and leave you "room" to make a change of implementation in the future (for example, returning a "deep copy" instead of the same object) without modifying the signature.
In short, i see it more flexible.
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