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

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

    If I'm writing an API, I use "return this" to set values that will only be set once. If I have any other values that the user should be able to change, I use a standard void setter instead.

    However, it's really a matter of preference and chaining setters does look quite cool, in my opinion.

提交回复
热议问题