TL;DR
Mutable state is data that a program can change after it is created. An update overwrites the value in its existing place, so anyone who refers to that place sees the new value at once. This is how most programs remember things, such as a score, a bank balance or a list of open files. It becomes dangerous when two parts of a program hold references to the same place, because a change made through one reference can surprise the other.
Builds on: Pointer, because a second reference to the same value is a second pointer to one box · Leads to: Immutability (the alternative that never overwrites), race conditions when several threads change one value, and Functional Programming, which limits mutation on purpose
Where it's used
Bank balances. A bank account holds one balance number. A withdrawal overwrites the balance with a smaller number, and every screen that shows the account reads the same stored value. If the balance were copied into each screen instead, a withdrawal would have to update every copy, and a missed copy would show the wrong amount.
Game state. A game keeps a score, a health value and a list of enemies, and each frame of the game updates them in place. Rewriting one number 60 times a second is cheap, and it is the natural way to describe a world that changes. A copy of the whole world for each frame would cost far more memory and time than the game can spare.
Shared data structures in a server. A web server may keep one in-memory table of logged-in users, and many request handlers, which may run on several threads, update it at the same moment. The table is mutable state shared by all handlers, so every change must be coordinated, or two handlers may overwrite each other's work.
How it works
Think of a value as a box with an address, as in the Pointer lesson. Mutation means writing a new value into an existing box. Here is a small counter that shows what changes and what stays the same.
Box 50 holds a counter c. Box 52 holds a pointer a. Box 56 holds a second counter d. Start with c at 0.
-
Start with one box. Box 50 holds 0, and
cnames box 50. Check: the only place with the counter is box 50. -
Make a second name for the same box. Store the address of
c, which is 50, ina. Nowaandcboth lead to box 50. They are two names for one box, which is called an alias. Check: changing the box throughaalso changes whatcreads. -
Mutate through one name. Compute
*a = *a + 1. The box at 50 is overwritten with 1. Check: readingcnow gives 1, although the statement useda. -
Copy instead of alias. Copy the current value into
d. Box 56 now holds 1, a separate box with its own value. Check:dandcagree at this moment, but they are no longer linked. -
Mutate again. Add 1 to
c. Box 50 now holds 2. Box 56 still holds 1. Check:creads 2, anddreads 1. The copy went stale the moment the original changed.
flowchart LR C["Name c"] --> B["Box 50: 2"] A["Name a"] --> B D["Name d"] --> E["Box 56: 1, a separate copy"]
Steps 3 and 5 are the core of mutable state. An update overwrites a box, and any name that leads to that box sees the change. Step 4 shows the other option, copying, where each box changes only when its own name writes to it. Most bugs with mutable state come from aliases that the programmer did not notice.
The math
A program's state at any time is the set of values in its boxes. Call it at step . An update reads the current state and an input , and produces the next state:
Here is the update rule. Mutation means the update writes into the same boxes, so the old state is gone once the update runs. The formula is still the right model, but the old value no longer exists anywhere the program can read it.
Step 3 in symbols: the counter
Let be the value in box 50, and let each update add 1:
The arrow means "overwrite the box with", not "equals". Starting from , after updates the value is . The notation is a sequence of values over time, but the program keeps only the newest one.
Step 2 in symbols: aliases
Two names and are aliases when . For every alias pair, a write through one name is a write through the other, so for every update on the shared box, and always read the same value.
Step 5 in symbols: copies drift
A copy is a separate box, so and agree only at the moment of copying. After further updates to and none to , . The copy is correct for the past and wrong for the present.
Worked examples
Let start at 0 in box 10. Apply three times.
- Update 1: . Box 10 now holds 1.
- Update 2: . Box 10 now holds 2.
- Update 3: . Box 10 now holds 3.
- The old values 0, 1 and 2 are gone. The program can read only 3.
Interpretation: the box's history is lost. Only the latest value survives, which is why a program that needs the past must copy it somewhere before the next update.
Let list be a list of numbers in one box, and let alias be a second name that points to the same box. The list starts as [4, 9].
- Call
alias.append(7). This writes 7 at the end of the list in the shared box. The list is now [4, 9, 7]. - Read
list. It shows [4, 9, 7], becauselistandaliaslead to the same box. - Now call
list.append(1). The shared box becomes [4, 9, 7, 1]. - Read
alias. It shows [4, 9, 7, 1]. - Let
copybe a copy of the list, made before step 1. The copy still holds [4, 9]. It does not see steps 1 or 3.
Interpretation: a function that receives alias and appends to it changes the caller's list. The caller never wrote that line, so it cannot know the list changed unless it reads it again.
An account holds a balance of 100 dollars. Two withdrawals of 60 dollars each run at the same time, one from a phone and one from a website. Each withdrawal reads the balance, subtracts 60 and writes the result back.
- Withdrawal A reads the balance: 100.
- Withdrawal B reads the balance before A writes: also 100.
- Withdrawal A computes and writes 40.
- Withdrawal B computes and writes 40. This overwrites A's result.
- The balance is 40, but 120 dollars have left the account. One withdrawal was lost.
The bug is in the order of steps 1 to 4, not in any one line. Locks or database transactions make the read-and-write happen as one step, so the second withdrawal sees 40 and is refused.
Interpretation: mutable state shared across two actors needs coordination, because each write silently discards whatever the other wrote in between.
Try it: An account starts at 100 dollars. A deposit of 50 and a withdrawal of 30 run one after the other, with no overlap. What is the final balance?
Answer: dollars.
Common mistakes and tradeoffs
It is tempting to think that mutation is always a mistake. In fact overwriting one box is the cheapest way to record a change. Copying a large structure on every update is far more expensive, and programs that avoid mutation pay for it in memory or in complicated data structures.
It is tempting to think that a variable is a copy of its value. In fact a variable may be a second name for a box that another part of the program is also using, so a change made through a function or another name can reach it without any visible assignment. The fix is to know which names share boxes.
It is tempting to think that two threads of work will not collide if each is careful on its own. In fact a race appears when the read and the write are separate steps, as in the bank example. Each thread is correct alone, and the combination is wrong.
When to use mutable state: a value has one owner, changes often, and must be fast, such as a loop counter, a buffer of pixels or a game frame. When not to use it: several parts of the program share the value and can change it, or the program runs in parallel. Alternatives: Immutability, where each change produces a new value and old readers keep the old one, or a message-passing design, where one owner holds the state and others ask it to change. Persistent data structures give much of the speed of mutation with the safety of immutability by sharing unchanged parts, as binary trees do.
History
Early programming languages in the 1950s, such as FORTRAN, made assignment a basic statement. The machine's memory was already a set of boxes that programs overwrote, so mutation was the natural model, and most languages that followed kept it.
A different tradition kept most data unchanging. Lisp, designed in 1958, built its programs from lists, and its style favoured building new lists over changing old ones, although it included destructive operations from the start. Languages in the ML family, developed in the 1970s, made immutable values the default and required an explicit marker for a mutable one.
Mutable state caught on because it matches how hardware works and how people think about a world that changes. The cost of sharing it across parts of a program became clearer as programs grew and ran on many processors at once, which is why the functional tradition returned to immutability as a way to make shared code safer.
Recap
- Mutable state is a value that is overwritten in place, so every name that leads to that box sees the change.
- An alias is a second name for the same box, and a write through any name changes all of them.
- A copy is a separate box that goes stale as soon as the original changes.
- Shared mutable state needs coordination when several parts of a program write to it at once.
- Immutability avoids these problems by making every change a new value, at some cost in memory.
Read next: Immutability for values that never change, race conditions for what goes wrong when two threads write one box, and Functional Programming for a style that limits mutation on purpose.
Check yourself
QuestionWhat is an alias, and why can it cause a surprise?Show answer
An alias is a second name for the same box. A write through either name changes the value that both read, so a change made in one part of the program can appear in another part that never wrote to it.
QuestionA box holds 7. A copy of its value is stored in a second box. The first box is then incremented twice. What do the two boxes hold?Show answer
The first box holds . The copy was made before the updates and is a separate box, so it still holds 7.
QuestionWhy can two correct-looking updates to one balance still lose money?Show answer
Each update reads the balance, computes a new one, and writes it back as separate steps. If two updates read the same old balance before either writes, the second write overwrites the first, so one change is lost. Each update is correct alone, but the combination is not.
QuestionA game loop updates a score 60 times per second, once per frame, and the score is read by only one function. Is mutable state a good choice here, and why?Show answer
It is a good choice. The score has one owner, it changes often, and copying it on every update would cost far more than overwriting one box. Mutation is cheap here, and no other part of the program holds a second name that could be surprised by the change.
Sources
- "State (computer science)", Wikipedia: https://en.wikipedia.org/wiki/State_(computer_science)
- "Aliasing (computing)", Wikipedia: https://en.wikipedia.org/wiki/Aliasing_(computing)
- "Immutable object", Wikipedia: https://en.wikipedia.org/wiki/Immutable_object