Immutability
medium 45 minAn immutable object keeps the value it was born with.
Video lesson · Chapter 1 of 6
Make a prediction
Immutability
1:04Reel
Theory
Read or listen first. About 2 min.
What it is
An immutable object has no visible change after its constructor has finished. Every field keeps its value, and everything reachable through the fields keeps its value too. A method that sounds like a change, such as plus, returns a new object.
The variable is another matter. wallet = wallet.plus(tip) makes the name wallet point at a new object. The old object is still what it was, and anybody who holds it still sees the old value. Freezing a variable (final, const) and freezing an object are two different things.
Immutability can be shallow (the fields cannot be reassigned) or deep (nothing behind the fields can change either). Only the deep kind gives the promises on this page. A frozen box that holds a normal list is a closed door in a house without a back wall.
Why it exists
Most surprising bugs need two things: sharing and change. Two parts of a program hold the same object, one of them changes it, and the other is wrong without having done anything. Remove either ingredient and the bug cannot happen. Immutability removes change, so sharing becomes free.
Threads are the strongest case. A race needs at least one writer. An object that nobody can write has no race, so no lock is needed to read it.
It also removes half built states. All checks run in the constructor. If it succeeds, the object is valid for life. If an operation fails, the old object is untouched. This is called failure atomicity.
A short history
1986
Driscoll, Sarnak, Sleator and Tarjan describe how to make data structures persistent: an update gives a new version and the old version stays usable.
2004
The revised Java memory model (JSR-133, Java 5) gives final fields a special promise: if the constructor does not leak
this, other threads see them correctly without locks.2016
TypeScript 2.0 adds
readonlyproperties, so the compiler refuses assignments.2018
Python 3.7 ships data classes (PEP 557) with the option
frozen=True.2021
Java 16 makes records final (JEP 395). The JEP describes them as shallowly immutable.
Words to know
- Immutable
- No visible change after construction, through any path.
- Shallow and deep
- Only the fields are fixed, or everything reachable from them is fixed too.
- Value object
- An object that is equal to another if their contents are equal, like two coins of the same value.
- Entity
- An object with an identity that stays while its state changes, like a customer.
- Aliasing
- Two names for one object. Harmless unless somebody changes it.
- Defensive copy
- Copying a changeable input or output so that outsiders never hold your internals.
- Wither
- A method such as
with_centsthat returns a copy with one field replaced. - Structural sharing
- A new version reuses the unchanged parts of the old one.
- Safe publication
- Handing an object to another thread so that the other thread sees it complete.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Build. Check everything in the constructor
Understand it
Start here
Flowers under glass
Lee presses flowers between two panes of glass. The glass is sealed, so a flower inside can be looked at but not changed. Whoever wants another flower makes another glass.
Everyday cousin: a birth certificate. After a change of name you get a new document, and the old paper does not rewrite itself.
The problem
Sharing plus change
Two invoices were made from one customer record, so both point to the same address object. Then the customer moves.
class Address: def __init__(self, street): self.street = streetclass Invoice: def __init__(self, month, address): self.month, self.address = month, addresshome = Address("Mill Lane 4")january = Invoice("January", home) # shares the objecthome.street = "Harbour Road 9" # the customer movesfebruary = Invoice("February", home)print(january.address.street) # Harbour Road 9, but it was sent to Mill Lane 4How the January invoice changed
Immutable
- State fixed at creation
- Can be read by any thread without a lock
- Equal today means equal tomorrow
- One place to check: the constructor
- A change is visible in the code: a new name or a swapped reference
Mutable and shared
- State may change at any moment
- Needs a lock or an owner
- A dictionary key can get lost
- Every setter must keep the rules
- Hard to say who changed it, and when
Gains
Six things you get
Thread safety
Any number of threads may read the object without synchronization. The hand-over must be proper in languages that reorder writes.
Predictable
What you checked three lines ago is still true. No other code can change it in between.
Cheap to share
It can be cached, pooled and returned from a getter without a copy, because the receiver can do no harm.
No order of calls
There is no moment after
newand beforesetCurrencyin which the object is half done.Safe hash keys
The hash cannot change while the object sits in a map or a set.
Failure atomicity
If
plusraises an error, nothing has happened. There is no state to repair.
class Point: def __init__(self, x): self.x = x def __eq__(self, o): return isinstance(o, Point) and self.x == o.x def __hash__(self): return hash(self.x)p = Point(1)seen = {p}p.x = 2print(p in seen, p in list(seen)) # False TrueHow to
Five rules for an immutable class
| Rule | Why | Java | Python |
|---|---|---|---|
| No subclass may break it | A subclass can add a setter or override a getter | final class or a record | Agreement, or @final for the type checker |
| Fields are private and set once | Nobody assigns them, the compiler helps | private final | frozen=True or no __setattr__ |
| No method changes state | A setter is a change with a name | withX returns a new one | replace(self, x=...) |
| Copy changeable inputs | The caller still holds the list they gave you | List.copyOf(lines) | tuple(lines) |
| Do not hand out changeable parts | A getter that returns the list is a setter | return the immutable copy | return the tuple |
Instant and not java.util.Date, a tuple and not a list.Memory trick: FINAL
- 1
F: final class
Nobody can extend it and add a setter. Records are final already.
- 2
I: initialize everything
All fields get their value in the constructor, and the constructor checks them.
- 3
N: no setters
Methods answer questions or return new objects.
- 4
A: all fields private and final
Assigned once. In Python: frozen data class.
- 5
L: lock what can change
Copy lists, dates and arrays on the way in and on the way out.
The bad shape: one address, many hands
1/3An invoice holds an address
It keeps the reference and not a copy. While nobody writes, this is fine.
useshas (lives on)
The good shape: values all the way down
1/3Money
A number and a currency. Both are fixed. plus answers with a new Money.
owns (dies together)has (lives on)
Depth
Shallow or deep?
Is this object really immutable?
from dataclasses import dataclass@dataclass(frozen=True)class Team: names: listt = Team(["Asha", "Lee"])t.names.append("Max") # no errorprint(t.names) # ['Asha', 'Lee', 'Max']@dataclass(frozen=True)class SafeTeam: names: tuple def __post_init__(self): object.__setattr__(self, "names", tuple(self.names))source = ["Asha", "Lee"]s = SafeTeam(source)source.append("Max")print(s.names) # ('Asha', 'Lee')What each tool freezes
| Tool | Freezes | Does not freeze |
|---|---|---|
Java final field | The reference | The object it points at |
| Java record | The fields, shallowly | A list inside it, unless you copy |
Collections.unmodifiableList | This view | The list behind it: the owner can still change it |
List.copyOf | The list | Elements that can change |
Python frozen=True | Assignment to fields | A list in a field, and object.__setattr__ |
| Python tuple, frozenset | The elements' slots | A list inside the tuple |
TypeScript readonly | Assignments, at compile time only | Anything at run time, nested objects |
JavaScript Object.freeze | The object's own properties, at run time | Nested objects |
C++ const object | All access through it, except mutable members | What a raw pointer member points at |
Where
Value or entity?
Should this class be immutable?
An Order in a shop design: should it be immutable?
BreaksSetters for everything
- How
setStatus,setTotal,setLines.- Limit
- Any caller can put a shipped order back to new, or set a total that does not match the lines.
- Choose when
- Never for rules that matter.
WorksFully immutable order
- How
order.ship()returns a new order. A repository stores the newest version.- Limit
- Two holders may have two versions of the same order. You need a version number to see that yours is old.
- Choose when
- Events, audit needs, functional code bases.
StrongEntity with guarded state, made of values
- How
order.ship()checks and changes its own status. Lines, money and addresses inside are immutable.- Limit
- The entity needs an owner or a lock when threads meet.
- Choose when
- Most interview designs. Say which parts are values and why.
Summary
The whole topic in one minute.
A change builds a new object, the old one stays. This removes the pair that causes most surprises, sharing together with change. It gives free sharing between threads, safe keys, simple undo and checks that run once.
The freeze must be deep: no setters, fields assigned once, copies of changeable inputs and outputs, and no subclass that breaks the promise.
Use it for values. Let entities, buffers and builders change, but keep the change in one owner. For shared state, swap one reference to a new snapshot.
- Bugs need sharing and change together. Immutability takes the change away.
- Immutable means deep: fields, what they point at, and subclasses.
- Five rules, FINAL: final class, initialize all, no setters, all private final, lock changeable parts.
- A method that sounds like change returns a new object. The caller must use the result.
- Values are immutable, entities may change in one place, builders change for a short time.
- For shared state: one reference, swapped to a new snapshot.
Sources
- Java Language Specification 17.5: final field semantics
- JSR-133 FAQ (Java memory model)
- Java tutorial: a strategy for defining immutable objects
- JEP 395: Records
- PEP 557: Data Classes
- TypeScript 2.0 release notes: read-only properties
- Martin Fowler: ValueObject
- Persistent data structure
- Java: String
- Java: LocalDate
- Java: CopyOnWriteArrayList
- Python: built-in types
- Clojure: data structures
- Redux style guide
- Git internals: objects
- Kubernetes: ConfigMaps
- Amazon S3 Object Lock