Video in progress
When a class returns a collection to the outside, how do you choose between a copy, an unmodifiable view and a Stream?
It is a trade-off between safety, speed and semantics: a copy is fully independent but allocates on every call; an unmodifiable view is cheap but "live"; a Stream suits one-time reading. With immutable internal state I usually take the copy once in the constructor.
📖 Answer
The problem is internal state "escaping":
public List<Item> getItems() { return items; } // the caller does clear() and breaks the invariant
The options:
-
The internal list is itself immutable (
List.copyOfin the constructor). The getter just returns it, so you need neither a copy nor a wrapper. The cleanest path for records and value objects. -
The internal list changes, but the caller only reads:
Collections.unmodifiableList(items). It is O(1), but if the caller keeps it, it sees later changes, and may get a CME on a concurrent modification. This should be written in the javadoc. -
A copy on every call:
List.copyOf(items). A thread-safe snapshot, but on a big list and a hot path it means GC pressure. On one service I saw a getter like this account for 20% of allocations in the profiler, because it was called several times per request. -
Stream<Item> items(): the caller can only iterate, can't modify, and can't hold on to it. But a Stream is used once, and if it was created under a lock, it ends outside the lock.
In a multithreaded class (a synchronized registry, say) I take the copy inside the lock and return that, since a view is dangerous here. If the internal state is a Map, Map.copyOf works the same way.
One more rule: return an empty collection, not null. List.of() creates nothing, since it is a single instance.
Sign up to mark studied questions and save your progress.