Video in progress
When designing an immutable object, how do you choose between a builder, a wither and a defensive copy?
For an object with 3–4 fields, a plain constructor or a record is enough. A builder when there are many optional fields, a wither when you need a new copy with one field changed. And I always make a defensive copy of mutable inputs (List, Date, arrays).
📖 Answer
An immutable object is thread-safe, safe as a HashMap key and easy to cache. But the way you create and "change" it decides how convenient the API is.
Defensive copy is the required minimum:
public record Route(String name, List<Stop> stops) {
public Route {
stops = List.copyOf(stops); // changes to the outside list don't affect us
}
}
List.copyOf doesn't copy an already immutable list again, so the cost is low. For Date, arrays and StringBuilder, return a copy from the getter too, or switch to immutable types like Instant and List.
A builder is for 6+ fields, mostly optional. Do the validation inside build(), otherwise a half-filled object comes out. Lombok's @Builder is convenient, but it doesn't validate: put it on a constructor if you need that.
A wither is a method like withStatus(...), and the old object doesn't change:
Order paid = order.withStatus(Status.PAID);
There is one catch: copying big objects often puts load on the GC. If there are millions of "changes" per second on a hot path, check with a profiler. In practice a modern GC collects short-lived objects cheaply, so this is rarely a real problem.
The rule: domain objects and value objects are immutable. JPA entities are controlled-mutable (meaningful methods instead of setters).
Sign up to mark studied questions and save your progress.