Skip to content

Instantly share code, notes, and snippets.

@sajjadyousefnia
Created October 10, 2018 10:47
Show Gist options
  • Save sajjadyousefnia/242be0445087663fa55f5f3fee5062e0 to your computer and use it in GitHub Desktop.
Save sajjadyousefnia/242be0445087663fa55f5f3fee5062e0 to your computer and use it in GitHub Desktop.
// Telescoping constructor pattern - does not scale well!
public class NutritionFacts {
private final int servingSize; // (mL)
required
private final int servings;
// (per container) required
private final int calories;
// (per serving)
optional
private final int fat;
// (g/serving)
optional
private final int sodium;
// (mg/serving)
optional
private final int carbohydrate; // (g/serving)
optional
public NutritionFacts(int servingSize, int servings) {
this(servingSize, servings, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories) {
this(servingSize, servings, calories, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories, int fat) {
this(servingSize, servings, calories, fat, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories, int fat, int sodium) {
this(servingSize, servings, calories, fat, sodium, 0);
}ITEM 2: CONSIDER A BUILDER WHEN FACED WITH MANY CONSTRUCTOR PARAMETERS
public NutritionFacts(int servingSize, int servings,
int calories, int fat, int sodium, int carbohydrate) {
this.servingSize = servingSize;
this.servings
= servings;
this.calories
= calories;
this.fat
= fat;
this.sodium
= sodium;
this.carbohydrate = carbohydrate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment