liveBook · Manning

Shallow immutability

As explained in Data-Oriented Programming in Java

Shallow immutability is a condition in which an object's own fields cannot be changed while objects reachable through its references may still be mutable.

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

How Data-Oriented Programming in Java covers it

How deep it goes
Explains aliasing, defensive copying, immutable wrappers, and the remaining mutability of wrapped objects.
Examples
Uses Person records, mutable friends lists, List.copyOf, ImmutableList, and a PastDue wrapper around Invoice.
What it assumes
Assumes familiarity with Java records, references, lists, and mutation while demonstrating value semantics from concrete examples.
What you can do after
Build defensive record boundaries with List.copyOf or an immutable collection wrapper, and recognize when nested identity remains mutable.
How it connects
Connects records with value semantics, immutable data, defensive copying, collections, and wrapper types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming in Java. The section links point to the parts of the book it draws on.