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

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

    If you don't want to return 'this' from the setter but don't want to use the second option you can use the following syntax to set properties:

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

    As an aside I think its slightly cleaner in C#:

    list.Add(new Employee() {
        Name = "Jack Sparrow",
        Id = 1,
        Foo = "bacon!"
    });
    

提交回复
热议问题