What is Telescoping Pattern
A telescoping constructor is a series of constructors where each one has a different number of parameters. Each constructor calls a more specific constructor in the hierarchy, providing a default value for the remaining parameters.
Disadvantage of Below Approach
- Constructors are hard to read when they have many parameters
- When adding new parameters, you have to add new constructors to the chain. This pattern can therefore not scale very well
- It becomes difficult to remember the required order of the parameters, especially when many of them are of the same type. Additionally, the code becomes less readable, and it’s not always clear what is being passed to the constructor. This is addressed by using Builder Pattern
Report
import java.util.Date; public class Report { private String reportName; private Integer reportSize; private String reportFormat; private Date reportDate; public Report() { } //Constructor1 public Report(String reportName) { this.reportName = reportName; } public Report(String reportName, Integer reportSize) { this(reportName); //Call to before Constructor1 this.reportSize = reportSize; } public Report(String reportName, Integer reportSize, String reportFormat) { this(reportName, reportSize); //Call to before Constructor2 this.reportFormat = reportFormat; } public Report(String reportName, Integer reportSize, String reportFormat, Date reportDate) { this(reportName, reportSize, reportFormat); //Call to before Constructor3 this.reportDate = reportDate; } }