AlgoViz

Immutability

medium 45 min

An immutable object keeps the value it was born with.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:40

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

  1. 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.

  2. 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.

  3. 2016

    TypeScript 2.0 adds readonly properties, so the compiler refuses assignments.

  4. 2018

    Python 3.7 ships data classes (PEP 557) with the option frozen=True.

  5. 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_cents that 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.

Step 1 of 4

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.

Lee and the glass flowers
1

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.

Python
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 4
Nobody touched the invoice of January, and it changed.
Edit and run it in your browser

How the January invoice changed

Two holders, one object, one writer. With a frozen address the form would have to make a new one, and January would keep the old.

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 new and before setCurrency in 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 plus raises an error, nothing has happened. There is no state to repair.

Python
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 True
A key that gets lost. The set looks in the bucket for the new hash, and the object sits in the bucket for the old one.
Edit and run it in your browser

How to

Five rules for an immutable class

RuleWhyJavaPython
No subclass may break itA subclass can add a setter or override a getterfinal class or a recordAgreement, or @final for the type checker
Fields are private and set onceNobody assigns them, the compiler helpsprivate finalfrozen=True or no __setattr__
No method changes stateA setter is a change with a namewithX returns a new onereplace(self, x=...)
Copy changeable inputsThe caller still holds the list they gave youList.copyOf(lines)tuple(lines)
Do not hand out changeable partsA getter that returns the list is a setterreturn the immutable copyreturn the tuple
The last two rules disappear when the parts are immutable themselves. Use Instant and not java.util.Date, a tuple and not a list.

Memory trick: FINAL

  1. 1

    F: final class

    Nobody can extend it and add a setter. Records are final already.

  2. 2

    I: initialize everything

    All fields get their value in the constructor, and the constructor checks them.

  3. 3

    N: no setters

    Methods answer questions or return new objects.

  4. 4

    A: all fields private and final

    Assigned once. In Python: frozen data class.

  5. 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

reads laterInvoice- address: Address+ print()Address- street: String+ getStreet()+ setStreet(s)

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

Money- cents: long- currency: String+ plus(m): Money+ withCents(c): Money

1/3Money

A number and a currency. Both are fixed. plus answers with a new Money.

owns (dies together)has (lives on)

Immutable core, one small changing edge.

Depth

Shallow or deep?

Is this object really immutable?

Python
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')
Frozen, and still changeable: the dataclass freezes the field and not the list.
Edit and run it in your browser

What each tool freezes

ToolFreezesDoes not freeze
Java final fieldThe referenceThe object it points at
Java recordThe fields, shallowlyA list inside it, unless you copy
Collections.unmodifiableListThis viewThe list behind it: the owner can still change it
List.copyOfThe listElements that can change
Python frozen=TrueAssignment to fieldsA list in a field, and object.__setattr__
Python tuple, frozensetThe elements' slotsA list inside the tuple
TypeScript readonlyAssignments, at compile time onlyAnything at run time, nested objects
JavaScript Object.freezeThe object's own properties, at run timeNested objects
C++ const objectAll access through it, except mutable membersWhat a raw pointer member points at

Where

Value or entity?

Should this class be immutable?

Money, dates, coordinates, ids, events, settings and messages are values. An account, an order and a parking spot are entities.

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