They Just Did It

Get better in Java






Telescopic constructor pattern

without comments

Telescopic constructor pattern is a pattern (which have its disadvantages) to create constructors of class that have a number of optional parameters.

Consider a class which has 2 mandatory fields – man1 and man2 – and 4 optional – opt1, opt2, opt3 and opt4. Programmers traditionally have been using telescopic pattern to create constructors for this class.

In telescopic pattern, you provide a constructor with only the required parameters, another with a single optional parameter, third with two optional parameters and so on, until constructor with all optional parameters are available.


public class TelescopicPattern {

	//mandatory fields
	private final int man1;
	private final int man2;

	//optional fields defaults to zero
	private final int opt1;
	private final int opt2;
	private final int opt3;
	private final int opt4;

	public TelescopicPattern(int man1, int man2){
		this(man1, man2, 0);
	}

	public TelescopicPattern(int man1, int man2, int opt1){
		this(man1, man2, opt1, 0);
	}

	public TelescopicPattern(int man1, int man2, int opt1,
			int opt2){
		this(man1, man2, opt1, opt2, 0);
	}

	public TelescopicPattern(int man1, int man2, int opt1,
			int opt2, int opt3){
		this(man1, man2, opt1, opt2, opt3, 0);
	}

	public TelescopicPattern(int man1, int man2, int opt1,
			int opt2, int opt3, int opt4){
		this.man1 = man1;
		this.man2 = man2;
		this.opt1 = opt1;
		this.opt2 = opt2;
		this.opt3 = opt3;
		this.opt4 = opt4;
	}

}

Telescopic pattern disadvantages

The following are some of the disadvantages of the pattern

  1. Client may still have to use the longest constructor even if some of optional parameters have to be left out.

TelescopicPattern telescope = new TelescopicPattern(10, 20, 0, 0, 1, 1);

2.    Pattern does not scale well and can be a maintenance nightmare if there is large number of optional parameters.
3.    User has to be very careful while passing the constructor arguments. Interchanging values may not give a compile-time error but can cause misbehaviors during runtime.
4.    Pattern is hard to read and write.

Consider using Builder pattern instead of Telescopic pattern in these situation.

Written by Aneesh

December 23rd, 2009 at 2:41 pm