Sub topic 6
Normalizing and checking state in compact constructors
This chapter assumes you know basic Java record syntax, which the previous chapter covers. It also assumes you can write a Spring Boot @RestController and have seen Bean Validation annotations such as @NotBlank. You need Java 17 or later.
A record's constructor is the one place where every instance passes through, whether Jackson creates it from JSON, your mapper builds it from an entity, or a test calls it directly. That makes it a good place to clean up input and to reject values that can never be valid. It is also easy to misuse. This chapter covers what a compact constructor can do, what it cannot, and how it fits with Bean Validation.
What a compact constructor is
Every record has a canonical constructor, which takes one parameter per component. If you don't write it, the compiler generates one that assigns each field. You can write it out in full, or you can use the compact form, which has no parameter list:
public record Point(int x, int y) {
// Compact form: no parameter list, no field assignments
public Point {
if (x < 0 || y < 0) {
throw new IllegalArgumentException("coordinates must not be negative");
}
}
}The compact body runs first. When it finishes, the compiler appends the assignments this.x = x; this.y = y; for you. Inside the body, x and y are the constructor parameters, not the fields. That detail explains most of the rules below.
- You can read and reassign the parameters. The new values are what end up in the fields.
- You cannot write
this.x = x. The compiler rejects direct field assignment in a compact constructor. - You cannot use
return. Leaving early would skip the field assignments. - The constructor must be at least as accessible as the record. A
publicrecord needs apubliccompact constructor. - You can throw exceptions. This is how you reject invalid state.
Normalizing input
Normalizing means converting equivalent inputs to one canonical form. For DTOs this is mostly trimming whitespace and fixing case. Reassign the parameters before the fields are set:
public record CreateUserRequest(String name, String email) {
public CreateUserRequest {
name = name == null ? null : name.strip();
email = email == null ? null : email.strip().toLowerCase();
}
}Two things matter in this example.
First, the null checks are required. If a client omits email from the JSON body, Jackson passes null to the constructor. The constructor runs before Bean Validation, so a @NotBlank annotation has not had a chance to reject the value yet. Without the null check you would get a NullPointerException and a confusing error instead of a clean validation message. The normalizer should leave null alone and let validation decide whether null is acceptable.
Second, toLowerCase() uses the default locale. In a Turkish locale, "I".toLowerCase() produces a dotless ı. For identifiers such as emails, pass Locale.ROOT:
email = email == null ? null : email.strip().toLowerCase(java.util.Locale.ROOT);Because normalization happens in the constructor, the normalized values are what equals, hashCode, toString, and the accessors see. Two requests that differ only in whitespace or case become equal. This is a real benefit, and it also means the original input is gone. If you need to log or echo what the user actually typed, normalize somewhere else.
What to normalize, and what to leave alone
Only normalize things that are not meaningful. Trimming a name is safe. Trimming a password is not, because leading spaces may be part of it. Lowercasing an email's domain is safe, and lowercasing the local part is a policy decision that some mail systems would disagree with. Treat each normalization as a contract with your clients, and document it.
Checking invariants
An invariant is a condition that must hold for every instance. Compact constructors suit invariants that involve a single value or several components together, which annotations express poorly:
import java.time.LocalDate;
import java.util.Objects;
public record DateRange(LocalDate from, LocalDate to) {
public 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 (" + to + ") must not be before from (" + from + ")");
}
}
public static void main(String[] args) {
DateRange ok = new DateRange(LocalDate.of(2026, 1, 1), LocalDate.of(2026, 1, 31));
System.out.println(ok);
try {
new DateRange(LocalDate.of(2026, 2, 1), LocalDate.of(2026, 1, 1));
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}Running this prints the valid range, then the rejection message. A cross-field rule like "end not before start" is the typical case. You can express it with a custom class-level Bean Validation constraint, but a constructor check is shorter and can never be skipped.
How constructor failures surface in Spring MVC
The constructor runs at a different time than Bean Validation, and the two failures reach the client differently.
When your constructor throws, Jackson wraps the exception and Spring MVC reports an HttpMessageNotReadableException. By default that is a 400 response with a generic body that does not name the field. When a constraint such as @NotBlank fails, Spring raises MethodArgumentNotValidException, which carries a list of field errors you can turn into a structured response.
This difference drives a practical rule. Use Bean Validation for errors the client should fix field by field. Use constructor checks for conditions that indicate a malformed or impossible object. The table summarizes the choice.
| Rule | Put it in | Reason |
|---|---|---|
| Trim and lowercase text | Compact constructor | Must happen before equality and validation see the value |
| Defensive copy of a collection | Compact constructor | Only the constructor can guarantee it for every instance |
| Field is required, size limit, email format | Bean Validation annotations | Gives field-level error messages |
| Start date must precede end date | Compact constructor, or a class-level constraint | Spans multiple components |
| Value must exist in the database | Service layer | The DTO should not call repositories |
The last row is worth stressing. A constructor should be pure: no I/O, no static lookups, no time or randomness. Records are created in many places, including tests and mappers, and a constructor with side effects makes all of them harder to reason about.
Using both together
Normalization and annotations combine well. The constructor cleans the value, and the annotations then check the cleaned value, because validation runs on the finished object:
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.Locale;
public record RegisterRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email) {
public RegisterRequest {
name = name == null ? null : name.strip();
email = email == null ? null : email.strip().toLowerCase(Locale.ROOT);
}
}With this record, a name of " " is stripped to an empty string and then rejected by @NotBlank. The client receives a normal field error for name. An email of " [email protected] " is stored as [email protected] and passes @Email. Without the normalization, the name " " would still fail @NotBlank, but a 51-character name padded with spaces could pass or fail @Size depending on where the padding sat.
Defensive copies of collections
A record holding a List holds a reference to whatever list the caller passed. If the caller keeps that list and changes it later, the record changes too. A compact constructor fixes this by copying:
import java.util.List;
public record OrderRequest(String customerId, List<String> itemIds) {
public OrderRequest {
itemIds = List.copyOf(itemIds);
}
}List.copyOf returns an unmodifiable copy. It has two behaviors you need to know:
- It throws
NullPointerExceptionif the list itself isnull. - It throws
NullPointerExceptionif any element isnull.
For a request DTO, a missing itemIds property reaches the constructor as null, so this record answers a missing field with an NPE rather than a validation error. If you want a missing list treated as empty, write that explicitly:
public OrderRequest {
itemIds = itemIds == null ? List.of() : List.copyOf(itemIds);
}If a missing list should be an error, say so with a clear message instead of relying on the NPE:
public OrderRequest {
Objects.requireNonNull(itemIds, "itemIds must not be null");
itemIds = List.copyOf(itemIds);
}Use Set.copyOf and Map.copyOf for sets and maps. Set.copyOf silently drops duplicates. Map.copyOf throws NullPointerException on null keys or values. The copy is also shallow: the elements themselves are not copied, so a list of mutable objects can still change. The chapter on immutability limits returns to this.
Providing defaults with a custom non-canonical constructor
A compact constructor cannot change which parameters exist. When you want a convenience form, add a separate constructor that delegates to the canonical one:
public record PageRequestDto(int page, int size) {
public PageRequestDto {
if (page < 0) {
throw new IllegalArgumentException("page must be 0 or greater");
}
if (size < 1 || size > 100) {
throw new IllegalArgumentException("size must be between 1 and 100");
}
}
public PageRequestDto() {
this(0, 20);
}
}Any additional constructor must start with this(...). Be careful with Jackson here. Recent Jackson versions find the canonical constructor of a record without annotations, but if you add several constructors you rely on that detection. Keep records used as request bodies simple, and apply defaults in the canonical constructor when you can.
Common mistakes
- Assigning fields. Writing
this.name = name.strip();in a compact constructor is a compile error. Reassign the parameter instead:name = name.strip();. - Forgetting null. Missing JSON properties arrive as
nullfor reference types and as0orfalsefor primitives. A primitiveint agecannot tell "missing" from "zero", so useIntegerwhen absence matters, and add@NotNull. - Strict constructors on response records. Mappers like
UserResponse.from(user)and Spring Data projections also call your constructor. If a response record rejects a value that legacy rows in the database contain, a read endpoint fails with a 500. Keep response records lenient and put strict rules on request records. - Doing work in the constructor. Calling a service, reading a clock, or logging at high volume turns a data carrier into something with behavior. Do that work in the service layer.
- Duplicating rules. If the constructor throws on
size > 100and an annotation also says@Max(100), clients see two different error shapes for one mistake. Pick one place per rule.
Exercise
A client sends {"email": null} to an endpoint whose request record is record SignupRequest(@NotBlank String email) { public SignupRequest { email = email.strip().toLowerCase(); } }. What happens, and how do you fix the record so the client gets a normal field error for email?
Show answer
The constructor runs before Bean Validation, so email.strip() is called on null and throws NullPointerException. Jackson wraps it and the client gets a generic 400 with no field information (or a 500 if the exception is not wrapped). Fix it by making the normalization null-safe: email = email == null ? null : email.strip().toLowerCase(Locale.ROOT);. The constructor then passes null through, and @NotBlank rejects it with a field-level error.
Exercise
Write a compact constructor for record Coupon(String code, List<String> productIds) that uppercases and strips code (leaving null alone), treats a null productIds as an empty list, and makes the list unmodifiable.
Show answer
public Coupon { code = code == null ? null : code.strip().toUpperCase(java.util.Locale.ROOT); productIds = productIds == null ? java.util.List.of() : java.util.List.copyOf(productIds); }
Exercise
Why is a rule such as "the username must not already exist" a bad fit for a compact constructor?
Show answer
It needs a database lookup. Constructors should be pure because records are created by Jackson, mappers, projections, and tests. A lookup in the constructor would make all of them depend on a repository and would run on every instantiation. Put the check in the service layer, where the transaction and the repository live.