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

See it run

Objects at run time: which object is touched, which is new, and who still sees the old one.

Operations

A change makes a new object

100 dollars minus 25, without touching the wallet.

Step 1 of 5

Create

maincallerwallet100 USDwalletMoneycents10000currencyUSD

The wallet gets 100 USD. Its value is fixed for life.

Step 1: Create

wallet = Money(10000, "USD")tip = Money(-2500, "USD")after = wallet.plus(tip)def plus(self, other):    if self.currency != other.currency: raise ValueError    return Money(self.cents + other.cents, self.currency)
Good for
Every small value
Costs
One more small object

The caller decides which name points at which object. The objects stay.

In the real world

The same immutability doing real jobs. Pick one and step through it.

The immutable object everybody uses. Why a lonely upper() does nothing.

Step 1 of 4

A string

name points atother strings
name = "Ada""Ada"none
name.upper()
x = name.upper()
name = x

The name points at the string Ada.

Step 1: A string

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Frozen class, open list

    critical

    The field is fixed, the list is not.

    Wrong
    @dataclass(frozen=True)class Team:    names: list
    Right
    names: tupledef __post_init__(self):    object.__setattr__(self, "names", tuple(self.names))
  • The result is ignored

    major

    Immutable objects answer, they do not change.

    Wrong
    price.plus(tax)
    Right
    price = price.plus(tax)
  • Check, then copy

    critical

    Between the two lines another thread can change the argument.

    Wrong
    check(dates)self.dates = tuple(dates)
    Right
    self.dates = tuple(dates)check(self.dates)
  • Append on copies in a loop

    major

    About n x n / 2 copied slots.

    Wrong
    for line in source:    receipt = add_line(receipt, line)
    Right
    receipt = Receipt(tuple(source), now)
  • Two references for one truth

    critical

    A reader can meet the new limit with the old burst.

    Wrong
    store.limit = 90store.burst = 120
    Right
    store.update(lambda s: replace(s, limit=90, burst=120))

Interview tips

  • Say deep

    • Name each field's type
    • Say who else holds it
    • Copy in the constructor
  • Value or entity

    • Money and dates are frozen
    • Accounts change in one place
    • Say why
  • Threads

    • Snapshot and one reference
    • Lost update: compare and set
    • Stale reads are a choice
  • Cost

    • Small: just copy
    • Loop: builder
    • Large: share the structure