Consider a NutritionFacts
class with the following attributes:
public class NutritionFacts {
private int servingSize; // Required
private int fat; // Optional
private int protein; // Optional
private int carbohydrates; // Optional
private int sodium; // Optional
private int calories; // = fat*9 + protein*4 + carbohydrates*4
Suppose that servingSize
is
required, other fields are optional, and calories
are computed.
Show how this constructor would be used.
What is the consistency disadvantage,
how could you detect it, and
how could "freezing" (partially) overcome it.
Show the problematic code.
What is the mutability disadvantage?
How many constructors are needed? Show them all.
Use the constructors for a product where
carbohydrates
are zero.
Repeat for protein
zero. How easy is it to confuse these?
public class ClassOfInterest {
// private final attributes
public static class Builder {
// repeated (nonfinal) attributes
// one public Builder constructor for all required attributes
// public Builder producer/setters, one for each optional attribute
// public build() method that produces a ClassOfInterest object
}
// private constructor for ClassOfInterest that takes a Builder as an argument.
// the constructor assigns the Builder attributes to the ClassOfInterest attributes
}
Use the builder pattern to construct a NutritionFacts
object.
The pattern here is:
ClassOfInterest.Builder
constructor call
with all required attributes,
build()
call.