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

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

    I prefer using 'with' methods for this:

    public String getFoo() { return foo; }
    public void setFoo(String foo) { this.foo = foo; }
    public Employee withFoo(String foo) {
      setFoo(foo);
      return this;
    }
    

    Thus:

    list.add(new Employee().withName("Jack Sparrow")
                           .withId(1)
                           .withFoo("bacon!"));
    

    Warning: this withX syntax is commonly used to provide "setters" for immutable objects, so callers of these methods might reasonably expect them to create new objects rather than to mutate the existing instance. Maybe a more reasonable wording would be something like:

    list.add(new Employee().chainsetName("Jack Sparrow")
                           .chainsetId(1)
                           .chainsetFoo("bacon!"));
    

    With the chainsetXyz() naming convention virtually everyone should be happy.

提交回复
热议问题