CS/SWE 332 In Class Exercise Number 24

Name(s):

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.
  1. What does a "regular" constructor look like for this class and why is it a problem?



  2. Design a constructor appropriate for the bean pattern. Beans are objects with getters and setters (you only need the latter here.)

    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?



  3. Address the mutability problem with a telescoping pattern. A telescoping constructor recursively calls other constructors. (Obviously, this has to end somewhere...)

    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?

  4. Address all these problems with a builder pattern. The builder model for constructors is:
    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:
    • A ClassOfInterest.Builder constructor call with all required attributes,
    • followed by a "dot train" for each non-default value of the other attributes,
    • followed by a build() call.