Question

The Builder Pattern solves the problem of Telescoping Constructors; that is, having a single constructor for every possible parameter combination (including those combinations for which a parameter is omitted).

So for example:

  public Food(int id, String name) {
    this(id, name, 0, 0, 0);
  }

  public Food(int id, String name, int calories) {
    this(id, name, calories, 0, 0);
  }

  public Food(int id, String name, int servingSize) {
    this(id, name, 0, servingSize, 0);
  }

  public Food(int id, String name, int fat) {
    this(id, name, 0, 0, fat);
  }

  public Food(int id, String name, int calories, int servingSize) {
    this(id, name, calories, servingSize, 0);
  }
  public Food(int id, String name, int calories, int fat) {
    this(id, name, calories, 0, fat);
  }

  public Food(int id, String name, int servingSize, int fat) {
    this(id, name, 0, servingSize, fat);
  }

  public Food(int id, String name, int calories, int servingSize, int fat) {
    this(id, name, calories, servingSize, fat);
  }

If you set the Builder Pattern up properly, using the voluminous amount of code required, you can simply:

Food food = new FoodBuilder().SetName("Bananas").SetCalories(120).Build();

using any combination of parameters in any order.

Assuming that each parameter in the constructor will always reside at the same relative location while still allowing for omitted parameters, how would one calculate the number of constructors required given the number n of optional parameters needed?

(in the above example, id and name are required parameters, while calories, servingSize, and fat are all optional parameters).

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with cs.stackexchange
scroll top