Immutability — Notes
Heuristics
- Default to immutable. Make a class mutable only when there's a reason.
- Value objects (Money, Date, IP, URL) almost always immutable.
- Entity objects (User, Account) often need controlled mutation.
- Containers passed across thread / module boundaries → immutable.
Costs
- Allocations + GC pressure.
- Awkward when you need to update one field of a 30-field object — language sugar helps (
copy(x = ...) in Kotlin, records' withers).
Language support
- Java records,
record keyword.
- Kotlin
data class val.
- Python
frozen=True dataclass; tuple, frozenset.
- C# records,
readonly struct, ImmutableList.
- Rust default-immutable;
mut is opt-in.
- Clojure / Haskell — immutable from the ground up.
Refs
- Effective Java — Item 17 (minimize mutability).
- "Out of the Tar Pit" — Moseley & Marks, 2006.
- Rich Hickey: "The Value of Values".