Video in progress
Where should you check invariants in the Builder pattern, and what trap does Lombok's `@Builder` set here?
The check has to be in build() or in the constructor it calls, so an invalid object is never born. Lombok's @Builder checks nothing by default, and if you forget a required field it silently leaves null.
📖 Answer
A typical case with Lombok:
@Builder
public class Transfer {
private final AccountId from;
private final AccountId to;
private final Money amount;
}
Transfer t = Transfer.builder().from(a).amount(m).build(); // to == null, no error
The error shows up later, maybe on another thread or when writing to the database, and it's not obvious where it came from.
The fix is to put validation in a constructor and apply @Builder to the constructor:
public class Transfer {
private final AccountId from;
private final AccountId to;
private final Money amount;
@Builder
private Transfer(AccountId from, AccountId to, Money amount) {
this.from = Objects.requireNonNull(from, "from");
this.to = Objects.requireNonNull(to, "to");
this.amount = Objects.requireNonNull(amount, "amount");
if (from.equals(to)) throw new IllegalArgumentException("o'z hisobiga o'tkazma");
if (!amount.isPositive()) throw new IllegalArgumentException("summa > 0 bo'lishi kerak");
}
}
Now build() calls this constructor and an invalid Transfer can't be created.
More traps:
@Builder+@NoArgsConstructor+ setters: the invariant is open again;@Builder.Defaulttreats the field initializer differently:new Transfer()andbuilder().build()may give different defaults (depending on the Lombok version);toBuilder = truecreates a copy, but innerLists are copied shallowly.
If there are many required fields, you often don't need a builder at all: a plain constructor or a static factory (Transfer.of(from, to, amount)) is clearer, and the compiler checks the number of arguments.
Sign up to mark studied questions and save your progress.