Card 07/ 09

GotchaDifficulty: Advanced1 min

A Builder for an Object With Three Fields

Two classes and a chain of calls where one constructor call was clear.

A builder pays for itself when an object has many optional parts or is assembled step by step, and a builder around a short constructor only adds a class to read and keep in step. It is a common result of applying the pattern by rule, in any language: every class with a constructor gains a builder. This card shows the shape and the question that catches it.

A three-field object with and without a builder

With a buildertwo classes for one call

java
Point point = new PointBuilder()
    .x(3)
    .y(4)
    .label("start")
    .build();

PointBuilder repeats every field of Point, and adding a field means editing both.

Withoutone constructor

java
Point point = new Point(3, 4, "start");

There are three required parts, in the order every reader of a point expects.

The builder in the first form adds no validation a constructor could not do, assembles nothing across statements, and names parts that were never confusing. It also doubles the places that list the fields: PointBuilder must store each one and pass it on, so a fourth field is two edits, and forgetting the second compiles cleanly in a builder whose build() passes a default.

The question to ask is whether a call to the constructor is hard to read or hard to make correct. If a reader cannot tell what each argument is, or the object must be assembled in pieces, a builder helps. If the constructor has a handful of required parts in an expected order, it does not, and neither does the builder some tools generate for every class.