Video in progress

Strong Middle 🧱 OOP and SOLID

How do you choose between a telescoping constructor, a static factory and a builder for an object with many parameters?

With up to 3-4 required parameters, a constructor or a named static factory. With many optional parameters, a builder. A static factory has a name, can cache, and can return a subtype; a builder assembles the object step by step in a readable way.

📖 Answer

Telescoping constructors:

new Notification(user, "Salom");
new Notification(user, "Salom", Channel.SMS);
new Notification(user, "Salom", Channel.SMS, true, null, 3);

In the last one, what are true and 3? If you swap two parameters of the same type, the compiler says nothing.

A static factory: the name gives it meaning:

Money.ofTiyin(1500);
Money.zero(Currency.UZS);
Duration.ofMinutes(5);
List.of();          // always the same empty object: caching

How it differs from a constructor: it has a name, it doesn't have to create a new object every time, and it can return an interface or a subtype (EnumSet.of returns an internal RegularEnumSet or JumboEnumSet).

A builder is for when there are many optional parameters:

var n = Notification.builder()
        .to(user)
        .text("Salom")
        .channel(Channel.SMS)
        .retries(3)
        .build();     // validation happens here, in one place

The subtle points of builders:

  • required fields can be forgotten, so check them in build() or pass the required ones as arguments to builder(user, text);
  • Lombok's @Builder works well with records or immutable classes, but without @Builder.Default the field initializers are ignored, which is a classic trap;
  • a builder in a hierarchy (with inheritance) is complicated and needs @SuperBuilder or a generic self-type.

For records, a compact constructor plus a few static factories is often enough, and a builder is overkill.