Slide Statements is the smallest structural refactoring you can do. You move a line, or a few lines, up or down inside a function so that statements working on the same thing sit together. You add no logic and remove none. You only change the order. It rarely ships on its own. You use it to set up the next move, usually Extract Function, Split Variable or Replace Temp with Query. In an interview it shows you see the shape of a function before you cut it up, and that you know which reorderings are safe and which are not.
The problem
A situation where the obvious design starts to hurt.
Picture the checkout service for Harborline, a small ferry operator running routes between four islands. summarizeBooking builds a one-line summary for the confirmation email: the fare total including a vehicle surcharge, plus the loyalty points earned.
Over time, people added each new rule wherever there was room. The points counter is declared at the top, bumped after the fare loop, then bumped again after the vehicle fee. The fare calculation and the points calculation are braided together. You want to pull out computeTotal and computeLoyaltyPoints, but no contiguous block of lines belongs to just one of them, so any extraction would drag unrelated statements along or need awkward extra parameters.
Before and after
The same code, before and after the change.
Before
interface Leg {
baseFare: number;
}
interface Booking {
id: string;
passenger: string;
legs: Leg[];
vehicle: "car" | "bike" | null;
}
function summarizeBooking(b: Booking): string {
let points = 0;
const header = `Booking ${b.id} for ${b.passenger}`;
let fare = 0;
for (const leg of b.legs) {
fare += leg.baseFare;
}
points += b.legs.length * 5;
const vehicleFee = b.vehicle === "car" ? 18 : b.vehicle === "bike" ? 4 : 0;
if (b.legs.length >= 3) {
points += 25;
}
const total = fare + vehicleFee;
return `${header}: total ${total.toFixed(2)}, points ${points}`;
}
console.log(
summarizeBooking({
id: "HL-2041",
passenger: "Ines Moreau",
legs: [{ baseFare: 22.5 }, { baseFare: 14 }, { baseFare: 31 }],
vehicle: "car",
})
);
// Booking HL-2041 for Ines Moreau: total 85.50, points 40from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Leg:
base_fare: float
@dataclass(frozen=True)
class Booking:
id: str
passenger: str
legs: list[Leg]
vehicle: Optional[str]
def summarize_booking(b: Booking) -> str:
points = 0
header = f"Booking {b.id} for {b.passenger}"
fare = 0.0
for leg in b.legs:
fare += leg.base_fare
points += len(b.legs) * 5
vehicle_fee = {"car": 18, "bike": 4}.get(b.vehicle, 0)
if len(b.legs) >= 3:
points += 25
total = fare + vehicle_fee
return f"{header}: total {total:.2f}, points {points}"
print(
summarize_booking(
Booking("HL-2041", "Ines Moreau", [Leg(22.5), Leg(14), Leg(31)], "car")
)
)
# Booking HL-2041 for Ines Moreau: total 85.50, points 40<?php
final class Leg
{
public function __construct(public readonly float $baseFare) {}
}
final class Booking
{
/** @param Leg[] $legs */
public function __construct(
public readonly string $id,
public readonly string $passenger,
public readonly array $legs,
public readonly ?string $vehicle,
) {}
}
function summarizeBooking(Booking $b): string
{
$points = 0;
$header = "Booking {$b->id} for {$b->passenger}";
$fare = 0.0;
foreach ($b->legs as $leg) {
$fare += $leg->baseFare;
}
$points += count($b->legs) * 5;
$vehicleFee = match ($b->vehicle) {
'car' => 18,
'bike' => 4,
default => 0,
};
if (count($b->legs) >= 3) {
$points += 25;
}
$total = $fare + $vehicleFee;
return sprintf('%s: total %.2F, points %d', $header, $total, $points);
}
echo summarizeBooking(
new Booking('HL-2041', 'Ines Moreau', [new Leg(22.5), new Leg(14), new Leg(31)], 'car')
), PHP_EOL;
// Booking HL-2041 for Ines Moreau: total 85.50, points 40After
interface Leg {
baseFare: number;
}
interface Booking {
id: string;
passenger: string;
legs: Leg[];
vehicle: "car" | "bike" | null;
}
function summarizeBooking(b: Booking): string {
const header = `Booking ${b.id} for ${b.passenger}`;
let fare = 0;
for (const leg of b.legs) {
fare += leg.baseFare;
}
const vehicleFee = b.vehicle === "car" ? 18 : b.vehicle === "bike" ? 4 : 0;
const total = fare + vehicleFee;
let points = 0;
points += b.legs.length * 5;
if (b.legs.length >= 3) {
points += 25;
}
return `${header}: total ${total.toFixed(2)}, points ${points}`;
}
console.log(
summarizeBooking({
id: "HL-2041",
passenger: "Ines Moreau",
legs: [{ baseFare: 22.5 }, { baseFare: 14 }, { baseFare: 31 }],
vehicle: "car",
})
);
// Booking HL-2041 for Ines Moreau: total 85.50, points 40from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Leg:
base_fare: float
@dataclass(frozen=True)
class Booking:
id: str
passenger: str
legs: list[Leg]
vehicle: Optional[str]
def summarize_booking(b: Booking) -> str:
header = f"Booking {b.id} for {b.passenger}"
fare = 0.0
for leg in b.legs:
fare += leg.base_fare
vehicle_fee = {"car": 18, "bike": 4}.get(b.vehicle, 0)
total = fare + vehicle_fee
points = 0
points += len(b.legs) * 5
if len(b.legs) >= 3:
points += 25
return f"{header}: total {total:.2f}, points {points}"
print(
summarize_booking(
Booking("HL-2041", "Ines Moreau", [Leg(22.5), Leg(14), Leg(31)], "car")
)
)
# Booking HL-2041 for Ines Moreau: total 85.50, points 40<?php
final class Leg
{
public function __construct(public readonly float $baseFare) {}
}
final class Booking
{
/** @param Leg[] $legs */
public function __construct(
public readonly string $id,
public readonly string $passenger,
public readonly array $legs,
public readonly ?string $vehicle,
) {}
}
function summarizeBooking(Booking $b): string
{
$header = "Booking {$b->id} for {$b->passenger}";
$fare = 0.0;
foreach ($b->legs as $leg) {
$fare += $leg->baseFare;
}
$vehicleFee = match ($b->vehicle) {
'car' => 18,
'bike' => 4,
default => 0,
};
$total = $fare + $vehicleFee;
$points = 0;
$points += count($b->legs) * 5;
if (count($b->legs) >= 3) {
$points += 25;
}
return sprintf('%s: total %.2F, points %d', $header, $total, $points);
}
echo summarizeBooking(
new Booking('HL-2041', 'Ines Moreau', [new Leg(22.5), new Leg(14), new Leg(31)], 'car')
), PHP_EOL;
// Booking HL-2041 for Ines Moreau: total 85.50, points 40Why it's worth it
What the change buys you.
After the slides, the function reads as three paragraphs: the header, the money, the points. Each paragraph is a contiguous block that reads only the booking and writes only its own variables. That is exactly the shape Extract Function needs. You can now lift lines into computeTotal(b) and computeLoyaltyPoints(b) with one parameter each and a single return value, instead of threading a half-built points through the fare logic.
The reordering is safe because none of the moved statements depend on each other across groups. points is never read by the fare code, fare and vehicleFee are never read by the points code, and every expression is free of side effects: no I/O, no mutation of the booking, no calls that could throw in a different order. The rule you check before every slide is simple: a statement can move past another only if neither one writes something the other reads or writes. When that holds, the output is byte-for-byte the same.
- Turns a tangled function into contiguous blocks that Extract Function can lift with minimal parameters.
- Declares variables next to where they are used, so readers stop scrolling up to find an initial value.
- Each move is tiny and mechanical, so a failing test points straight at the one line you just moved.
- Makes hidden data dependencies visible: a statement that refuses to move is telling you something about coupling.
Careful with
- Never slide a statement past one with side effects, such as logging, writing to a database, emitting events or mutating a shared object, unless you have proved the order does not matter.
- Watch for exceptions: moving a call that can throw above a statement that commits state changes what happens on failure.
- In languages with getters or properties, an innocent-looking field read can run code. Check what it does before reordering.
- If a statement cannot move without breaking a dependency, stop and consider Split Variable or Split Loop first rather than forcing the slide.
Step by step
Small, safe steps, with the tests passing after each.
Make sure a test pins the current output, for example the
HL-2041booking producingtotal 85.50, points 40, plus a case with no vehicle and fewer than three legs.Pick the group you want to gather, here everything that touches
points, and list what each statement reads and writes.Slide
let points = 0down so it sits directly above the firstpoints +=line. Nothing between the old and new position readspoints, so the move is safe. Run the tests.Slide
points += b.legs.length * 5down past thevehicleFeeline, which neither reads nor writespoints. Run the tests.Slide the three points statements as a block below
const total = fare + vehicleFee, checking thattotaldoes not depend onpoints. Run the tests.Add blank lines between the header, fare and points groups so the paragraphs are visible, then commit.
Now apply Extract Function to each group in its own commit, running the tests after each extraction.
Smells it removes
Smells this refactoring helps remove.
Common questions
Short answers to the usual doubts.
How do I know a slide is safe without running anything?
Compare read and write sets. Two adjacent statements can swap if neither writes a variable the other reads or writes, and neither has an observable side effect. If either calls a function, you need to know that function is pure or at least independent of the other statement. When in doubt, rely on your tests and move one line at a time.
Is Slide Statements worth doing if I never extract anything afterwards?
Sometimes. Declaring a variable right before its first use and grouping related lines already makes code easier to read. But its main value is as preparation. If you slide lines and then leave the function just as long, mention in review that the extraction is the next step.
How does this relate to Split Loop?
They often travel together. If one loop accumulates both fare and points, sliding alone cannot separate them because both happen inside the same body. You split the loop first, giving two loops, and then slide each loop next to the rest of its group.
How should I talk about this in an interview?
Say it out loud when refactoring a long function: first I group the statements by concern, checking that nothing I move past has side effects or shared state, then I extract each group. It shows you treat reordering as a deliberate, verified step rather than a cosmetic shuffle.