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

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

    On first sight: "Ghastly!".

    On further thought

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

    is actually less error prone than

    Employee anEmployee = new Employee();
    anEmployee.setName("xxx");
    ...
    list.add(anEmployee);
    

    So quite interesting. Adding idea to toolbag ...

提交回复
热议问题