Question
What is the meaning of "shallowly immutable" in the context of Java 14 Records?
Answer
In Java 14, Records represent a new class type introduced for modeling immutable data structures. The term "shallowly immutable" refers to how the immutability of Records is enforced, affecting only their top-level fields. This means that while the fields of a Record themselves cannot be modified, if those fields reference mutable objects, the state of those objects can still be changed. Thus, the immutability is not absolute but rather applies to the references held by the Record, not the underlying objects.
record Person(String name, List<String> hobbies) {
public Person {
// Defensive copy to maintain immutability.
hobbies = List.copyOf(hobbies);
}
}
Causes
- Records contain fields that might reference mutable objects, allowing those objects to change despite the Record itself being immutable.
- Constructors of Records cannot enforce deep immutability unless additional measures are taken during object construction.
Solutions
- To ensure deep immutability, use only immutable objects as fields within a Record, or create defensive copies of mutable objects in the Record's constructor.
- Consider using immutable collections, such as `List.of()` or `Set.of()`, when you need to include collections in your Records.
Common Mistakes
Mistake: Assuming Records are deeply immutable by default.
Solution: Always validate the types of fields in your Record and use immutable types where needed.
Mistake: Modifying mutable objects referenced by a Record after instantiation.
Solution: Avoid using mutable objects or always create defensive copies when passing mutable objects to a Record.
Helpers
- Java 14 Records
- shallowly immutable definition
- Java immutability
- Record class Java
- mutable objects in Java Records