Video in progress
How do you write an immutable class?
Make the class final, make all fields private final, provide no setters, and make defensive copies of mutable fields (a list, an array, a Date) in the constructor and in the getter. "Modifying" methods should return a new object.
📖 Answer
public final class Order {
private final long id;
private final List<String> items;
private final Instant createdAt;
public Order(long id, List<String> items, Instant createdAt) {
this.id = id;
this.items = List.copyOf(items); // if the outside list changes, ours doesn't
this.createdAt = createdAt; // Instant is immutable itself
}
public List<String> items() { return items; } // List.copyOf: can't be modified
public Order withItem(String item) {
var copy = new ArrayList<>(items);
copy.add(item);
return new Order(id, copy, createdAt);
}
}
Why each step matters:
- a
finalclass: a subclass can't add mutable state; private final: a field is assigned once;- a defensive copy: otherwise the caller can change the list it passed in later and break the object's insides;
Instant/LocalDateinstead ofjava.util.Date: they're immutable.
The benefits: it's thread-safe, safe as a HashMap key, easy to cache, and simpler to reason about.
In many cases a record plus List.copyOf in the constructor gives the same result with less code.
Sign up to mark studied questions and save your progress.