Is it bad practice to make a setter return “this”?

前端 未结 27 1037
抹茶落季
抹茶落季 2020-11-27 09:39

Is it a good or bad idea to make setters in java return \"this\"?

public Employee setName(String name){
   this.name = name;
   return this;
}
27条回答
  •  无人及你
    2020-11-27 09:54

    It's not a bad practice at all. But it's not compatiable with JavaBeans Spec.

    And there is a lot of specification depends on those standard accessors.

    You can always make them co-exist to each other.

    public class Some {
        public String getValue() { // JavaBeans
            return value;
        }
        public void setValue(final String value) { // JavaBeans
            this.value = value;
        }
        public String value() { // simple
            return getValue();
        }
        public Some value(final String value) { // fluent/chaining
            setValue(value);
            return this;
        }
        private String value;
    }
    

    Now we can use them together.

    new Some().value("some").getValue();
    

    Here comes another version for immutable object.

    public class Some {
    
        public static class Builder {
    
            public Some build() { return new Some(value); }
    
            public Builder value(final String value) {
                this.value = value;
                return this;
            }
    
            private String value;
        }
    
        private Some(final String value) {
            super();
            this.value = value;
        }
    
        public String getValue() { return value; }
    
        public String value() { return getValue();}
    
        private final String value;
    }
    

    Now we can do this.

    new Some.Builder().value("value").build().getValue();
    

提交回复
热议问题