Techniquecore
Move field
Move a field to the record or class that it belongs with, after you encapsulate it, so that data that changes together lives together.
- Family
- refactoring
- Intent
- Keep each piece of data in the structure whose changes it follows.
Purpose
Data structures shape code. When a field is in the wrong structure, the code around it pays: it passes the field together with another structure, or it must update copies of the field in two places when one thing changes.
Move field puts the field in the structure it belongs with. The catalogue card moves a discount rate from a customer to the customer's plan; the customer's getter then reads it from the plan.1 The book gives two signs that a field is in the wrong place: a field that is always passed together with another record, and a change in one record that forces a change to a field in another.2 The first edition has the refactoring under the same name.3
Steps
- Encapsulate the field, so that all reads and writes go through accessors. See Encapsulate Variable.2
- Test.
- Make the field and its accessors in the target.
- Make sure the source object can reach the target object. If not, add a reference.
- Change the source accessors to use the target's field.2 Test.
- Remove the field from the source, and test.
Step 1 is what makes the move safe. When every access goes through one getter and one setter, only those two change in step 5.
Example
Each seat in a theatre stores its own price, but the price is set per section: a price change must find and update every seat. After the refactoring, the section holds the price, and the seat's getter reads it.
import assert from "node:assert/strict";
class Section {
constructor(name, priceCents) { this.name = name; this.priceCents = priceCents; }
}
class Seat {
#section;
constructor(row, number, section) { this.row = row; this.number = number; this.#section = section; }
// Step 5: the accessor reads the moved field.
get priceCents() { return this.#section.priceCents; }
}
const stalls = new Section("stalls", 4500);
const seats = [new Seat("A", 1, stalls), new Seat("A", 2, stalls), new Seat("B", 7, stalls)];
assert.deepEqual(seats.map((s) => s.priceCents), [4500, 4500, 4500]);
stalls.priceCents = 4900; // one change, in one place
assert.deepEqual(seats.map((s) => s.priceCents), [4900, 4900, 4900]);
console.log("move field: tests pass");
move field: tests pass
Before the refactoring, the same price change was a loop over every seat in the section, and a seat added later with the old price was a bug.
| Language | What the example shows |
|---|---|
| JavaScript | a price moved from each seat to its section, as above |
| Python | the same move, with a property in the seat that reads the section |
| Java | the same move, where a seat record holds a reference to a mutable section |
| Go | the same move, with a pointer from each seat to the shared section |
class Section:
def __init__(self, name: str, price_cents: int):
self.name = name
self.price_cents = price_cents
class Seat:
def __init__(self, row: str, number: int, section: Section):
self.row = row
self.number = number
self._section = section
@property
def price_cents(self) -> int:
return self._section.price_cents # the field now lives in Section
stalls = Section("stalls", 4500)
seats = [Seat("A", 1, stalls), Seat("A", 2, stalls), Seat("B", 7, stalls)]
assert [s.price_cents for s in seats] == [4500] * 3
stalls.price_cents = 4900
assert [s.price_cents for s in seats] == [4900] * 3
print("move field: tests pass")
move field: tests pass
import java.util.List;
public class Main {
static final class Section {
private final String name;
private long priceCents; // moved here from Seat
Section(String name, long priceCents) { this.name = name; this.priceCents = priceCents; }
long priceCents() { return priceCents; }
void setPriceCents(long c) { priceCents = c; }
}
record Seat(String row, int number, Section section) {
long priceCents() { return section.priceCents(); }
}
public static void main(String[] args) {
Section stalls = new Section("stalls", 4500);
List<Seat> seats = List.of(new Seat("A", 1, stalls), new Seat("A", 2, stalls), new Seat("B", 7, stalls));
stalls.setPriceCents(4900);
for (Seat s : seats) if (s.priceCents() != 4900) throw new AssertionError(s);
System.out.println("move field: tests pass");
}
}
move field: tests pass
package main
import "fmt"
type Section struct {
Name string
PriceCents int // moved here from Seat
}
type Seat struct {
Row string
Number int
section *Section
}
func (s Seat) PriceCents() int { return s.section.PriceCents }
func main() {
stalls := &Section{"stalls", 4500}
seats := []Seat{{"A", 1, stalls}, {"A", 2, stalls}, {"B", 7, stalls}}
stalls.PriceCents = 4900
for _, s := range seats {
if s.PriceCents() != 4900 {
panic(s)
}
}
fmt.Println("move field: tests pass")
}
move field: tests pass
When to use
- One change, many updates. A change to one fact forces updates to the same field in many records. This is one form of Shotgun Surgery.
- Data that travels together. A field is always passed with another structure. See Data Clumps.
- Before moving functions. A function that uses a field moves more cleanly when the field is already in the target. See Move Function.
Pitfalls
Shared data becomes shared. After the move, many objects see one field. That is the purpose, but it also means that a write through one object changes what all the others see. Make sure that is what the domain wants.
Accessors left out. If code reads the field directly in some places, the move breaks them. Encapsulate first.
Persisted data. If the field is stored in a database or a file format, the move is also a data migration. Plan the migration and the code change together.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool. Test after each step.
References
- Martin Fowler, Catalog of Refactorings, Move Field, the entry
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Move Field, motivation and mechanics
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 7, Moving Features Between Objects, Move Field
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 EZVNWS Edit this page History Report an error Markdown