Extract Variable takes part of a long expression and assigns it to a local variable whose name says what that part means. The logic stays the same. The difference is that a reader no longer has to decode the arithmetic or boolean soup to understand the rule. This guide uses an invented refund check from the ticketing service at Harbour Hall, a 1,200-seat concert venue. You will see the same function in TypeScript, Python and PHP, before and after the refactoring, along with the steps to get there safely.
The problem
A situation where the obvious design starts to hurt.
Harbour Hall's refund rule fits in one sentence: refund a ticket if the show is more than 48 hours away, the ticket was not bought on resale, and it was paid for within 30 days, unless the buyer is a premium member. The code that implements it is one return statement with millisecond arithmetic, a negated comparison and a nested || inside an &&.
Because the expression is hard to read, someone added a comment that restates it in English. Now there are two copies of the rule, and only one is checked by the compiler. When the 48-hour cutoff changes to 72, the code will get updated and the comment probably won't.
Before and after
The same code, before and after the change.
Before
type Customer = { tier: "standard" | "premium" };
type Order = {
eventStart: Date;
paidAt: Date;
source: "box-office" | "online" | "resale";
customer: Customer;
};
function isRefundable(order: Order, now: Date): boolean {
// Refund if the show is more than 48 hours away, the ticket was not bought on resale,
// and it was paid for within 30 days (premium members are exempt from the 30-day limit).
return (
order.eventStart.getTime() - now.getTime() > 48 * 60 * 60 * 1000 &&
order.source !== "resale" &&
(now.getTime() - order.paidAt.getTime() <= 30 * 24 * 60 * 60 * 1000 ||
order.customer.tier === "premium")
);
}
const order: Order = {
eventStart: new Date("2025-03-08T20:00:00Z"),
paidAt: new Date("2025-02-10T09:00:00Z"),
source: "online",
customer: { tier: "standard" },
};
console.log(isRefundable(order, new Date("2025-03-01T12:00:00Z"))); // truefrom dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@dataclass
class Customer:
tier: str # "standard" or "premium"
@dataclass
class Order:
event_start: datetime
paid_at: datetime
source: str # "box-office", "online" or "resale"
customer: Customer
def is_refundable(order: Order, now: datetime) -> bool:
# Refund if the show is more than 48 hours away, the ticket was not bought on resale,
# and it was paid for within 30 days (premium members are exempt from the 30-day limit).
return (
order.event_start - now > timedelta(hours=48)
and order.source != "resale"
and (now - order.paid_at <= timedelta(days=30) or order.customer.tier == "premium")
)
order = Order(
event_start=datetime(2025, 3, 8, 20, 0, tzinfo=timezone.utc),
paid_at=datetime(2025, 2, 10, 9, 0, tzinfo=timezone.utc),
source="online",
customer=Customer(tier="standard"),
)
print(is_refundable(order, datetime(2025, 3, 1, 12, 0, tzinfo=timezone.utc))) # True<?php
final class Customer
{
public function __construct(public readonly string $tier) {}
}
final class Order
{
public function __construct(
public readonly DateTimeImmutable $eventStart,
public readonly DateTimeImmutable $paidAt,
public readonly string $source,
public readonly Customer $customer,
) {}
}
function isRefundable(Order $order, DateTimeImmutable $now): bool
{
// Refund if the show is more than 48 hours away, the ticket was not bought on resale,
// and it was paid for within 30 days (premium members are exempt from the 30-day limit).
return $order->eventStart->getTimestamp() - $now->getTimestamp() > 48 * 60 * 60
&& $order->source !== 'resale'
&& ($now->getTimestamp() - $order->paidAt->getTimestamp() <= 30 * 24 * 60 * 60
|| $order->customer->tier === 'premium');
}
$order = new Order(
new DateTimeImmutable('2025-03-08T20:00:00Z'),
new DateTimeImmutable('2025-02-10T09:00:00Z'),
'online',
new Customer('standard'),
);
var_dump(isRefundable($order, new DateTimeImmutable('2025-03-01T12:00:00Z'))); // bool(true)After
type Customer = { tier: "standard" | "premium" };
type Order = {
eventStart: Date;
paidAt: Date;
source: "box-office" | "online" | "resale";
customer: Customer;
};
const HOUR_MS = 60 * 60 * 1000;
const DAY_MS = 24 * HOUR_MS;
function isRefundable(order: Order, now: Date): boolean {
const msUntilShow = order.eventStart.getTime() - now.getTime();
const showIsMoreThan48HoursAway = msUntilShow > 48 * HOUR_MS;
const boughtOnResale = order.source === "resale";
const msSincePayment = now.getTime() - order.paidAt.getTime();
const paidWithin30Days = msSincePayment <= 30 * DAY_MS;
const isPremiumMember = order.customer.tier === "premium";
const withinPaymentWindow = paidWithin30Days || isPremiumMember;
return showIsMoreThan48HoursAway && !boughtOnResale && withinPaymentWindow;
}
const order: Order = {
eventStart: new Date("2025-03-08T20:00:00Z"),
paidAt: new Date("2025-02-10T09:00:00Z"),
source: "online",
customer: { tier: "standard" },
};
console.log(isRefundable(order, new Date("2025-03-01T12:00:00Z"))); // truefrom dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@dataclass
class Customer:
tier: str # "standard" or "premium"
@dataclass
class Order:
event_start: datetime
paid_at: datetime
source: str # "box-office", "online" or "resale"
customer: Customer
def is_refundable(order: Order, now: datetime) -> bool:
time_until_show = order.event_start - now
show_is_more_than_48_hours_away = time_until_show > timedelta(hours=48)
bought_on_resale = order.source == "resale"
time_since_payment = now - order.paid_at
paid_within_30_days = time_since_payment <= timedelta(days=30)
is_premium_member = order.customer.tier == "premium"
within_payment_window = paid_within_30_days or is_premium_member
return show_is_more_than_48_hours_away and not bought_on_resale and within_payment_window
order = Order(
event_start=datetime(2025, 3, 8, 20, 0, tzinfo=timezone.utc),
paid_at=datetime(2025, 2, 10, 9, 0, tzinfo=timezone.utc),
source="online",
customer=Customer(tier="standard"),
)
print(is_refundable(order, datetime(2025, 3, 1, 12, 0, tzinfo=timezone.utc))) # True<?php
final class Customer
{
public function __construct(public readonly string $tier) {}
}
final class Order
{
public function __construct(
public readonly DateTimeImmutable $eventStart,
public readonly DateTimeImmutable $paidAt,
public readonly string $source,
public readonly Customer $customer,
) {}
}
const HOUR_SECONDS = 60 * 60;
const DAY_SECONDS = 24 * HOUR_SECONDS;
function isRefundable(Order $order, DateTimeImmutable $now): bool
{
$secondsUntilShow = $order->eventStart->getTimestamp() - $now->getTimestamp();
$showIsMoreThan48HoursAway = $secondsUntilShow > 48 * HOUR_SECONDS;
$boughtOnResale = $order->source === 'resale';
$secondsSincePayment = $now->getTimestamp() - $order->paidAt->getTimestamp();
$paidWithin30Days = $secondsSincePayment <= 30 * DAY_SECONDS;
$isPremiumMember = $order->customer->tier === 'premium';
$withinPaymentWindow = $paidWithin30Days || $isPremiumMember;
return $showIsMoreThan48HoursAway && !$boughtOnResale && $withinPaymentWindow;
}
$order = new Order(
new DateTimeImmutable('2025-03-08T20:00:00Z'),
new DateTimeImmutable('2025-02-10T09:00:00Z'),
'online',
new Customer('standard'),
);
var_dump(isRefundable($order, new DateTimeImmutable('2025-03-01T12:00:00Z'))); // bool(true)Why it's worth it
What the change buys you.
Each extracted variable turns a fragment of mechanics into a statement of intent. msUntilShow > 48 * HOUR_MS is still there, but the reader meets it under the name showIsMoreThan48HoursAway, and the final return line reads almost word for word like the business rule. That line is now the documentation, so the comment that duplicated it can go.
Naming the parts also makes the structure visible. In the original, the grouping of paidWithin30Days || isPremiumMember depended on a pair of parentheses buried mid-expression. Pulling it into withinPaymentWindow makes the precedence explicit and hard to break by accident.
Finally, debugging gets easier. You can set a breakpoint or log one named value instead of re-evaluating pieces of a compound condition in your head. The function has no side effects, so evaluating every sub-expression up front rather than short-circuiting changes nothing about the result.
- The return statement reads like the business rule, so reviewers can check it against the spec at a glance.
- Comments that restated the expression can be deleted, leaving one source of truth that the compiler checks.
- Operator precedence becomes explicit, which protects the logic from accidental edits to parentheses.
- Each intermediate value can be inspected in a debugger or logged by name.
- Named pieces are ready to be promoted into their own functions if another part of the code needs them.
Careful with
- Extracting operands of
&&or||into variables evaluates all of them eagerly. That is safe here, but if a sub-expression has side effects, is expensive, or guards against null (likeuser && user.name), keep the short-circuit or extract a function instead. - A vague name such as
check1ortempadds a line without adding meaning. If you cannot find a good name, you may not yet understand what that piece does. - If the same expression appears in several functions or the variable is useful outside this scope, a local variable is not enough. Consider Extract Function or Replace Temp with Query.
- Do not split every token into its own variable. Stop when each line expresses one idea a reader can grasp at once.
Step by step
Small, safe steps, with the tests passing after each.
Make sure tests cover the function's branches: show under and over 48 hours away, resale and non-resale, paid inside and outside 30 days, standard and premium. Run them and confirm they pass.
Pick one self-contained sub-expression, starting with the innermost, such as
order.eventStart.getTime() - now.getTime(). Check that it has no side effects.Declare a local constant just above the return with a name that states what the value means, for example
msUntilShow, and assign the sub-expression to it.Replace the sub-expression in the original line with the new variable. Run the tests.
Repeat for the next piece: the 48-hour comparison, the resale check, the payment age, the 30-day comparison and the premium check, running tests after each extraction.
Extract the grouped condition
paidWithin30Days || isPremiumMemberintowithinPaymentWindowso the precedence is named rather than implied by parentheses. Run the tests.Replace magic numbers like
60 * 60 * 1000with named constants such asHOUR_MS. Run the tests.Read the final return line aloud. If it states the rule clearly, delete the explaining comment and run the tests one last time.
Smells it removes
Smells this refactoring helps remove.
Common questions
Short answers to the usual doubts.
When should I use Extract Variable instead of Extract Function?
Use Extract Variable when the meaning is only relevant inside the current function and you want a quick, low-risk naming step. Choose Extract Function when the same calculation is needed elsewhere, when it belongs conceptually to another class, or when you want to test it in isolation. Extract Variable is often a first step: once a piece has a good name, promoting it to a function is easy.
Does introducing extra variables hurt performance?
In practice, no. Modern compilers and interpreters handle a few local variables trivially. The only real behavioural difference is the loss of short-circuit evaluation when you extract operands of && or ||, which matters only if those operands are costly or have side effects.
Should the extracted variables be constants?
Yes, wherever the language allows it. Use const in TypeScript, and treat the Python and PHP locals as assigned once. A variable that is reassigned later is no longer a simple name for an expression and makes the function harder to follow.
How would I explain this refactoring in an interview?
Say that you name a complex expression so the code states its intent, that you do it one sub-expression at a time with tests green after each step, and that you watch for side effects and short-circuit logic. Then point out when you would go further and extract a function instead.