Shallow immutability keeps an object's own fields fixed while allowing referenced objects to remain mutable. A record can therefore look like a value while still changing through an exposed collection or identity object. section 2.6.2
Use defensive boundaries when a record must preserve value semantics:
- Copy potentially mutable inputs during construction with List.copyOf, preventing later changes to the caller's list from altering the record. section 2.6.2
- Expose an immutable collection type when the model should communicate its constraints through the type system rather than hide them in a constructor. section 2.6.2
- Treat wrapping a mutable identity as a practical quarantine, while recognizing that the wrapped object can still be modified in place. section 5.4.1
A record poisoned by its list
With record Person(String name, List<String> friends), constructing a Person from Arrays.asList("Joe", "Jane") leaves the record exposed: changing friends.set(0, "Billy") changes the Person's displayed friends. Rebinding the constructor parameter with friends = List.copyOf(friends) preserves the original values. section 2.6.2
Listing 2.40 Creating immutable list types
record ImmutableList<A>(List<A> items) {
ImmutableList {
items = List.copyOf(items); #A
}
public static <A> ImmutableList<A> of(A... items) { #B
return new ImmutableList<>(List.of(items)); #B
} #B
} Inspect the ImmutableList record, which copies incoming items and provides a dedicated immutable boundary for nested collection data. section 2.6.2
