Patterncore
Mutable Data
Also called shared mutable state, aliasing bug.
A code smell: data is changed in place while other code still holds a reference to it, so a change in one part of the program shows up as a surprise in another.
- Family
- code-smell
- Intent
- Find the data that is changed in place without need, and limit the changes: copy before a change, compute values on demand, or make the data immutable.
Intent
Find the data that the program changes in place when it does not need to, and limit the changes. Make a copy before a change, compute a derived value when it is asked for, or make the data immutable, so that a change in one place cannot surprise the code in another place.
Problem
A program that changes data in place is normal: a counter goes up, a buffer fills, a record gets a new address. The smell is a change that other code does not expect. Refactoring gives the reason: a change to data in one place can have consequences in another place that the programmer did not foresee, and the resulting bugs are hard to find.1
The most common form is aliasing. Fowler defines it: "Aliasing occurs when the same memory location is accessed through more than one reference."2 His example is in Java. A variable partyDate is set to retirementDate, so both names refer to one Date object. A call to partyDate.setDate(5) moves the party to Saturday, and it also moves the retirement.2
The forces are these:
- In place changes are often faster and use less memory than copies.
- Many library functions change their argument. In JavaScript,
sort()"sorts the elements of an array in place and returns the reference to the same array".3 In Python,list.sort()"modifies the list in-place".4 In Go,slices.Sortsorts the slice that it is given.5 - A
constorfinaldeclaration protects the name, not the value. MDN states it for JavaScript:const"creates an immutable reference to a value. It does not mean the value it holds is immutable".6 - The wider the scope of the data, the worse the smell. A local variable that one function changes is easy to follow. A field that many functions change, or a global variable, is not.
Solution
Refactoring names a group of refactorings, each for one form of the smell.1 The catalogue at refactoring.com has a card for each.7
- Data that many functions change: Encapsulate Variable, so that each change goes through one function that can be found and watched.
- A variable that holds different things at different times: Split Variable, so that each variable is set once.
- Code that changes data mixed with code that only reads it: Slide Statements and Extract Function to move the changes away from the reads, and Separate Query from Modifier so that a function either returns a value or changes state, not both. Fowler's article on command query separation states the idea: queries "Return a result and do not change the observable state of the system", and commands "Change the state of a system but do not return a value".8
- A setter that nothing should call after construction: Remove Setting Method.
- A stored value that can be computed from other data: Replace Derived Variable with Query. A value that is computed when asked for cannot get out of date.
- Functions that update a shared structure step by step: Combine Functions into Class or Combine Functions into Transform, so that the changes happen in one place.
- A small object that is shared and changed: Change Reference to Value. Make it immutable, and replace it as a whole in place of changing its fields.
Fowler sums up the last point: "A good way to avoid shared updates of value objects is to make value objects immutable."2
Example
The function median sorts its argument to find the middle value. The caller passes the list of readings in the order they were taken, and after the call the list is in a different order. The function returns the right median, so a test of the result alone passes.
import assert from "node:assert/strict";
// Before: sort() changes the caller's array.
function medianBefore(values) {
values.sort((a, b) => a - b);
return values[Math.floor(values.length / 2)];
}
// After: toSorted() returns a sorted copy.
function median(values) {
const sorted = values.toSorted((a, b) => a - b);
return sorted[Math.floor(sorted.length / 2)];
}
let readings = [30, 10, 20];
assert.equal(medianBefore(readings), 20);
assert.deepEqual(readings, [10, 20, 30]); // the first reading is lost
console.log("medianBefore: the caller's array was changed");
readings = [30, 10, 20];
assert.equal(median(readings), 20);
assert.deepEqual(readings, [30, 10, 20]);
console.log("median: tests pass");
medianBefore: the caller's array was changed
median: tests pass
The fix is one line, but it changes the contract of the function. The first version has a Side effect that its name does not show. The second version is a query: it returns a value and leaves its input as it was. MDN describes toSorted() as "the copying version of the sort() method".9
| Language | What the example shows |
|---|---|
| JavaScript | sort() against toSorted(), as above |
| Python | list.sort() against sorted(), and the mutable default argument |
| Java | Collections.sort on the caller's list, against a sorted stream; List.of rejects the change |
| Go | slices.Sort on the caller's slice, against slices.Clone first |
# Before: list.sort() changes the caller's list.
def median_before(values):
values.sort()
return values[len(values) // 2]
# After: sorted() returns a sorted copy.
def median(values):
ordered = sorted(values)
return ordered[len(ordered) // 2]
readings = [30, 10, 20]
assert median_before(readings) == 20
assert readings == [10, 20, 30] # the first reading is lost
print("median_before: the caller's list was changed")
readings = [30, 10, 20]
assert median(readings) == 20
assert readings == [30, 10, 20]
print("median: tests pass")
# The same smell in a default argument: one list is shared by all calls.
def add_tag_before(tag, tags=[]):
tags.append(tag)
return tags
def add_tag(tag, tags=None):
tags = [] if tags is None else list(tags)
tags.append(tag)
return tags
assert add_tag_before("a") == ["a"]
assert add_tag_before("b") == ["a", "b"] # the list from the first call
assert add_tag("a") == ["a"]
assert add_tag("b") == ["b"]
print("add_tag: tests pass")
median_before: the caller's list was changed
median: tests pass
add_tag: tests pass
list.sort()returnsNone, so code such asordered = values.sort()fails at once. The Python sorting guide says that this is "to avoid confusion".- The default value
[]is made once, when thedefstatement runs, and each call that uses the default gets the same list. The fix usesNoneas the default and makes the list inside the function. list(tags)also copies a list that the caller passes, so the function does not change the caller's list either.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
// Before: Collections.sort changes the caller's list.
static int medianBefore(List<Integer> values) {
Collections.sort(values);
return values.get(values.size() / 2);
}
// After: the stream sorts a copy.
static int median(List<Integer> values) {
List<Integer> sorted = values.stream().sorted().toList();
return sorted.get(sorted.size() / 2);
}
static void check(boolean ok, String what) {
if (!ok) throw new AssertionError(what);
}
public static void main(String[] args) {
List<Integer> readings = new ArrayList<>(List.of(30, 10, 20));
check(medianBefore(readings) == 20, "before");
check(readings.equals(List.of(10, 20, 30)), "the first reading is lost");
System.out.println("medianBefore: the caller's list was changed");
readings = new ArrayList<>(List.of(30, 10, 20));
check(median(readings) == 20, "after");
check(readings.equals(List.of(30, 10, 20)), "unchanged");
System.out.println("median: tests pass");
try {
medianBefore(List.of(30, 10, 20));
throw new AssertionError("sorted an unmodifiable list");
} catch (UnsupportedOperationException expected) {
System.out.println("medianBefore: List.of rejects the change");
}
}
}
medianBefore: the caller's list was changed
median: tests pass
medianBefore: List.of rejects the change
- A list from
List.ofis unmodifiable, so the "before" version fails at once withUnsupportedOperationException. An unmodifiable list turns a silent change into an error at the line that makes it. Stream.toList()also returns an unmodifiable list, so the copy inmediancannot be changed by a later caller either.- The method signature
int median(List<Integer> values)says nothing about a change tovalues. Java has no way to mark a parameter as read only, so the contract must be in the name, the documentation or the type of the list.
package main
import (
"fmt"
"slices"
)
// Before: slices.Sort changes the caller's slice.
func medianBefore(values []int) int {
slices.Sort(values)
return values[len(values)/2]
}
// After: sort a clone.
func median(values []int) int {
sorted := slices.Clone(values)
slices.Sort(sorted)
return sorted[len(sorted)/2]
}
func main() {
readings := []int{30, 10, 20}
if medianBefore(readings) != 20 || !slices.Equal(readings, []int{10, 20, 30}) {
panic("before")
}
fmt.Println("medianBefore: the caller's slice was changed")
readings = []int{30, 10, 20}
if median(readings) != 20 || !slices.Equal(readings, []int{30, 10, 20}) {
panic("after")
}
fmt.Println("median: tests pass")
// A sub-slice shares the array, so a sort of the part changes the whole.
all := []int{30, 10, 20, 5}
medianBefore(all[:3])
if !slices.Equal(all, []int{10, 20, 30, 5}) {
panic("sub-slice")
}
fmt.Println("medianBefore: a sub-slice changed the whole slice")
}
medianBefore: the caller's slice was changed
median: tests pass
medianBefore: a sub-slice changed the whole slice
- A Go slice is a small header that points to an array. Passing a slice copies the header, not the array, so the function and the caller share the elements.
slices.Clonemakes a shallow copy. For a slice of integers that is a full copy. For a slice of pointers, the copy shares the values that the pointers refer to.- The last test shows that
all[:3]is a view of the first three elements ofall. The sort changes them inalltoo.
Consequences
Data that does not change can be shared without fear. It can be passed to any function, kept in a cache and read from many threads, and no copy is needed to protect it. Fowler notes that immutability "makes it harder to create several kinds of bugs".2
The cost is copies and more allocation. Sorting a copy uses memory for a second array. For a large data set in a tight loop, an in place change can be the right choice, and then the function name and its documentation must say that it changes its argument. Fowler also warns that immutability is "by no means a free breakfast": when things do need to change, it can add complexity.2
Some changes are meant to be shared. When a person's phone number changes, every reference to that person must see the new number. Fowler calls these reference objects, and contrasts them with value objects, which no code should change in place.2 The smell is a change to data that the other holders expect to stay the same.
Languages give different defaults:
- Rust variables are immutable unless declared with
mut. The Rust book says thatmut"conveys intent to future readers of the code by indicating that other parts of the code will be changing this variable’s value."10 - In JavaScript,
Object.freeze()makes an object immutable, but MDN notes that "freeze is shallow": an object inside a frozen object can still change.11 - In Java,
List.ofandList.copyOfreturn unmodifiable lists, and "Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown."12 - In Python, a mutable default argument is shared by all calls. The Python FAQ says that this "type of bug commonly bites neophyte programmers."13
How to fix it
- A function that changes its argument without need: copy first, or use the copying form of the operation (
toSorted,sorted,slices.Clone).945 - A field that many functions set: Encapsulate Variable.1
- A variable that is set many times for different purposes: Split Variable.1
- A function that returns a value and also changes state: Separate Query from Modifier.1
- A field that can be computed: Replace Derived Variable with Query.1
- A setter that is only used to build the object: Remove Setting Method, and set the field in the constructor.1
- A small object that is shared and changed: Change Reference to Value.1
Variants and related patterns
Global Data. Mutable data with the largest scope. See Global Data.
Immutability. The language feature that removes the smell at its root. See Immutability.
Data races. Mutable data that two threads change at the same time without a lock. See Data race.
Value objects. Small objects, such as a date or an amount of money, that are compared by value and are not changed in place. See Value object.
Temporary Field. A field that is set only in some cases, which is a form of mutable state in an object. See Temporary Field.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Mutable Data
- Martin Fowler, Aliasing Bug, bliki, the first paragraph, the Date example and the last paragraph
- MDN Web Docs, Array.prototype.sort(), the introduction and Return value
- Python documentation, Sorting Techniques, Python 3.14, Sorting Basics
- Go standard library, package slices, func Clone and func Sort
- MDN Web Docs, const, Description
- Martin Fowler, Catalog of Refactorings, the cards Split Variable, Separate Query from Modifier, Remove Setting Method, Replace Derived Variable with Query and Change Reference to Value
- Martin Fowler, Command Query Separation, bliki, the definitions of queries and commands
- MDN Web Docs, Array.prototype.toSorted(), the introduction
- The Rust Programming Language, Variables and Mutability, the introduction
- MDN Web Docs, Object.freeze(), the introduction and Description
- Java SE 25 API, java.util.List, Unmodifiable Lists
- Python Programming FAQ, Python 3.14, Why are default values shared between objects?
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag A135SR Edit this page History Report an error Markdown