Is it a good or bad idea to make setters in java return "this"?
public Employee setName(String name){
this.name = name;
return this;
}
This pattern can be useful because then you can chain setters like this:
list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));
instead of this:
Employee e = new Employee();
e.setName("Jack Sparrow");
...and so on...
list.add(e);
...but it sort of goes against standard convention. I suppose it might be worthwhile just because it can make that setter do something else useful. I've seen this pattern used some places (e.g. JMock, JPA), but it seems uncommon, and only generally used for very well defined APIs where this pattern is used everywhere.
Update:
What I've described is obviously valid, but what I am really looking for is some thoughts on whether this is generally acceptable, and if there are any pitfalls or related best practices. I know about the Builder pattern but it is a little more involved then what I am describing - as Josh Bloch describes it there is an associated static Builder class for object creation.
It not only breaks the convention of getters/setters, it also breaks the Java 8 method reference framework.
MyClass::setMyValue
is aBiConsumer<MyClass,MyValue>
, andmyInstance::setMyValue
is aConsumer<MyValue>
. If you have your setter returnthis
, then it's no longer a valid instance ofConsumer<MyValue>
, but rather aFunction<MyValue,MyClass>
, and will cause anything using method references to those setters (assuming they are void methods) to break.I used to prefer this approach but I have decided against it.
Reasons:
The Builder pattern I saw do not use the setFoo(foo).setBar(bar) convention but more foo(foo).bar(bar). Perhaps for exactly those reasons.
It is, as always a matter of taste. I just like the "least surprises" approach.
If you use the same convention in whole applicaiton it seems fine.
On the oher hand if existing part of your application uses standard convention I'd stick to it and add builders to more complicated classes