Techniquecore
Move statements to callers
When some callers of a function need part of its behavior to be different, move that part out of the function into each caller; the inverse of Move Statements into Function.
- Family
- refactoring
- Intent
- Let callers vary a part of a function that no longer means the same thing for all of them.
Purpose
A function is a boundary: the statements inside it run for every caller. The boundary can be right when you draw it and wrong a year later, when one caller needs a step done another way. A flag parameter that switches the step, or a copy of the function, are poor fixes.
Move statements to callers moves the step out of the function into each caller. Callers that need the old behavior write it; the caller that needs a different behavior writes its own. The catalogue card moves the line that writes a photo's location out of emitPhotoData into its callers.1 The inverse is Move Statements into Function.1
The book describes this as the case where a behavior that was common to callers needs to vary for some of them.2 It is the most direct when the varying part is at the start or the end of the function.
Steps
- In a small case, with one or two callers, cut the statements from the function and paste them into each caller. Test. Stop here.2
- Otherwise, use Extract Function on all the statements that stay. Give the result a temporary name.2
- Inline the original function into each caller with Inline Function. Each caller now calls the extracted function and has the moved statements of its own.
- Rename the extracted function to the original name with Change Function Declaration, and test.
If the varying statements are in the middle of the function, first use Slide Statements to move them to the start or the end, if the order allows.
Example
A receipt function writes the items and then a footer. The till and the email both call it, but the email now needs a footer with an unsubscribe line. The footer moves to the callers.
import assert from "node:assert/strict";
const items = [{ name: "Tea", cents: 350 }, { name: "Scone", cents: 275 }];
// Before: the footer is inside, the same for every caller.
function receiptOld(items) {
const lines = items.map((i) => `${i.name} ${(i.cents / 100).toFixed(2)}`);
lines.push("Thank you!");
return lines;
}
// After: the function keeps what all callers share.
function receipt(items) { return items.map((i) => `${i.name} ${(i.cents / 100).toFixed(2)}`); }
const till = [...receipt(items), "Thank you!"];
const email = [...receipt(items), "Thank you!", "Unsubscribe: example.com/u"];
assert.deepEqual(till, receiptOld(items));
assert.deepEqual(email.slice(0, 3), receiptOld(items));
assert.equal(email.at(-1), "Unsubscribe: example.com/u");
console.log("move statements to callers: tests pass");
move statements to callers: tests pass
The till caller is the same as before. Without the move, the receipt function would need a parameter such as forEmail, which is a flag argument.
| Language | What the example shows |
|---|---|
| JavaScript | a footer moved out of the function into two callers, as above |
| Python | the mechanics for many callers: extract what stays, inline the old function, rename |
| Go | the same move, where each caller writes the footer to its own writer |
items = [("Tea", 350), ("Scone", 275)]
def receipt_old(items):
lines = [f"{n} {c / 100:.2f}" for n, c in items]
lines.append("Thank you!")
return lines
# Step 2: extract what stays, with a temporary name.
def receipt_lines(items):
return [f"{n} {c / 100:.2f}" for n, c in items]
# Step 3: inline the old function into each caller; the footer is now theirs.
till = receipt_lines(items) + ["Thank you!"]
email = receipt_lines(items) + ["Thank you!", "Unsubscribe: example.com/u"]
# Step 4: rename receipt_lines back to the old name.
receipt = receipt_lines
assert till == receipt_old(items)
assert email[:3] == receipt_old(items) and email[-1].startswith("Unsubscribe")
assert receipt(items) == ["Tea 3.50", "Scone 2.75"]
print("move statements to callers: tests pass")
move statements to callers: tests pass
package main
import (
"fmt"
"io"
"strings"
)
type Item struct {
Name string
Cents int
}
// After: WriteReceipt writes only what all callers share.
func WriteReceipt(w io.Writer, items []Item) {
for _, it := range items {
fmt.Fprintf(w, "%s %d.%02d\n", it.Name, it.Cents/100, it.Cents%100)
}
}
func main() {
items := []Item{{"Tea", 350}, {"Scone", 275}}
var till strings.Builder
WriteReceipt(&till, items)
till.WriteString("Thank you!\n") // moved to the caller
var email strings.Builder
WriteReceipt(&email, items)
email.WriteString("Thank you!\nUnsubscribe: example.com/u\n") // this caller varies it
if till.String() != "Tea 3.50\nScone 2.75\nThank you!\n" {
panic(till.String())
}
if !strings.HasPrefix(email.String(), till.String()) {
panic(email.String())
}
fmt.Println("move statements to callers: tests pass")
}
move statements to callers: tests pass
When to use
- One caller needs it different. A behavior common to all callers must vary for some of them.2
- A flag grows. A boolean parameter that switches a step in or out is a sign that the step belongs to the callers.
Pitfalls
Duplication. After the move, each caller has a copy of the statements. If most callers still need the same statements, that is Duplicated Code. Keep the move for the case where the callers really differ, or move the statements back later with the inverse.
Statements in the middle. A step in the middle of a function cannot move out without changing the order of what runs. If the order matters, consider passing the step in as a function argument, not moving it.
A boundary that moves again. The book's point is that boundaries shift as needs change; this refactoring and its inverse move them in the two directions.2
Tools that do it
This refactoring is a sequence of steps, not one action of a tool. The steps use Extract Function, Inline Function and Change Function Declaration; see those pages for the tools.
References
- Martin Fowler, Catalog of Refactorings, Move Statements to Callers, the entry; inverse of Move Statements into Function
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Move Statements to Callers, motivation and mechanics
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 | W3 standard |
|
Tag 675H79 Edit this page History Report an error Markdown