Is it a good or bad idea to make setters in java return \"this\"?
public Employee setName(String name){
this.name = name;
return this;
}
From the statement
list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));
i am seeing two things
1) Meaningless statement. 2) Lack of readability.
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
public class NutritionalFacts {
private final int sodium;
private final int fat;
private final int carbo;
public int getSodium(){
return sodium;
}
public int getfat(){
return fat;
}
public int getCarbo(){
return carbo;
}
public static class Builder {
private int sodium;
private int fat;
private int carbo;
public Builder sodium(int s) {
this.sodium = s;
return this;
}
public Builder fat(int f) {
this.fat = f;
return this;
}
public Builder carbo(int c) {
this.carbo = c;
return this;
}
public NutritionalFacts build() {
return new NutritionalFacts(this);
}
}
private NutritionalFacts(Builder b) {
this.sodium = b.sodium;
this.fat = b.fat;
this.carbo = b.carbo;
}
}
Paulo Abrantes offers another way to make JavaBean setters fluent: define an inner builder class for each JavaBean. If you're using tools that get flummoxed by setters that return values, Paulo's pattern could help.