Video in progress
Where do you do validation: in the controller with `@Valid`, in the service, or in the domain object itself?
Each layer checks what belongs at its level. The controller checks the request format (@Valid: not blank, length, format). The domain object checks business invariants, because wherever the object is created, it must never be in an invalid state. The service checks rules that depend on other data.
📖 Answer
Three layers, three different questions:
// 1. The API boundary: is the request the right shape?
public record CreateTransferRequest(
@NotBlank String fromAccount,
@NotBlank String toAccount,
@Positive BigDecimal amount) {}
// 2. The domain: can this object exist at all?
public record Transfer(AccountId from, AccountId to, Money amount) {
public Transfer {
if (from.equals(to)) throw new IllegalArgumentException("o'z hisobiga o'tkazma");
if (!amount.isPositive()) throw new IllegalArgumentException("summa musbat bo'lsin");
}
}
// 3. The service: rules that depend on external data
if (!accounts.isActive(cmd.from())) throw new AccountBlockedException(cmd.from());
Relying on @Valid alone is a mistake: the same Transfer is also created from a Kafka consumer, a batch job or a test, where there is no @Valid. If the invariant lives in the domain object, it works on every path in.
Some checks are repeated (the amount is positive), and that is normal. The check in the API gives the user a nice 400 message, while the one in the domain is the last line of defense.
One catch: you can use Bean Validation annotations (@NotNull) inside the domain, but they only work if someone calls validator.validate(). A plain check in the constructor is more reliable.
Sign up to mark studied questions and save your progress.