defensive copy
A copy of a mutable object, such as a list, made when it crosses a boundary so the other side cannot change your data.
In more detail
If a method returns its internal list, a caller can alter your state without going through any domain rule. Returning a copy, for example with List.copyOf, gives the caller its own unmodifiable collection. Decide and document who owns each mutable collection.
Example
return List.copyOf(items);Related terms
- unmodifiable view — A wrapper around a collection that rejects writes but still shows changes the owner makes to the underlying collection.
- mutable state — Data that can change after it is created, such as a field that is reassigned or a list that is added to.
- immutable — Something that cannot be changed after it is created; to change it you make a new one.
Taught in
- The Collections Framework — Modern Java: Virtual Threads & High-Throughput Services