Video in progress

What contract do you set between modules for stream results and immutable collections? When is a defensive copy needed?

The agreement: public methods return unmodifiable collections (toList(), List.copyOf), and a collection that is received is copied before it is stored inside. That makes bugs about who modified whose list disappear. The cost is allocation, but it is usually unnoticeable.

📖 Answer

A large share of collection bugs come from "shared mutable state": a service returns its internal list, the caller does add on it, and the service's state silently changes. Or the reverse: a list passed to a constructor is later modified outside.

The contract I set:

public record Cart(List<Item> items) {
    public Cart {
        items = List.copyOf(items);   // a copy on the way in; a null element means an immediate NPE
    }
}

public List<Item> activeItems() {
    return items.stream().filter(Item::active).toList();   // can't be modified
}

Subtle points:

  • Collections.unmodifiableList(list) is a view, not a copy. If the original list changes, the view changes too. For a contract, List.copyOf is more reliable.
  • List.copyOf doesn't copy if the argument is already immutable, so it's free.
  • toList() allows null, while List.copyOf and Collectors.toUnmodifiableList don't. Two different behaviors in one project cause confusion; pick one for the team.
  • If the elements themselves are mutable (a List<Order> and Order has setters), an immutable list is only half the protection. The real benefit comes when you use it together with records and immutable DTOs.

About the cost: a copy is O(n) plus allocation. On a hot path, with a list of millions of elements, this can be noticeable: there you can work with mutable inside the module and copy only at the boundary. But in ordinary service code this cost is invisible next to the network and the DB, while the protection against bugs is very large.

To enforce it: concrete types like ArrayList and HashMap aren't returned from public APIs (ArchUnit), Error Prone checks like MutablePublicArray, and the question "who can modify this list?" in code review.