The following bean was presented in the book:
NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohydrate(27);
of these, the servingSize
and servings
set by setServingSize(int)
and setServings(int)
are fundamental - at least in the book - for the nutrition facts.
But if you just call:
NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setCalories(100);
then the servings
field would not be set. Thus the resulting instance is now in an invalid state.
So if you would call a method that expects a valid instance, say healthRiskCalculator.calculateHealthRisk(NutritionFacts facts)
then you would get an exception either within the object or in healthRiskCalculator
.
So now you could check the damage to your health when you call calculateHealthRisk()
but there may be many methods that read or use the object instance. Furthermore, you may have created a lot of invalid instances for other products as well. In other words, this is not fail fast.
So there is no fail safe way of creating a constructed object using beans. This is not particular to threading, you can create an invalid bean instance within a single thread.