Duplicate Code? Chain Constructors

Posted on Monday, September 27, 2010

0


After the ‘Introduction of Null Object’ and the ‘Replace One/Many Distinctions with Composite’ let us do an easy one this time. It is easy but of course it is present in a lot of code samples else we would not be discussing it here. If there are a lot of constructors which have duplicate code then see if there is a reasonable possibility to chain them.

By chaining we mean that one constructor calls the other and so on.

For example is one of our projects for a fraud management system using complex event processing we had an alert type called ScoreAlert

Following are 3 of the many constructors that it had

public ScoreAlert(ScoreType type, float average, int rating, Date expiry) {
	this.type = type;
	this.average=average;
	this.rating = rating;
	this.expiry = expiry;
}
public ScoreAlert( ScoreType type, float average, int rating, Date expiry, Date maturity) {
	this.level=AlertLevel.HIGH;
	this.type = type;
	this.average=average;
	this.rating = rating;
	this.expiry = expiry;
	this.maturity = maturity;
}
public ScoreAlert(AlertLevel level, ScoreType type, float average, int rating, Date expiry, Date maturity) {
	this.level = level;
	this.type = type;
	this.average=average;
	this.rating = rating;
	this.expiry = expiry;
	this.maturity = maturity;
}

now in order to remove duplication one of the ways is to chain the constructors such that one constructor calls the other.

After chaining we have something like this,

public ScoreAlert(ScoreType type, float average, int rating, Date expiry) {
	this(null, type,average, rating, expiry, null)
}

public ScoreAlert(ScoreType type, float average, int rating, Date expiry) {
	this(AlertLevel.HIGH, type,average, rating, expiry, maturity)

}

public ScoreAlert(AlertLevel level, ScoreType type, float average, int rating, Date expiry, Date maturity) {
	this.level = level;
	this.type = type;
	this.average=average;
	this.rating = rating;
	this.expiry = expiry;
	this.maturity = maturity;
}

This makes it easier to add new attributes to the class, which would otherwise have to be repeated endlessly in all the constructors. Whenever you have a code like this, We often accomplish this refactor it with constructor chaining.
The concept is simple, specific constructors call more general-purpose constructors until a final constructor is reached. If you have one constructor at the end of every chain, it is a catch-all constructor because it handles every constructor call. A catch-all constructor often accepts more parameters than other constructors.

Another way to handle the problem of multiple constructors is with the use of Builder pattern. Any idea how to do that? We will come to that soon.

About these ads
Posted in: Agile, Java