Skip to content

Extract Variable: Give a Complex Expression a Name

Learn how to break a dense conditional or calculation into well-named local variables so the code explains itself, with safe steps and examples.

7 min readRefactoring

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"))); // 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"))); // 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 (like user && user.name), keep the short-circuit or extract a function instead.
  • A vague name such as check1 or temp adds 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.

  1. 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.

  2. Pick one self-contained sub-expression, starting with the innermost, such as order.eventStart.getTime() - now.getTime(). Check that it has no side effects.

  3. 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.

  4. Replace the sub-expression in the original line with the new variable. Run the tests.

  5. 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.

  6. Extract the grouped condition paidWithin30Days || isPremiumMember into withinPaymentWindow so the precedence is named rather than implied by parentheses. Run the tests.

  7. Replace magic numbers like 60 * 60 * 1000 with named constants such as HOUR_MS. Run the tests.

  8. 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.

Next guide4 of 7 · Techniques: composing functionsSplit Loop: One Loop Doing Two Jobs Becomes Two LoopsRead the next one