Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java return the Object/modify the object (coding guidelines)

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?

like image 659
Rnet Avatar asked Jul 07 '11 11:07

Rnet


People also ask

Can you return an object in Java?

"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.

Can you modify the object set in Java?

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.

How do you return a new object in Java?

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.

Can a method return a reference to an 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.


3 Answers

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")....

like image 165
Thomas Avatar answered Sep 28 '22 07:09

Thomas


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.

like image 29
Don Roby Avatar answered Sep 28 '22 07:09

Don Roby


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.

like image 27
Mr.Eddart Avatar answered Sep 28 '22 06:09

Mr.Eddart