Video in progress
In a large codebase worked on by several teams, how do you roll out the rule "public APIs return only immutable collections"?
Writing the rule down in a document isn't enough: I reinforce it with static analysis (ArchUnit, Error Prone, Sonar rules), a shared helper library and a code review checklist. On old code I apply it gradually, starting with the riskiest modules.
📖 Answer
First I make the reason clear, otherwise teams will take it as an arbitrary order. The evidence is usually incidents: another module modified a returned list and corrupted data in a cache; or a CME caused by a concurrent modification.
Then three layers:
-
Convention and examples. A short ADR: domain objects and service interfaces return immutable collections with
List.copyOf/Map.copyOf; an empty result isList.of(), not null; if the caller needs to modify the returned collection, it makes its own copy. -
Automatic checks. For example, in ArchUnit it is hard to verify that records in the DTO package copy in their constructors, but a rule like "a public method must not return
ArrayList/HashMap" is easy to write:
noMethods().that().arePublic()
.and().areDeclaredInClassesThat().resideInAPackage("..api..")
.should().haveRawReturnType(ArrayList.class)
.check(classes);
Error Prone and Sonar also have ready-made rules that catch mutable static collections.
- Boundaries. In contracts between modules (DTOs generated from OpenAPI, Kafka messages), enforce immutability through the generator settings.
I state the cost openly too: copying adds allocation on hot paths. So the rule is accepted as the "default", and an exception is accepted with a comment and a benchmark.
For old code I don't change everything at once. First the rule applies only to new code (the diff), then refactoring goes module by module, starting with those that have the most incidents. At each stage I set up an alert on UnsupportedOperationException, so that if someone tries to modify an immutable collection, it shows up immediately.
Sign up to mark studied questions and save your progress.