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

前端 未结 27 946
抹茶落季
抹茶落季 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 know Java but I've done this in C++. Other people have said it makes the lines really long and really hard to read, but I've done it like this lots of times:

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

    This is even better:

    list.add(
        new Employee("Jack Sparrow")
        .Id(1)
        .foo("bacon!"));
    

    at least, I think. But you're welcome to downvote me and call me an awful programmer if you wish. And I don't know if you're allowed to even do this in Java.

提交回复
热议问题