Monday, November 1, 2010

Replace Telescoping Constructor With Builder

Traditionally, when faced with a class that necessitates a large number of constructor parameters, programmers have utilized the telescoping constructor pattern, creating constructors with increasing numbers of parameters. This practice, however, does not scale well and can also be very difficult and confusing to interpret when debugging. For a fairly small example, HIPAA (Health Insurance Portability and Accountability Act) transaction data can be stored in database tables with no less than five values representing its distinct key. Following the pattern mentioned previously, you might end up with something like this to construct one of these key objects:
public HIPAAKey(String loopId, String segmentId, int segmentSequenceId,
int loopSequenceCount, int providerSubmittedLineNumber){...}

The call to this constructor then might look something like this:
new HIPAAKey("2010BA", "HI", 1,  2,  3);

Even if you are familiar with the constructor and its parameters, it can become laborious trying to keep track of which attribute is represented by each value.

A better solution would be to create a builder object which is passed to the constructor as the single parameter. In this case, the builder might look like this:

public static class HIPAAKeyBuilder {
private String loopId;
private String segmentId;
private int segmentSequenceId;
private int loopSequenceCount;
private int providerSubmittedLineNumber;

public HIPAAKeyBuilder() {}

public HIPAAKeyBuilder loopId(String loopId){
this.loopId = loopId;
return this;
}

public HIPAAKeyBuilder segmentId(String segmentId){
this.segmentId = segmentId;
return this;
}
//continue until all key values have similar methods, each
//returning the current instance of the object
....
}

Now, when you need to construct a new key, you chain calls to the builder pattern like this:

new HIPAAKeyBuilder().loopId("2010BA").segmentId("HI").segmentSequenceId(1).
loopSequenceCount(2).providerSubmittedLineNumber(3);

Then, you simply pass this as the parameter to the HIPAAKey constructor. This makes both constructing these key objects and debugging them much more clear.

No comments:

Post a Comment