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

前端 未结 27 1058
抹茶落季
抹茶落季 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 not only breaks the convention of getters/setters, it also breaks the Java 8 method reference framework. MyClass::setMyValue is a BiConsumer, and myInstance::setMyValue is a Consumer. If you have your setter return this, then it's no longer a valid instance of Consumer, but rather a Function, and will cause anything using method references to those setters (assuming they are void methods) to break.

提交回复
热议问题