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

后端 未结 6 1002
野性不改
野性不改 2021-01-12 15:08

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 r

相关标签:
6条回答
  • 2021-01-12 15:48

    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.

    0 讨论(0)
  • 2021-01-12 15:48

    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.

    0 讨论(0)
  • 2021-01-12 15:56

    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 讨论(0)
  • 2021-01-12 15:58

    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.

    0 讨论(0)
  • 2021-01-12 16:07

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

    0 讨论(0)
  • 2021-01-12 16:08

    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.

    0 讨论(0)
提交回复
热议问题