Programming Search⌘K

Techniquecore

Extract variable

Also called Introduce Explaining Variable, Introduce Variable.

Give a part of a complex expression a name, by moving it into a local variable and using the variable in its place, so that the expression reads as the steps of a rule.

Family
refactoring
Intent
Name a part of an expression, so that a reader sees what it means and not only how it is computed.
Also called
Introduce Explaining Variable

Purpose

An expression can be correct and still hard to read. order.quantity * order.itemPrice - Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 + Math.min(order.quantity * order.itemPrice * 0.1, 100) computes a price, but the reader must take it apart to see the base price, the discount for quantity and the shipping.

Extract variable gives each part a name: basePrice, quantityDiscount, shipping. The expression becomes basePrice - quantityDiscount + shipping, which says the rule. The second edition of Refactoring gives the reason: a local variable names a piece of a complex expression, so that a reader sees its purpose, and a debugger can show its value.1

The refactoring changes the structure and keeps the behaviour. Its inverse is Inline Variable, and the first edition called it Introduce Explaining Variable.23

Steps

  1. Run the tests and see them pass.
  2. Check that the part of the expression has no side effect. Moving a call with a side effect to an earlier line can change the order of effects.
  3. Declare a local variable, preferably immutable (const, final, let in Rust), and set it to the part of the expression.
  4. Replace the part in the expression with the variable.
  5. Run the tests.
  6. If the same part appears more than once in the function, replace each copy, after a check that each one has the same value at that point.

When the name is useful outside the function, the second edition suggests Extract Function in place of a variable, so that other code can use the name too.1 In a class, that often means a method or a getter.

Example

The price formula is one expression with three ideas in it.

import assert from "node:assert/strict";

// Before: one expression, three ideas.
function priceBefore(order) {
  return (
    order.quantity * order.itemPrice -
    Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 +
    Math.min(order.quantity * order.itemPrice * 0.1, 100)
  );
}

// After: each idea has a name.
function price(order) {
  const basePrice = order.quantity * order.itemPrice;
  const quantityDiscount = Math.max(0, order.quantity - 500) * order.itemPrice * 0.05;
  const shipping = Math.min(basePrice * 0.1, 100);
  return basePrice - quantityDiscount + shipping;
}

for (const order of [
  { quantity: 1, itemPrice: 10 },
  { quantity: 500, itemPrice: 2 },
  { quantity: 501, itemPrice: 2 },
  { quantity: 2000, itemPrice: 3 },
]) {
  assert.equal(price(order), priceBefore(order));
}
assert.equal(price({ quantity: 2000, itemPrice: 3 }), 6000 - 225 + 100);
console.log("price: tests pass");
Output
price: tests pass

The second version also reuses basePrice in the shipping rule, where the first version wrote the product out a second time. A reader now sees that shipping is ten percent of the base price, up to 100.

Language What the example shows
JavaScript three parts of a price named, as above
Python the same three parts, and a condition named with a boolean variable
Go the same three parts, in the form that gopls extracts
PythonGitHub
from datetime import date


# Before: one expression, three ideas.
def price_before(quantity, item_price):
    return (
        quantity * item_price
        - max(0, quantity - 500) * item_price * 0.05
        + min(quantity * item_price * 0.1, 100)
    )


# After: each idea has a name.
def price(quantity, item_price):
    base_price = quantity * item_price
    quantity_discount = max(0, quantity - 500) * item_price * 0.05
    shipping = min(base_price * 0.1, 100)
    return base_price - quantity_discount + shipping


for q, p in [(1, 10), (500, 2), (501, 2), (2000, 3)]:
    assert price(q, p) == price_before(q, p)


# A condition, named with a boolean variable.
def ships_today_before(order_day, hour, express):
    return (order_day.weekday() < 5 and hour < 14) or (express and hour < 18)


def ships_today(order_day, hour, express):
    is_workday = order_day.weekday() < 5
    before_cutoff = hour < 14
    express_window = express and hour < 18
    return (is_workday and before_cutoff) or express_window


for day in (date(2026, 11, 13), date(2026, 11, 14)):
    for hour in (9, 15, 19):
        for express in (False, True):
            assert ships_today(day, hour, express) == ships_today_before(day, hour, express)
print("price: tests pass")
Output
price: tests pass

The variables in ships_today are safe to extract because each part is a comparison with no side effect. If a part called a function that did work, extracting it would run that work even where and or or used to skip it.

package main

import (
	"fmt"
	"math"
)

// Before: one expression, three ideas.
func priceBefore(quantity, itemPrice float64) float64 {
	return quantity*itemPrice -
		math.Max(0, quantity-500)*itemPrice*0.05 +
		math.Min(quantity*itemPrice*0.1, 100)
}

// After: each idea has a name. gopls names an extracted variable newVar;
// the rename to a name that says the role is the programmer's step.
func price(quantity, itemPrice float64) float64 {
	basePrice := quantity * itemPrice
	quantityDiscount := math.Max(0, quantity-500) * itemPrice * 0.05
	shipping := math.Min(basePrice*0.1, 100)
	return basePrice - quantityDiscount + shipping
}

func main() {
	for _, c := range [][2]float64{{1, 10}, {500, 2}, {501, 2}, {2000, 3}} {
		if math.Abs(price(c[0], c[1])-priceBefore(c[0], c[1])) > 1e-9 {
			panic(fmt.Sprint("price ", c))
		}
	}
	fmt.Println("price: tests pass")
}
Output
price: tests pass

Go allows const only for constant expressions, so the extracted names are variables declared with :=. Each one is assigned once, which keeps it a name for one value. The test compares the two results with a tolerance, as is usual for floating-point values.

When to use

  • A complex expression. Name its parts, so that the expression reads as the rule.1
  • A complex condition. A variable such as isEligible or isWeekend names the test, and the if reads as the rule. This fixes a small Mysterious Name.
  • A repeated subexpression. Compute it once, after a check that each copy has the same value.
  • A value to watch in a debugger. A named variable can be inspected; a part of an expression usually cannot.

When the name is useful beyond this function, use Extract Function instead.1

Pitfalls

Side effects and order. Moving a part of an expression to an earlier line moves its evaluation. If it calls a function with an effect, or reads a value that the rest of the expression changes, the result can differ.

Short-circuit operators. In a && f(b), f(b) runs only if a is true. A variable const fb = f(b) before the if runs it always, which can throw or do work that was skipped before.

Names that repeat the code. const quantityTimesPrice = quantity * itemPrice adds a line and no meaning. Name the role, basePrice, not the computation.

Mutation. A variable that is assigned again later is not a name for one value. Keep extracted variables immutable, and see Split Variable when one variable holds several things.

Tools that do it

Tool Languages What it automates
IntelliJ IDEA Java, Kotlin Extract Variable, which places "the result of such expression or its part into a separate variable that is less complex and easier to understand"4
Visual Studio Code TypeScript, JavaScript Extract to constant: "Extract the selected expression to a new constant in the file."5
gopls Go refactor.extract.variable, which "replaces an expression by a reference to a new local variable named newVar initialized by the expression", and refactor.extract.variable-all for all copies in the function6
rust-analyzer Rust extract_variable, which "Extracts subexpression into a variable."7

The tools choose a placeholder name, such as newVar in gopls, and then start a rename. The name is the part of the refactoring that a tool cannot do.

References

  1. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 6, A First Set of Refactorings, Extract Variable, motivation and mechanics
  2. Martin Fowler, Catalog of Refactorings, Extract Variable, the entry; inverse of Inline Variable; alias Introduce Explaining Variable
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 6, Composing Methods, Introduce Explaining Variable
  4. IntelliJ IDEA documentation, Extract/Introduce variable, the introduction
  5. Visual Studio Code documentation, Refactoring TypeScript, Extract to constant
  6. gopls documentation, Code transformation features, refactor.extract.variable and refactor.extract.variable-all
  7. rust-analyzer manual, Assists, extract_variable

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/HTTQKT/text.yaml