Is it a good or bad idea to make setters in java return \"this\"?
public Employee setName(String name){
this.name = name;
return this;
}
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.
It's not a bad practice at all. But it's not compatiable with JavaBeans Spec.
And there is a lot of specification depends on those standard accessors.
You can always make them co-exist to each other.
public class Some {
public String getValue() { // JavaBeans
return value;
}
public void setValue(final String value) { // JavaBeans
this.value = value;
}
public String value() { // simple
return getValue();
}
public Some value(final String value) { // fluent/chaining
setValue(value);
return this;
}
private String value;
}
Now we can use them together.
new Some().value("some").getValue();
Here comes another version for immutable object.
public class Some {
public static class Builder {
public Some build() { return new Some(value); }
public Builder value(final String value) {
this.value = value;
return this;
}
private String value;
}
private Some(final String value) {
super();
this.value = value;
}
public String getValue() { return value; }
public String value() { return getValue();}
private final String value;
}
Now we can do this.
new Some.Builder().value("value").build().getValue();
I'm in favor of setters having "this" returns. I don't care if it's not beans compliant. To me, if it's okay to have the "=" expression/statement, then setters that return values is fine.
This may be less readable
list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));
or this
list.add(new Employee()
.setName("Jack Sparrow")
.setId(1)
.setFoo("bacon!"));
This is way more readable than:
Employee employee = new Employee();
employee.setName("Jack Sparrow")
employee.setId(1)
employee.setFoo("bacon!"));
list.add(employee);
If I'm writing an API, I use "return this" to set values that will only be set once. If I have any other values that the user should be able to change, I use a standard void setter instead.
However, it's really a matter of preference and chaining setters does look quite cool, in my opinion.
In general it’s a good practice, but you may need for set-type functions use Boolean type to determine if operation was completed successfully or not, that is one way too. In general, there is no dogma to say that this is good or bed, it comes from the situation, of course.