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

前端 未结 27 1041
抹茶落季
抹茶落季 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 10:06

    It's not bad practice. It's an increasingly common practice. Most languages don't require you to deal with the returned object if you don't want to so it doesn't change "normal" setter usage syntax but allows you to chain setters together.

    This is commonly called a builder pattern or a fluent interface.

    It's also common in the Java API:

    String s = new StringBuilder().append("testing ").append(1)
      .append(" 2 ").append(3).toString();
    

提交回复
热议问题