Split Variable fixes a local variable that gets reassigned to hold something unrelated to its previous value. The variable might hold minutes, then a price, then a points total. You give each purpose its own variable, ideally a constant, named after what it holds. This is one of the smallest refactorings you can make. It still comes up in interviews and code reviews, because a reused variable usually sits in exactly the kind of function that is about to grow. When an interviewer hands you a messy function, splitting variables is often a safe first move. It makes the code readable enough that you can see what to extract next.
The problem
A situation where the obvious design starts to hurt.
Picture PedalPort, a bike-share operator. Its receipt function takes a ride's start and end timestamps in seconds, a per-minute rate and an unlock fee in cents. A single variable called temp first holds the billed minutes, then the charge in cents, then the loyalty points earned. Comments explain what temp currently means.
That is three meanings under one name. To work out what temp holds on any given line, you have to trace every assignment above it. If someone inserts a line between two assignments, they can easily read the wrong meaning. The variable also cannot be a constant, so nothing stops an accidental reassignment. And if you later want to extract the points calculation, you first have to untangle which temp it depends on.
Before and after
The same code, before and after the change.
Before
function rideReceipt(startedAt: number, endedAt: number, ratePerMinute: number, unlockFee: number): string {
// temp holds the billed minutes first
let temp = Math.ceil((endedAt - startedAt) / 60);
const lines: string[] = [`Ride time: ${temp} min`];
// now temp is the charge in cents
temp = unlockFee + temp * ratePerMinute;
lines.push(`Charge: ${(temp / 100).toFixed(2)}`);
// and finally the loyalty points
temp = Math.floor(temp / 100);
lines.push(`Points earned: ${temp}`);
return lines.join("\n");
}
console.log(rideReceipt(0, 725, 29, 100));import math
def ride_receipt(started_at: int, ended_at: int, rate_per_minute: int, unlock_fee: int) -> str:
# temp holds the billed minutes first
temp = math.ceil((ended_at - started_at) / 60)
lines = [f"Ride time: {temp} min"]
# now temp is the charge in cents
temp = unlock_fee + temp * rate_per_minute
lines.append(f"Charge: {temp / 100:.2f}")
# and finally the loyalty points
temp = temp // 100
lines.append(f"Points earned: {temp}")
return "\n".join(lines)
print(ride_receipt(0, 725, 29, 100))<?php
function rideReceipt(int $startedAt, int $endedAt, int $ratePerMinute, int $unlockFee): string
{
// $temp holds the billed minutes first
$temp = (int) ceil(($endedAt - $startedAt) / 60);
$lines = ["Ride time: {$temp} min"];
// now $temp is the charge in cents
$temp = $unlockFee + $temp * $ratePerMinute;
$lines[] = 'Charge: ' . number_format($temp / 100, 2, '.', '');
// and finally the loyalty points
$temp = intdiv($temp, 100);
$lines[] = "Points earned: {$temp}";
return implode("\n", $lines);
}
echo rideReceipt(0, 725, 29, 100), PHP_EOL;After
function rideReceipt(startedAt: number, endedAt: number, ratePerMinute: number, unlockFee: number): string {
const billedMinutes = Math.ceil((endedAt - startedAt) / 60);
const chargeCents = unlockFee + billedMinutes * ratePerMinute;
const pointsEarned = Math.floor(chargeCents / 100);
return [
`Ride time: ${billedMinutes} min`,
`Charge: ${(chargeCents / 100).toFixed(2)}`,
`Points earned: ${pointsEarned}`,
].join("\n");
}
console.log(rideReceipt(0, 725, 29, 100));import math
def ride_receipt(started_at: int, ended_at: int, rate_per_minute: int, unlock_fee: int) -> str:
billed_minutes = math.ceil((ended_at - started_at) / 60)
charge_cents = unlock_fee + billed_minutes * rate_per_minute
points_earned = charge_cents // 100
return "\n".join([
f"Ride time: {billed_minutes} min",
f"Charge: {charge_cents / 100:.2f}",
f"Points earned: {points_earned}",
])
print(ride_receipt(0, 725, 29, 100))<?php
function rideReceipt(int $startedAt, int $endedAt, int $ratePerMinute, int $unlockFee): string
{
$billedMinutes = (int) ceil(($endedAt - $startedAt) / 60);
$chargeCents = $unlockFee + $billedMinutes * $ratePerMinute;
$pointsEarned = intdiv($chargeCents, 100);
return implode("\n", [
"Ride time: {$billedMinutes} min",
'Charge: ' . number_format($chargeCents / 100, 2, '.', ''),
"Points earned: {$pointsEarned}",
]);
}
echo rideReceipt(0, 725, 29, 100), PHP_EOL;Why it's worth it
What the change buys you.
A variable name is a promise about what the variable holds. Once temp means three different things, the name promises nothing, and the comments have to do the job the name should have done. After the split, each value has one name and one assignment. You can read any line without scrolling up to see which meaning is live.
Each new variable is assigned exactly once, so it can be a const in TypeScript. In Python and PHP, which have no local constants, it is still single-assignment by convention. Data flow becomes explicit: pointsEarned depends on chargeCents, and chargeCents depends on billedMinutes. That dependency chain is what you need before you apply Extract Function or Replace Temp with Query. The comments become redundant and go away.
Behaviour is unchanged. For a 725-second ride at 29 cents a minute with a 100-cent unlock fee, both versions bill 13 minutes, charge 4.77 and award 4 points.
- Each name states what the value is, so readers no longer trace assignments to understand a line.
- Single-assignment variables can be constants, which turns accidental reassignment into a compile-time or lint error.
- Dependencies between values become visible, which makes Extract Function and Replace Temp with Query straightforward.
- Comments that existed only to track the variable's current meaning can be deleted.
Careful with
- Do not split accumulators. A running total or a string built up in a loop is one purpose updated many times, and it should stay a single variable.
- If the reused variable is a function parameter, the same idea applies, but the specific move is Remove Assignments to Parameters. Introduce a local instead of overwriting the argument.
- In loops, check whether a reassignment carries a value into the next iteration before you split it. Splitting a loop-carried value changes behaviour.
Step by step
Small, safe steps, with the tests passing after each.
Make sure tests cover the function's output, including the charge formatting and the points total, and that they pass.
Find the first assignment to the reused variable. Rename only that variable and its reads up to the next assignment, for example to
billedMinutes. Declare it withconstwhere the language allows. Run the tests.At the second assignment, declare a new variable such as
chargeCentsinstead of reassigning. Update the reads that follow, up to the next reassignment. Run the tests.Repeat for each remaining assignment, giving
pointsEarnedits own declaration. Run the tests.Confirm the old name is gone. If the compiler or linter reports reassignment of a constant, you missed a purpose.
Delete the comments that only explained what the variable held at each point, then simplify the surrounding code if the new names allow it. Run the tests.
Smells it removes
Smells this refactoring helps remove.
Common questions
Short answers to the usual doubts.
How is Split Variable different from Rename Variable?
Rename Variable changes the name of a variable that already has one clear purpose. Split Variable applies when one variable has several purposes. You create a new variable for each purpose, so one old name becomes several new ones, and each assignment gets its own declaration.
How do I tell a reused variable from a legitimate accumulator?
Check whether each new value is built from the previous value of the same quantity. A sum like total = total + item.price updates one thing, so it is an accumulator. If the new value means something else, like minutes turning into cents, the variable has more than one purpose and you should split it.
Does adding more variables hurt performance?
Not in any way you would measure. Compilers and interpreters handle short-lived locals cheaply, and the values are computed either way. The split changes names and scope, not the amount of work the function does.
Why would an interviewer care about such a small refactoring?
It shows you can make safe, incremental changes to unfamiliar code before restructuring it. Splitting variables first makes later steps, such as extracting the points calculation into its own function, easier to explain and lower risk while someone is watching you work.