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

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

    I don't think there's anything specifically wrong with it, it's just a matter of style. It's useful when:

    • You need to set many fields at once (including at construction)
    • you know which fields you need to set at the time you're writing the code, and
    • there are many different combinations for which fields you want to set.

    Alternatives to this method might be:

    1. One mega constructor (downside: you might pass lots of nulls or default values, and it gets hard to know which value corresponds to what)
    2. Several overloaded constructors (downside: gets unwieldy once you have more than a few)
    3. Factory/static methods (downside: same as overloaded constructors - gets unwieldy once there is more than a few)

    If you're only going to set a few properties at a time I'd say it's not worth returning 'this'. It certainly falls down if you later decide to return something else, like a status/success indicator/message.

提交回复
热议问题