开发者

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 th开发者_开发问答e 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?


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜