Part 5 of 6 · 2 min read
Benefits and limits
Safety, sharing and the cost of copies.
Why it pays, and when to relax
EJ lists the benefits. An immutable object has one state, the one it was created in. If constructors enforce the invariants, they hold for all time. Immutable objects are inherently thread-safe, since no thread can see another thread's change, and so they can be shared freely. They also give failure atomicity for free (module 1), because a failed operation cannot leave an existing object half-changed. And they make good map keys and set elements, since their hash code never changes.
There is one cost, which EJ states plainly: a separate object is needed for each distinct value. A chain of operations creates many short-lived objects. For most designs this is cheap. For a value that is built up in many steps, such as a long text, a mutable helper such as StringBuilder can build it, and the final result is then frozen into an immutable String. This is the idea behind the builder (Level 3, module 3).
Not everything should be immutable. An entity such as a booking changes over its life, as module 3 of Level 4 showed with the state pattern. A reasonable design makes the values immutable, such as money, slots and guest lists, and keeps entities small, with the mutable parts hidden and changed only through methods that protect the invariants.
EJ's guidance is to make classes immutable unless there is a good reason not to, and to keep the mutable surface as small as possible. In a design round, say which classes are values and immutable, and which are entities and mutable. That shows you have decided, not guessed.
Interview angle
Answer in your head first, then open it.
How do you make a class immutable?
No setters, final class, final private fields, and defensive copies of any mutable component.
Why prefer immutable objects?
One consistent state, thread safety, safe sharing, safe use as keys, and failure atomicity.
Is a final field enough?
No. A final reference to a mutable object still lets the object change.
Check yourself: 1. Which benefit makes immutable objects good map keys? 2. What is the cost, and how does a builder help? 3. Which kind of class should stay mutable?
Words you will meet
| Word | Meaning |
|---|---|
| Immutable | Unable to change after creation |
| Value object | An immutable object equal to others with the same content |
| Entity | An object with a lasting identity, whose details may change |
| Defensive copy | A private copy of a mutable argument or result |
| Wither | A method that returns a copy with one field changed |