Pages

Constructor telescoping in Java

Use Case : When there are several parameters in which some is required/mandatory parameter to create an instance of class and some are optional, you can provide the value of optional parameter or not.

The default value for the optional parameter is provided by class.

What is telescoping constructor ?

telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameter, a third with two optional parameters, and so on, culminating in a constructor with all the optional parameters.

Note: this pattern is helpful only when you have limited number of parameters. if parameter list is too long then this is not the best choice, you should use Builder pattern in this case.

Here I am providing you an example how toimplements this pattern -

public class ConsTelescoping {

 private final int servingSize; //  required
 private final int servings; // required
 private final int calories; // optional
 private final int fat; //  optional
 private final int sodium; // optional
 private final int carbohydrate; // optional

 public ConsTelescoping(int servingSize, int servings) {
  this(servingSize, servings, 0);
 }

 public ConsTelescoping(int servingSize, int servings, int calories) {
  this(servingSize, servings, calories, 0);
 }

 public ConsTelescoping(int servingSize, int servings, int calories, int fat) {
  this(servingSize, servings, calories, fat, 0);
 }

 public ConsTelescoping(int servingSize, int servings, int calories, int fat,
   int sodium) {
  this(servingSize, servings, calories, fat, sodium, 0);
 }

 public ConsTelescoping(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;
 }
}
 

How to write an immutable Class in Java 


No comments:

Post a Comment