Telescoping

Lets have a look at the constructor below

public class Car {
  int modelYear;
  String modelName;
  String color;
  String manufacturer;
  double sellingPrice;
  String carType;
  Boolean isLuxury;
  Boolean isImported;
  String countryOfManufacture;

  public Car(int modelYear) {
    this.modelYear = modelYear;
  }

  public Car(int modelYear, String modelName) {
    this(modelYear);
    this.modelName = modelName;
  }

  public Car(int modelYear, String modelName, String color) {
    this(modelYear, modelName);
    this.color = color;
  }

  public Car(int modelYear, String modelName, String color, String manufacturer) {
    this(modelYear, modelName, color);
    this.manufacturer = manufacturer;
  }

...

  public Car(int modelYear, String modelName, String color, String manufacturer, double sellingPrice, String carType, Boolean isLuxury, Boolean isImported, String countryOfManufacture) {
    modelYear = modelYear;
    modelName = modelName;
    ...
  }
}

It just looks ugly. And if you were to look at this code, you could figure out it wasn’t the work of an Amateur programmer. This is one of those things which make you wonder why doesn’t my code look clean and professional (Feel me?)

Believe it or not, there’s a term for it - it’s called Constructor Telescoping. When you load your constructor with a shit ton of parameters, it makes the code look ugly. I, myself have done it many times, and now that I know there’s something I can do to avoid it - I am not going down this ugly lane anymore.

Builder Pattern

If you ever used the StringBuilder in Java - that’s an example of the Builder pattern. Today, we’re going to create our very own Builder class! Hang Tight!

Java Beans Crash Course

Rules for a class to qualify as a “Java Bean” :

  1. The class must have a public default constructor (with no arguments).
  2. Must have a shit ton of getters and setters
  3. The class should be serializable. (implements java.io.Serializable)

So to make our Car class a Java Bean, we just have to change it to look like this:

    public class Car {
        private int modelYear;
        private String modelName;
        private String color;
        private String manufacturer;
        private double sellingPrice;
        private String carType;
        private Boolean isLuxury;
        private Boolean isImported;
        private String countryOfManufacture;

        /** No-arg constructor (takes no arguments). */
        public Car() { }

        public getModelYear(){
            return modelYear;
        }

        public setModelYear(int year){
            modelYear = year;
        }

        ...
        ...


    }

There are two obvious problems here:

  1. Lack of Immutability - Thread safety is a problem
  2. We The People worth of setters and getters and yet it’s hard to enfore combination rules (eg; A Car must have a manufacturer and a modelName!

To get around that, we could resort to having multiple Telescoped Constructors (and miss out on having all permutations, and get an even uglier looking code), or, we could just learn the Builder Pattern (finally! )

Builder Pattern

Now lets have a one mile overview of the code above, because right now - it looks pretty daunting.

One Mile View

Alright, so what did we just achieve with making our code look scarier?

All Cars built will require a manufacturer and a model name

Observer how IDE shows a red mark below Car.builder

IDE Code Check

You can play with rest of the permutations cleanly, while keeping the immutability (and thus thread safety)

Car Demo

Build A Space Shuttle

// "static void main" must be defined in a public class.
class SpaceShuttle {
    public String engine;
    public String cockpit;
    
    static class Builder {
        private String engine;
        private String cockpit;
        
        Builder(String engine){
            this.engine = engine;
        }
        
        Builder engine(String engine){
            this.engine = engine;
            return this;
        }
        Builder cockpit(String cockpit){
            this.cockpit = cockpit;
            return this;
        }
        
        SpaceShuttle build(){
            return new SpaceShuttle(this);
        }
    }
    
    private SpaceShuttle(Builder b){
        this.engine = b.engine;
        this.cockpit = b.cockpit;
    }
}

public class Main {
    public static void main(String[] args) {
        SpaceShuttle.Builder sb = new SpaceShuttle.Builder("RS-25");
        sb.engine("RS-25").cockpit("C101");
        SpaceShuttle Titan = sb.build();
        System.out.println(Titan); // SpaceShuttle@c818063
        System.out.println(Titan.engine); // RS-25
        System.out.println(Titan.cockpit); // C101
    }
}

Feeling generous ? Help me write more blogs like this :)


Feeling even more generous ?

$20 can feed a poor child for a whole year. Akshaya Patra (Aak-sh-ayah pa-tra) is the world’s largest NGO school meal program, providing hot, nutritious school lunches to over 1.8 million children in 19,257 schools, across India every day. Your 20$ makes all the difference.