I'm reading "Effective Java 2n Edition" from Joshua Bloch. My question is about Item 2 "Consider a builder when faced with many constructor parameters".
Shortened example from the book:
public class NutritionFacts {
private final int calories;
public static class Builder {
private int calories = 0;
public Builder(){}
public Builder calories(int val) {
calories = val;
return this;
}
public NutritionFacts build(){
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder){
calories = builder.calories;
}
}
invoke it: NutritionFacs cocaCola = new NutritionFacts.Builder().calories(300).build()
My version
public class NutritionFacts {
private int calories;
public NutritionFacts calories(int calories) {
this.calories = calories;
return this;
}
}
invoke: NutritionFacts cocaCola = new NutritionFacts().calories(300);
So what's the advantage of the example from the book? I only see the immutability which is not possible with my solution.
Aucun commentaire:
Enregistrer un commentaire