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

后端 未结 6 1036
野性不改
野性不改 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: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.

提交回复
热议问题