Sub topic 6
Normalizing and checking state in compact constructors
This chapter assumes you know basic record syntax, can write a Spring Boot @RestController, and have seen @Valid with Bean Validation annotations. It covers the compact canonical constructor: what it does, what to put in it, and what to leave to Bean Validation.
What a compact constructor is
Every record has a canonical constructor that takes one parameter per component and assigns each to its field. A compact canonical constructor lets you write only the logic that runs before those assignments. It has no parameter list, and you do not write the field assignments.
public record CreateUserRequest(String name, String email) {
public CreateUserRequest {
name = name == null ? null : name.strip();
email = email == null ? null : email.strip().toLowerCase();
}
}Inside the body, name and email are the constructor parameters, not the fields. Reassigning them changes the values that the compiler-generated code stores in the fields when the body finishes. Writing this.name = name is a compile error, because the compiler assigns the fields for you.
Where it runs in a request
Jackson deserializes a record by calling its canonical constructor. The compact body therefore runs before the object exists, and before Bean Validation sees it.
This order has two consequences:
- Normalization happens first, so constraints such as
@NotBlankand@Emailcheck the cleaned values. A name of" "becomes""afterstrip()and then fails@NotBlank. - A constructor that throws stops processing before validation starts. Spring turns the failure into an
HttpMessageNotReadableException. Bean Validation failures raiseMethodArgumentNotValidException. If you use@RestControllerAdvice, the two need separate handlers.
Two jobs: normalize and check
Use the compact constructor for two kinds of work.
Normalizing cleans the input: trimming, lowercasing, and replacing null with a default. Checking enforces rules that must hold for the record to make sense at all. The example below does both, and you can run it as a single file with java Demo.java.
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
record DateRange(LocalDate from, LocalDate to) {
DateRange {
Objects.requireNonNull(from, "from must not be null");
Objects.requireNonNull(to, "to must not be null");
if (to.isBefore(from)) {
throw new IllegalArgumentException("to must not be before from");
}
}
}
record OrderRequest(String customerId, List<String> itemIds) {
OrderRequest {
customerId = customerId == null ? null : customerId.strip();
itemIds = List.copyOf(itemIds);
}
}
public class Demo {
public static void main(String[] args) {
List<String> items = new java.util.ArrayList<>(List.of("a", "b"));
OrderRequest order = new OrderRequest(" c-42 ", items);
items.add("c");
System.out.println(order.customerId());
System.out.println(order.itemIds());
try {
new DateRange(LocalDate.of(2026, 12, 5), LocalDate.of(2026, 12, 1));
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}The output is c-42, then [a, b], then Rejected: to must not be before from. The caller's later items.add("c") does not reach the record, because List.copyOf made an unmodifiable copy.
Choosing between constructor checks and annotations
| Concern | Compact constructor | Bean Validation |
|---|---|---|
| Trim or lowercase input | Yes | No |
| Copy mutable collections | Yes | No |
| Required field, size, format | Possible, but verbose | Yes, and the response lists every violation |
| Rule across several components | Yes | Needs a custom constraint |
| Applies to records built in code or tests | Yes | Only when validated |
A good split is to keep per-field rules (@NotBlank, @Size, @Email) as annotations, so clients get all violations at once. Use the constructor for cleanup and for invariants that no valid record may break. A constructor throws on the first problem it finds.
Common errors
- Assigning to
this.field. This does not compile. Reassign the parameter instead. - Null-unsafe normalization.
name.strip()throwsNullPointerExceptionwhen the client omitsname. Guard with a null check so@NotBlankcan report it properly. - Passing
nulltoList.copyOf. It throwsNullPointerException, and also does so if the list contains a null element. Decide whether a missing list should becomeList.of()or be rejected. - Assuming a deep copy.
List.copyOfcopies the list, not the elements. If the elements are mutable, the record can still change through them. - Changing the constructor's visibility. The canonical constructor must be at least as accessible as the record itself. A
publicrecord needs apubliccompact constructor.
Exercise
A client posts {"name": " ", "email": "[email protected]"} to an endpoint whose request record strips name in a compact constructor and annotates it with @NotBlank. Which exception type does Spring raise, and why?
Show answer
MethodArgumentNotValidException. Jackson calls the constructor first, and strip() turns the name into an empty string without throwing. The record is created, and then @Valid runs Bean Validation, which finds that the stripped name violates @NotBlank.
Exercise
Why does this.itemIds = List.copyOf(itemIds); fail in a compact constructor, and what is the correct line?
Show answer
The compact form assigns the fields automatically after the body, so assigning this.itemIds is a compile error. Write itemIds = List.copyOf(itemIds); to reassign the parameter.