Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Implementing NestedBuilder

DZone's Guide to

Implementing NestedBuilder

If you're working with the Builder Pattern, you might find your relations growing complex. The NestedBuilder class lets proxies serve as parents and children at the same time.

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

While working with the Builder Pattern, you will come to the point when you have to build up complex objects. Suppose we would like to create "Car." It consists of attributes like engine, machine, and a number of wheels. For this purpose, we use the following class model.

public class Car {
    private Engine engine;
    private List<Wheel> wheelList;
}

public class Engine {
    private int power;
    private int type;
}

public class Wheel {
    private int size;
    private int type;
    private int colour;
}


Now it is possible to generate a corresponding Builder for each class. If you adhere to the basic pattern it will look like this for the class Wheel:

public static final class Builder {
     private int size;
     private int type;
     private int colour;

     private Builder() {}

     public Builder withSize(int size) {
         this.size = size;
         return this;
     }

     public Builder withType(int type) {
         this.type = type;
         return this;
     }

     public Builder withColour(int colour) {
         this.colour = colour;
         return this;
     }

     public Wheel build() {
         return new Wheel(this);
     }
 }


The Builder is implemented as an inner static class and, thus, it makes modifications in the class Wheel, which allows one to use only the Builder to create an instance. Of course, here I have omitted the option via reflection.

public class Wheel {

    private int size;
    private int type;
    private int colour;

    private Wheel(Builder builder) {
        setSize(builder.size);
        setType(builder.type);
        setColour(builder.colour);
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static Builder newBuilder(Wheel copy) {
        Builder builder = new Builder();
        builder.size = copy.size;
        builder.type = copy.type;
        builder.colour = copy.colour;
        return builder;
    }
...}


But what does it look like if we want to create an instance of the class Car? Here we come to the point when we have to add the instance of the class Wheel to the instance of the class Car.

public class Main {
  public static void main(String[] args) {

    Engine engine = Engine.newBuilder().withPower(100).withType(5).build();

    Wheel wheel1 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel2 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel3 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();

    List<Wheel> wheels = new ArrayList<>();
    wheels.add(wheel1);
    wheels.add(wheel2);
    wheels.add(wheel3);

    Car car = Car.newBuilder()
                 .withEngine(engine)
                 .withWheelList(wheels)
                 .build();

    System.out.println("car = " + car);
  }
}


This source code is not particularly well-done and in no way compact. So how can one adjust the Builder Pattern in order to manually write as little of the Builder source code as possible and to have more convenience when using it? WheelListBuilder Let's take a small detour. For example, to ensure, that only four wheels can be added to Car, you can create a WheelListBuilder. Here you can check in the method build() if four instances of the class Wheel are available.

public class WheelListBuilder {

    public static WheelListBuilder newBuilder(){
      return new WheelListBuilder();
    }

    private WheelListBuilder() {}

    private List<Wheel> wheelList;

    public WheelListBuilder withNewList(){
        this.wheelList = new ArrayList<>();
        return this;
    }
    public WheelListBuilder withList(List wheelList){
        this.wheelList = wheelList;
        return this;
    }

    public WheelListBuilder addWheel(Wheel wheel){
        this.wheelList.add(wheel);
        return this;
    }

    public List<Wheel> build(){
        //test if there are 4 instances....
        return this.wheelList;
    }

}


Now our example is as follows:

public class Main {
  public static void main(String[] args) {

    Engine engine = Engine.newBuilder().withPower(100).withType(5).build();

    Wheel wheel1 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel2 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel3 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();

//        List<Wheel> wheels = new ArrayList<>();
//        wheels.add(wheel1);
//        wheels.add(wheel2);
//        wheels.add(wheel3);

    List<Wheel> wheelList = WheelListBuilder.newBuilder()
        .withNewList()
        .addWheel(wheel1)
        .addWheel(wheel2)
        .addWheel(wheel3)
        .build();//more robust if you add tests at build()

    Car car = Car.newBuilder()
        .withEngine(engine)
        .withWheelList(wheelList)
        .build();

    System.out.println("car = " + car);
  }
}


The next step is to connect the Builder of the class Wheel to the class WheelListBuilder. The aim of it is to get a Fluent API — in order to avoid individual creation of each instance of the class Wheel and its connection via the method addWheel(Wheel w) to the WheelListBuilder. For programmers, it should look like this:

List<Wheel> wheels = wheelListBuilder
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .build();


The following thing happens here: As soon as the method addWheel() is called, a new instance of the class WheelBuilder should be returned. The method addWheelToList() creates the instance of the class Wheel and adds it to the list. To achieve it, one has to modify both Builders involved. On the side of the WheelBuilder, the method addWheelToList() is added. This method adds the instance of the class Wheel to the WheelListBuilder and returns the instance of the class WheelListBuilder.

private WheelListBuilder wheelListBuilder;

public WheelListBuilder addWheelToList(){
  this.wheelListBuilder.addWheel(this.build());
  return this.wheelListBuilder;
}


On the side of the class WheelListBuilder, only the method addWheel() is added.

public Wheel.Builder addWheel() {
  Wheel.Builder builder = Wheel.newBuilder();
  builder.withWheelListBuilder(this);
  return builder;
}


If we apply this to the other Builder, we will get a quite considerable result:

Car car = Car.newBuilder()
    .addEngine().withPower(100).withType(5).done()
    .addWheels()
      .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
      .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
      .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .done()
    .build();


NestedBuilder

Up to now, the Builders were modified manually. It can be easily implemented in a generic way, i.e. in the form of a Builder tree. Thus, each Builder knows its Children and its Parent. The necessary implementation can be found in the class NestedBuilder. It is assumed here that the methods for setting attributes always begin with "with". Since it is true for the most Builder Generators, no manual adjustment is necessary.

public abstract class NestedBuilder<T, V> {
  /**
   * To get the parent builder
   *
   * @return T the instance of the parent builder
   */
  public T done() {
    Class<?> parentClass = parent.getClass();
    try {
      V build = this.build();
      String methodname = "with" + build.getClass().getSimpleName();
      Method method = parentClass.getDeclaredMethod(methodname, build.getClass());
      method.invoke(parent, build);
    } catch (NoSuchMethodException
            | IllegalAccessException
            | InvocationTargetException e) {
      e.printStackTrace();
    }
    return parent;
  }

  public abstract V build();

  protected T parent;

  /**
   * @param parent
   * @return
   */
  public <P extends NestedBuilder<T, V>> P withParentBuilder(T parent) {
    this.parent = parent;
    return (P) this;
  }
}


Now we can add to one Parent the specific methods for connecting to the Children. A derivation from NestedBuilder is not needed.

public class Parent {

  private KidA kidA;
  private KidB kidB;

  //snipp.....

  public static final class Builder {
    private KidA kidA;
    private KidB kidB;

    private Builder() {
    }

    public Builder withKidA(KidA kidA) {
      this.kidA = kidA;
      return this;
    }

    public Builder withKidB(KidB kidB) {
      this.kidB = kidB;
      return this;
    }

    // to add manually
    private KidA.Builder builderKidA = KidA.newBuilder().withParentBuilder(this);
    private KidB.Builder builderKidB = KidB.newBuilder().withParentBuilder(this);

    public KidA.Builder addKidA() {
      return this.builderKidA;
    }

    public KidB.Builder addKidB() {
      return this.builderKidB;
    }
    //---------

    public Parent build() {
      return new Parent(this);
    }
  }
}


And on the Children side, it is as follows: Here it must be derived only from NestedBuilder:

public class KidA {

  private String note;

  @Override
  public String toString() {
    return "KidA{" +
        "note='" + note + '\'' +
        '}';
  }

  private KidA(Builder builder) {
    note = builder.note;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public static final class Builder extends NestedBuilder<Parent.Builder, KidA> {
    private String note;

    private Builder() {
    }

    public Builder withNote(String note) {
      this.note = note;
      return this;
    }

    public KidA build() {
      return new KidA(this);
    }

  }
}


The usage is then very compact, as it is seen in the previous example.

public class Main {
  public static void main(String[] args) {
    Parent build = Parent.newBuilder()
        .addKidA().withNote("A").done()
        .addKidB().withNote("B").done()
        .build();
    System.out.println("build = " + build);
  }
}


Conclusion

Of course, any combination is possible. It means that a Proxy can be Parent and Child at the same time. So there is nothing else to prevent the building of the complex structures.

public class Main {
  public static void main(String[] args) {
    Parent build = Parent.newBuilder()
        .addKidA().withNote("A")
                  .addKidB().withNote("B").done()
        .done()
        .build();
    System.out.println("build = " + build);
  }
}


Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
java ,java 8 ,builder pattern ,nestedbuilder

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}