Java returns an object / modifies an object (coding guidelines)

If a method fills / modifies an object, would it be preferable to return the object or save the return type as void, and the method will change 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 preferable?

+6
source share
6 answers

Depending on your style, but one advantage of returning: you can call populate(o).doSomethingElse(); , i.e. you can chain method calls.

See how StringBuilder does StringBuilder , for example, which allows things like new StringBuilder().append("a").append("b")....

+2
source

I would go with the Command-Query section as a whole.

That is, if a method mutates an argument, it also should not return the argument.

However, as noted in the Wikipedia article above, situations in which a violation of this general principle are appropriate.

+2
source

I would say the "first" option is to return the object. This has no shortcomings and leaves you a β€œroom” to make changes to the implementation in the future (for example, returning a β€œdeep copy” instead of the same object) without changing the signature.

In short, I see it more flexible.

+1
source

I would choose the first one, since it allows you to either modify the transferred object, or return it, or take a copy of the object and return a copy.

 public Obj populate(Obj o) { Obj returnObj = o.clone(); .... return returnObj; } 

This allows you to save the link to the source object and refer to the modified object.

0
source

It is preferable to modify the this object and leave the arguments unchanged.

 class ModifiedType { public ModifiedType populate(UnmodifiedType arg) { return this; } // or public void populate(UnmodifiedType arg) { } } 

See StringBuilder example.

0
source

The second of them is less confusing for me, because it is not clear from the first if the returned and transferred objects are the same, and I do not consider it normal to ignore the return value.

0
source

Source: https://habr.com/ru/post/892220/


All Articles