Telescoping Constructor

Is an anti-pattern: class having multiple constructors, where each constructor calls a more specific constructor in the hierarchy, which has more parameters than itself, providing default values for the extra parameters. The next constructor does the same until there is no left.

This technique brings common issues:

  • it’s difficult to read and maintain such code
  • if parameters are of same type, one could mix them up without a compilation (or runtime) error
  • calling a chain of constructors where many parameters are not used

There are 3 alternatives:

  1. JavaBeans – define constructor with min number of parameters and set the rest of the fields using mutators
    • – object can not be immutable (not thread safe)
    • – fields can not be final
    • – object can be accessed in a state when is not fully implemented (if not an atomic operation)
  2. Static factory method = static methods returning an instance of the enclosing class
    • + methods are named (unlike constructors), revealing their intent
    • + immutable instances can be returned
    • + instances can be reused (can be used for caching, pooling,…)
    • – hard to maintain if many different constructors are needed
  3. Builder Pattern