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

前端 未结 27 778
抹茶落季
抹茶落季 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 10:10

    From the statement

    list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));
    

    i am seeing two things

    1) Meaningless statement. 2) Lack of readability.

    0 讨论(0)
  • 2020-11-27 10:12

    If you use the same convention in whole applicaiton it seems fine.

    On the oher hand if existing part of your application uses standard convention I'd stick to it and add builders to more complicated classes

    public class NutritionalFacts {
        private final int sodium;
        private final int fat;
        private final int carbo;
    
        public int getSodium(){
            return sodium;
        }
    
        public int getfat(){
            return fat;
        }
    
        public int getCarbo(){
            return carbo;
        }
    
        public static class Builder {
            private int sodium;
            private int fat;
            private int carbo;
    
            public Builder sodium(int s) {
                this.sodium = s;
                return this;
            }
    
            public Builder fat(int f) {
                this.fat = f;
                return this;
            }
    
            public Builder carbo(int c) {
                this.carbo = c;
                return this;
            }
    
            public NutritionalFacts build() {
                return new NutritionalFacts(this);
            }
        }
    
        private NutritionalFacts(Builder b) {
            this.sodium = b.sodium;
            this.fat = b.fat;
            this.carbo = b.carbo;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:12

    Paulo Abrantes offers another way to make JavaBean setters fluent: define an inner builder class for each JavaBean. If you're using tools that get flummoxed by setters that return values, Paulo's pattern could help.

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