6

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?

Rnet
  • 4,326
  • 9
  • 42
  • 81
  • To me '''return o''' statement depends from your conrete implementation of it. Passing object by ref will modify the object in the stack. To me '''return o''' statement is not needed. – gskillz Jul 07 '11 at 11:11
  • http://stackoverflow.com/questions/40480/is-java-pass-by-reference – Ozair Kafray Jul 07 '11 at 11:10

6 Answers6

2

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

Thomas
  • 80,843
  • 12
  • 111
  • 143
2

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.

Don Roby
  • 39,169
  • 6
  • 84
  • 105
1

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.

Mr.Eddart
  • 9,190
  • 11
  • 45
  • 71
0

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

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

This allows you to keep a reference to the original object and have reference to the modified object.

luketorjussen
  • 2,916
  • 1
  • 17
  • 37
0

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

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

    }
}

See StringBuilder as an example.

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
0

The second one is less confusing to me, because it isn't clear from the first one if returned and passed objects are the same, and I don't find it normal to ignore a returned value.

JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174