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

后端 未结 6 1001
野性不改
野性不改 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题