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

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

    I used to prefer this approach but I have decided against it.

    Reasons:

    • Readability. It makes the code more readable to have each setFoo() on a separate line. You usually read the code many, many more times than the single time you write it.
    • Side effect: setFoo() should only set field foo, nothing else. Returning this is an extra "WHAT was that".

    The Builder pattern I saw do not use the setFoo(foo).setBar(bar) convention but more foo(foo).bar(bar). Perhaps for exactly those reasons.

    It is, as always a matter of taste. I just like the "least surprises" approach.

提交回复
热议问题