SyntaxHighlighter JS


Builder Pattern: Too many constructor parameters

A class has too many parameters in the constructor. For example,

    new VitalSign(98, 120, 80, 42, 23); 

  • Difficult to remember what each parameter represents. Problem exacerbated with increasing parameters.  Putting wrong value for parameter is a common cause of bugs.
  • No way to define optional parameters.
  • Adding new parameters mean creating another constructor or adding another parameter to an existing constructor.
Use the Builder pattern.
Assume temperature is the only required vital sign.

public class VitalSign {
    private final int temperature;
    private final int systolic;

    private final int diastolic;
    private final int pulse;
    private final int respiratoryRate;

    private VitalSign(Builder b) {
       this.temperature = b.temperature;
       this.systolic = b.systolic;
       this.diastolic = b.diastolic;
       this.pulse = b.pulse;
       this.respiratoryRate = b.respiratoryRate;

       // Put any state validation logic here and throw
       // IllegalStateException if violated


    public static class Builder {
        // Required
        private final int temperature;

       // Optional with defaults
       private int systolic = -1;
       private int diastolic = -1;
       private int pulse = -1;
       private int respiratoryRate = -1;

       public Builder(final int temp) {
           this.temperature = temp;

       public Builder systolic(final int val) {
           this.systolic = val;
           return this;

       public Builder diastolic(final int val) {
           this.diastolic = val;
           return this;

       public Builder pulse(final int val) {
           this.pulse = val;
           return this;

       public Builder respiratoryRate(final int val) {
           this.respiratoryRate = val;
           return this;

       public VitalSign build() {
           return new VitalSign(this);

To use,

    new VitalSign.Builder(98).pulse(42).

  • Construction code easy to understand.
  • VitalSign class is immutable.  No setters.
  • method can throw an IllegalStateException if state validation fails.  For example, if there is a systolic value but not a diastolic or if temperature is greater than 130.

No comments:

Post a Comment