Java / Java 21 Coding Standards Interview Questions
Why should you prefer immutable records over mutable classes for DTOs?
A mutable DTO can be modified after it is handed off - passed into a method, stored in a cache, or shared across threads - meaning the object a caller holds a reference to may no longer represent what it originally received, which is a frequent source of hard-to-trace bugs.
public record CustomerDto(String id, String name, String email) {} // any "change" produces a new instance via a wither or a new record literal
An immutable record eliminates that class of bug entirely: once constructed, its fields cannot change, so any two threads or callers holding a reference to the same instance are guaranteed to see the same values for its entire lifetime, with no defensive copying required.
DTOs also rarely have behavior beyond carrying data between layers - a service, a controller, a serializer - which is exactly the transparent-carrier use case records were designed for, so the two-field win of correctness and boilerplate reduction applies almost without exception.
More Related questions...