Value semantics make an entity behave like a description rather than an identity with a current state. Equality follows its contents, and change is excluded by design. Java collections can take either role: mutable lists act as identity objects, while unmodifiable collections behave as values when their elements are values. section 2.2.2
The important design choice is making that intention visible in code. final prevents reassignment, records provide compact value-oriented wrappers, and constructors can transform incoming data so mutable references cannot quietly change the value later. section 2.2.3 section 2.6.2
Apply value semantics by checking the entire path from construction to use:
- Choose whether each object should represent identity or a stable value; Java’s mutable-by-default APIs make accidental identity easy. section 2.2.2
- Use unmodifiable collections or List.of, Set.of, and Map.of where the collection itself must not change. section 2.2.2
- Protect nested data: a record containing List remains shallowly immutable unless construction copies or wraps the incoming list. section 2.6.2
- Use final while establishing semantic discipline, then rely on records and naturally immutable structures as the design matures. section 2.2.3 section 2.9
Defending a record from a mutable list
A record that accepts List<String> can be changed through the caller’s original reference. A compact constructor closes that aliasing path: record Person(String name, List<String> friends) { Person { friends = List.copyOf(friends); } }. The person now retains its original friends even if the caller later modifies its list. section 2.6.2
Listing 2.37 Using the compact constructor to enforce invariants
record Person(String name, List<String> friends){
Person {
friends = List.copyOf(friends); #A
}
}Inspect the compact-constructor pattern that enforces value semantics at construction time. section 2.6.2
