Search code examples
javabuilderfactory-patterneffective-java

Effective Java: Builder Pattern


I was reading Effective java item# 2- The Builder pattern

http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2

It is said here that java bean is not an effective way to create the object with multiple parameters. But what if I have the javabean this way:

// JavaBeans Pattern 
public class NutritionFacts {
private final int servingSize ;
private final int servings  ;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public NutritionFacts() { }
// Setters
public void setServingSize(int val) { servingSize = val; }
public void setServings(int val) { servings = val; }
public void setCalories(int val) { calories = val; }
public void setFat(int val) { fat = val; }
public void setSodium(int val) { sodium = val; }
public void setCarbohydrate(int val) { carbohydrate = val; }
}

Note that I made all member variables as Final

Now an instance can be created this way:

NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohydrate(27);

Whats wrong if I do this way? Can someone help me understand? Thanks, Rajan


Solution

  • You have not even tried to compile this, because unfortunately it will fail. The reason for this is because you declared a variable final, it must be initialized by the time the constructor is finished.

    This is incidentially why setters on final variables make no sense and also why the Builder pattern is often used to work around this problem.