Techniquecore
Change reference to value
Also called make immutable value, replace mutation with a fresh value.
When a small object that is held inside another is changed in place, make it immutable: give it value equality, and replace it with a fresh object each time its contents change.
- Family
- refactoring
- Intent
- Treat a small object as a value: never change it, replace it.
Purpose
An object that is held inside another object can be a reference or a value. If it is a reference, code changes it in place, and every holder of the reference sees the change. If it is a value, nobody changes it: a change makes a fresh object, which replaces the old one in the holder.
Change reference to value makes a small object a value. The catalogue card changes a Product that subtracts a discount from the amount of its price object into a Product that sets its price to a fresh Money object.1 The refactoring is in both editions of the book.23 A value is safe to share and to pass around, since no holder can change it under another one. See Immutability and Value equality and identity.
Steps
- Check that the object can be immutable, or that it can become so.3
- For each setter of the object, remove it. Where callers used it, make them build a fresh object, and assign it to the field that holds the object. Test after each change.
- Give the object equality based on its fields: two values with the same contents are equal.
- If the language uses a hash code with equality, make the hash code agree with equality.
Example
An order holds a delivery window. Code that moves the delivery by a day changes the window in place, and the change also moves the window of each other order that shares the object. After the refactoring, the window is a frozen value, and moving it gives a fresh window.
import assert from "node:assert/strict";
// Before: the window is a reference, changed in place.
const sharedWindow = { startHour: 9, endHour: 12, day: 3 };
const a = { id: "a", window: sharedWindow };
const b = { id: "b", window: sharedWindow };
a.window.day += 1; // also moves order b
assert.equal(b.window.day, 4);
// After: the window is a value.
class DeliveryWindow {
constructor(day, startHour, endHour) {
Object.assign(this, { day, startHour, endHour });
Object.freeze(this);
}
movedBy(days) { return new DeliveryWindow(this.day + days, this.startHour, this.endHour); }
equals(other) {
return other instanceof DeliveryWindow && this.day === other.day &&
this.startHour === other.startHour && this.endHour === other.endHour;
}
}
const morning = new DeliveryWindow(3, 9, 12);
const c = { id: "c", window: morning };
const d = { id: "d", window: morning };
c.window = c.window.movedBy(1);
assert.equal(d.window.day, 3); // d is not moved
assert.ok(c.window.equals(new DeliveryWindow(4, 9, 12)));
assert.throws(() => { "use strict"; morning.day = 5; }, TypeError);
console.log("change reference to value: tests pass");
change reference to value: tests pass
An assignment to a field of a frozen object fails, and MDN notes that in strict mode such attempts "will throw TypeErrors".4 JavaScript modules run in strict mode, and the test checks the error. In Python, frozen=True on a dataclass lets you "emulate immutability", and when equality and frozen are both on, the decorator generates a hash method.5
| Language | What the example shows |
|---|---|
| JavaScript | a frozen class with a method that returns a fresh value, and an equals method, as above |
| Python | a frozen dataclass, which gives equality and a hash code from the fields, and dataclasses.replace |
| Java | a record, which gives equals and hashCode from its components |
| Go | a struct passed and assigned by value, and compared with == |
import dataclasses
from dataclasses import dataclass
@dataclass(frozen=True)
class DeliveryWindow:
day: int
start_hour: int
end_hour: int
def moved_by(self, days: int) -> "DeliveryWindow":
return dataclasses.replace(self, day=self.day + days)
morning = DeliveryWindow(3, 9, 12)
c = {"id": "c", "window": morning}
d = {"id": "d", "window": morning}
c["window"] = c["window"].moved_by(1)
assert d["window"].day == 3 # d is not moved
assert c["window"] == DeliveryWindow(4, 9, 12) # equality from the fields
assert len({DeliveryWindow(4, 9, 12), c["window"]}) == 1 # hash agrees with equality
try:
morning.day = 5
raise RuntimeError("expected FrozenInstanceError")
except dataclasses.FrozenInstanceError:
pass
# Freezing is shallow: a list in a frozen dataclass can still change.
@dataclass(frozen=True)
class Route:
stops: list[str]
r = Route(["depot"])
r.stops.append("harbour")
assert r.stops == ["depot", "harbour"]
print("change reference to value: tests pass")
change reference to value: tests pass
import java.util.HashSet;
import java.util.Set;
public class Main {
// A record has final fields, and equals and hashCode from its components.
record DeliveryWindow(int day, int startHour, int endHour) {
DeliveryWindow movedBy(int days) {
return new DeliveryWindow(day + days, startHour, endHour);
}
}
static final class Order {
DeliveryWindow window;
Order(DeliveryWindow w) { window = w; }
}
public static void main(String[] args) {
DeliveryWindow morning = new DeliveryWindow(3, 9, 12);
Order c = new Order(morning);
Order d = new Order(morning);
c.window = c.window.movedBy(1);
if (d.window.day() != 3) throw new AssertionError("d moved");
if (!c.window.equals(new DeliveryWindow(4, 9, 12))) throw new AssertionError("equals");
Set<DeliveryWindow> set = new HashSet<>(Set.of(c.window));
if (!set.contains(new DeliveryWindow(4, 9, 12))) throw new AssertionError("hashCode");
System.out.println("change reference to value: tests pass");
}
}
change reference to value: tests pass
package main
import "fmt"
// DeliveryWindow is a value: assignment copies it, and == compares the fields.
type DeliveryWindow struct {
Day, StartHour, EndHour int
}
func (w DeliveryWindow) MovedBy(days int) DeliveryWindow {
w.Day += days // w is a copy
return w
}
type Order struct {
ID string
Window DeliveryWindow
}
func main() {
morning := DeliveryWindow{3, 9, 12}
c := Order{"c", morning}
d := Order{"d", morning}
c.Window = c.Window.MovedBy(1)
if d.Window.Day != 3 || morning.Day != 3 {
panic("moved")
}
if c.Window != (DeliveryWindow{4, 9, 12}) {
panic("equality")
}
seen := map[DeliveryWindow]bool{c.Window: true}
if !seen[DeliveryWindow{4, 9, 12}] {
panic("map key")
}
fmt.Println("change reference to value: tests pass")
}
change reference to value: tests pass
When to use
- A small object that holds data, not identity. An amount of money, a date range or a coordinate: two with the same contents are the same thing.
- A shared object that one holder changes by mistake. A value cannot be changed under another holder.
- An object used as a key in a map or an element of a set. A key that changes after it is put into a hash map can no longer be found.
Pitfalls
Objects that must be shared and updated. If several holders must see one update, such as a customer whose address changes, the object needs identity. That is the inverse refactoring, Change Value to Reference.1
Cost of copies. A large object that changes often makes a fresh copy at each change. For a small object this cost is small. For a large one, measure.
Shallow freezing. Object.freeze in JavaScript does not freeze the objects that a field holds: "those objects are not frozen".4 A frozen dataclass in Python also does not freeze the objects in its fields. A value must hold only values.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool.
References
- Martin Fowler, Catalog of Refactorings, Change Reference to Value, the entry; inverse of Change Value to Reference
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 8, Organizing Data, Change Reference to Value
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 9, Organizing Data, Change Reference to Value, motivation, mechanics and the example of a telephone number
- MDN Web Docs, Object.freeze(), Description, and the example of a shallow freeze
- Python documentation, dataclasses, Data Classes, the frozen parameter, and the hash method
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 PJWFP1 Edit this page History Report an error Markdown