Video in progress

Strong Junior 🧭 Design patterns

How do you prevent required fields from being forgotten when you use a Builder?

The simplest way is to validate in build() and throw an exception with a clear message if something is missing. Stronger options: make the required fields arguments of builder(...), or enforce them at compile time with a "step builder".

📖 Answer

The problem: a builder lets you call it in any order and without any field, and the null gets thrown much later, deep inside, as an NPE.

Option 1, validation in build():

public Payment build() {
    Objects.requireNonNull(amount, "amount majburiy");
    Objects.requireNonNull(currency, "currency majburiy");
    if (amount.signum() <= 0) throw new IllegalArgumentException("amount > 0 bo'lishi kerak");
    return new Payment(this);
}

The error comes right where the object is created, which makes debugging much easier.

Option 2, ask for the required ones when entering the builder:

Payment.builder(amount, currency)
       .description("Obuna")
       .build();

Option 3, a step builder: builder() returns an interface that only has .amount(), which returns one that only has .currency(), and so on. If you skip a required step, the code doesn't compile. It's powerful but takes a lot of code, so it's usually only worth it for a public library API.

Lombok's @Builder does none of this by itself, so in important places you need to fill in build() by hand or validate in the constructor.