A mutable type allows an object’s state to change after creation. That change introduces identity and time, so the object no longer behaves reliably as a value. section 2.2.4
Mutability becomes especially risky when a type is intended to model a value:
- A single mutable reference can make an otherwise value-like object identity-based. section 2.2.4
- Wrapping a mutable collection in an unmodifiable view does not make the referenced elements value-like. section 2.2.4
- Records can sanitize incoming mutable references in compact constructors, alongside validation and normalization. section 2.6.1
- A mutable domain object can still be contained behind a wrapper when fully immutable modeling is unnecessary. section 5.4.1
A mutable date breaks value behavior
A Person containing a final Date still exposes mutable state: calling person.birthday().setTime(...) changes the person. If that Person is already in a HashSet, the changed equality and hash state can cause a second entry to appear. section 2.2.4
Listing 2.18 Even a single mutable addition prevents us from modeling values
class Person {
final String name;
final Date birthday; #A
public String getName(){return this.name;}
public Date getBirthday(){return this.birthday;}
// equals & hashcode, but no setters. We’re a value object!
}
final Person person = new Person("Bob", new Date()); #B
System.out.println(person);
// [out] Person[name=Bob, birthday=Sun Aug 11 22:42:57 PDT 2024] #C
person.birthday().setTime( #D
new Date().getTime() + TimeUnit.DAYS.toMillis(1) #D
); #D
System.out.println(person);
// [out] Person[name=Bob, birthday=Tue Aug 12 22:42:57 PDT 2024] #E
Inspect the listing to see how a final Date remains mutable through its accessor. section 2.2.4





