Techniquecore
Slide statements
Also called consolidate duplicate conditional fragments.
Move statements up or down so that code that works on the same thing is together, after checking that the move does not change what the code does; a usual first step before Extract Function.
- Family
- refactoring
- Intent
- Put related statements next to each other so that the code reads in one piece and can be extracted.
- Also called
- Consolidate Duplicate Conditional Fragments
Purpose
Code is easier to read when statements that work on the same data sit together. A variable declared at the top of a function and first used thirty lines down makes the reader hold it in mind for those thirty lines. Two lines that belong together, with unrelated lines between them, cannot be extracted as one function.
Slide statements moves statements up or down to fix that. The catalogue card moves the line that reads the unit charge of a pricing plan up, next to the line that gets the plan.1 The book uses the move most often as a step before Extract Function, and to declare a variable right before its first use.2
The catalogue lists Consolidate Duplicate Conditional Fragments as an alias.1 That first-edition refactoring moves the same statement out of every branch of a conditional, to before or after it.3 In the second edition this is one case of sliding: slide the copy in each branch to the edge of the branch, and then out.2
Steps
- Find the place to move the statements to.
- Look at each statement between the old place and the target place, and check that the move does not change what the code does.2 The rules:
- Do not slide a statement above the declaration of anything it uses.
- Do not slide a statement below anything that uses what it declares or changes.
- Do not slide a statement past another statement that changes something it uses.
- Do not slide a statement that changes something past another statement that uses that thing.
- Cut the statements from the old place and paste them in the target place.
- Test.
If a test fails, the move crossed a dependency. Go back, and try a smaller slide.
Example
A function to price a booking mixes the lines for the base price with the lines for the discount. After sliding, the discount lines sit together and are ready for Extract Function. The conditional also had the same line at the end of both branches; that line slides out, below the if.
import assert from "node:assert/strict";
function priceBefore(b) {
const base = b.nights * b.rateCents;
const loyal = b.stays >= 5;
const tax = Math.round(base * 0.1);
let discount = 0;
let total;
if (loyal) { discount = Math.round(base * 0.05); total = base + tax - discount; }
else { total = base + tax - discount; }
return total;
}
function priceAfter(b) {
const base = b.nights * b.rateCents;
const tax = Math.round(base * 0.1);
const loyal = b.stays >= 5; // slid down, next to its use
let discount = 0;
if (loyal) discount = Math.round(base * 0.05);
return base + tax - discount; // the duplicate line slid out of both branches
}
for (const b of [{ nights: 3, rateCents: 9000, stays: 1 }, { nights: 2, rateCents: 12000, stays: 7 }]) {
assert.equal(priceAfter(b), priceBefore(b));
}
assert.equal(priceAfter({ nights: 2, rateCents: 12000, stays: 7 }), 25200);
console.log("slide statements: tests pass");
slide statements: tests pass
Each slide was legal: the loyal line uses only b, which is declared above, and the line that computes the total ran last in both branches, so moving it after the if does not change the order of anything it depends on.
| Language | What the example shows |
|---|---|
| JavaScript | a declaration slid next to its use, and a duplicate line slid out of both branches, as above |
| Python | a slide that is not legal, because a statement in between changes a value the moved line reads, and the test that catches it |
| Go | the same slides as above, ready for an extracted function |
class Cart:
def __init__(self):
self.items: list[int] = []
def add(self, cents: int) -> None:
self.items.append(cents)
def checkout_ok(cart: Cart) -> tuple[int, int]:
count = len(cart.items) # read before the call that changes the cart
cart.add(500) # shipping is added as an item
total = sum(cart.items)
return count, total
def checkout_bad_slide(cart: Cart) -> tuple[int, int]:
cart.add(500)
count = len(cart.items) # slid below a statement that changes what it reads
total = sum(cart.items)
return count, total
def fresh() -> Cart:
c = Cart()
c.add(1200)
c.add(800)
return c
assert checkout_ok(fresh()) == (2, 2500)
# The test catches the illegal slide: the count now includes the shipping item.
assert checkout_bad_slide(fresh()) != checkout_ok(fresh())
print("slide statements: tests pass")
slide statements: tests pass
package main
import "fmt"
type Booking struct{ Nights, RateCents, Stays int }
func price(b Booking) int {
base := b.Nights * b.RateCents
tax := base / 10
// The discount lines slid together; they can now be extracted.
loyal := b.Stays >= 5
discount := 0
if loyal {
discount = base * 5 / 100
}
return base + tax - discount // slid out of both branches
}
func main() {
if got := price(Booking{3, 9000, 1}); got != 29700 {
panic(got)
}
if got := price(Booking{2, 12000, 7}); got != 25200 {
panic(got)
}
fmt.Println("slide statements: tests pass")
}
slide statements: tests pass
When to use
- Before Extract Function. Bring the lines you want to extract together.2
- Declaration far from use. Move a declaration next to its first use.
- The same statement in each branch. Slide it out of the conditional, the old Consolidate Duplicate Conditional Fragments.3
- Before Split Loop. Related work is easier to split when it sits together. See Split Loop.
Pitfalls
Side effects. A function call between the old and the target place can change state that the moved line reads, or read state that it writes. If you cannot see what a call does, you cannot be sure the slide is safe. See side effect.
Long slides. A long slide passes many statements and has more chances to cross a dependency. Make many short slides, each with a test.
Tests that do not reach. If no test covers the path through the moved lines, a broken slide passes the tests. Check coverage before a slide over a branch.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool. The check of step 2 is yours, and so is the test of step 4.
References
- Martin Fowler, Catalog of Refactorings, Slide Statements, the entry; aliases Consolidate Duplicate Conditional Fragments
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Slide Statements, motivation, mechanics and the example with conditionals
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 9, Simplifying Conditional Expressions, Consolidate Duplicate Conditional Fragments
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 WW9AQW Edit this page History Report an error Markdown