Extract Function
Category A — Simplifying and restructuring functions
Turn a fragment of code into a function whose name states the fragment's intent, then replace the fragment with a call to that function.
Extraction is the most common refactoring. It is also the enabling move behind several others: once behavior has a name, you can move it, override it, compose it, or test it in isolation.
Motivation
The smell
Extract Function is the answer to several observable symptoms:
- A comment explains a block. The comment is the function name you have not written yet.
- A function is long, or reads as a sequence of phases ("validate…", "compute…", "render…") with no boundaries between them.
- One function mixes levels of abstraction: high-level policy sitting next to low-level detail.
- The same block, or a near-copy, appears more than once.
- A loop body or
ifarm performs several distinct jobs. - A temporary variable exists only to hold an intermediate result that has an obvious name.
- Changing one rule forces you to read code that has nothing to do with that rule.
Fowler's test: if you have to spend effort looking at a fragment of code to figure out what it is doing, extract it into a function and name it after the intent.
The design principle
- One job per function. A function should have one reason to be read, and its body should stay at one level of abstraction.
- Names are compression. A call to
applyLateFees(invoice)lets the reader skip the details and still know the effect. The name is a claim the body must keep true. - Locality. Once behavior lives in one named place, a change to that behavior has one obvious home, and a test can target it directly.
- Composition. Small named pieces can be reordered, reused, and replaced. Large unnamed blocks can only be copied.
- Behavior preservation. A refactoring changes structure, not observable behavior: same results, same side effects in the same order, same errors, same short-circuiting.
Extract Function is not:
- a way to add a feature or fix a bug — do that before or after, never inside the extraction;
- speculative reuse ("we might need this later");
- a way to turn a block into a vague helper.
When not to extract
- The fragment is a single clear expression; a name would only restate it (
multiply(a, b)fora * b). - You cannot name it without
and,handle,process,manage, orhelper. That usually means the fragment has more than one job; split it differently or extract a larger unit. - The extracted function needs so many parameters that the call is harder to read than the block. That is a signal to introduce a parameter object, or that the behavior belongs on another object.
- The code is in a measured hot loop and call overhead actually matters. Measure before believing this.
- The block mutates several surrounding variables. Restructure the data flow first; otherwise extraction only relocates the tangle.
Mechanic
Before you start
- Read the whole file. Know the fragment's inputs, outputs, side effects, and what runs after it.
- Find the project's existing safety net: type checker, linter, tests, or a runnable entry point. Use what exists. Do not add tests unless asked.
- Work on one extraction at a time, and run the checks after each one.
Steps
- Pick one fragment. Prefer the clearest intent and the smallest blast radius. When fragments nest, extract the innermost first.
- Name it after intent, not mechanics. A verb phrase that says what the caller gets:
calculateOutstandingBalance,isEligibleForDiscount,printInvoiceHeader. NotloopOverItems,doCalculation,handleData. - Choose the destination using the table below.
- Copy, do not improve. Move the fragment as-is. Resist renaming, reordering, or "fixing" while moving. One change at a time keeps failures attributable.
- Resolve variables using the table below.
- Replace the fragment with a call. Keep the argument order meaningful at the call site.
- Run the checks. If they fail, fix only what the extraction broke. If the fix requires a behavior change, stop and report.
- Clean up. Delete variables that are now unused, put the new function next to its caller, and rename it if the body revealed a better name.
- Look for reuse. If the same fragment exists elsewhere with identical behavior, route those call sites through the new function. Do not merge near-duplicates that merely look alike; that is a separate, behavior-changing decision.
Resolving variables
| Situation | Action |
|---|---|
| Declared and used only inside the fragment | Move the declaration into the new function. |
| Declared outside, only read inside | Pass it as a parameter, or capture it if the destination is a nested function. |
| Declared outside, read inside and used after | Pass it as a parameter. |
| Declared outside, assigned inside, read after | Return it. |
| Several variables assigned inside and read after | Return a small result object, or split the extraction. |
| A parameter is reassigned inside the fragment | Prefer returning the new value over mutating the parameter. |
| Instance field read or written | Make the new function a method on the same class. If it does not actually need instance state, pass the state explicitly instead. |
| Constant or configuration value | Pass it in, or reference it directly if that is the file's existing convention. |
Rules that keep the move safe:
- Preserve evaluation order and short-circuiting. Do not hoist a call above a guard that might skip it.
- Preserve side-effect order. Printing, writing, and throwing are behavior.
- Do not change visibility or public signatures unless the extraction requires it.
- Do not mix in unrelated cleanups. The diff should read as "this block became this call".
Choosing the destination
| Fragment | Destination |
|---|---|
| Uses instance state | Private method on the same class |
| Pure, used by one caller | Module-level function, or a nested function where the language supports it |
| Pure, used across the module | Module-level function; export only if a caller outside the module needs it |
| Belongs to another concept | Method on that object (the extraction is then followed by Move Function) |
Naming
| Weak | Better |
|---|---|
handleData() | applyLateFees(invoice) |
process() | calculateOutstandingBalance() |
check() | isEligibleForDiscount() |
doStuff() | notifyOverdueCustomers() |
loopItems() | sumLineItems() |
A good name describes the contract, not the loop. If the best name you can find is vague, the fragment is probably not one coherent job yet.
Example
The language is incidental; the same move applies in any language.
Before
type InvoiceItem = { name: string; price: number; quantity: number };
type Invoice = {
id: string;
customer: { name: string };
issuedAt: Date;
items: InvoiceItem[];
taxRate: number;
};
function printInvoice(invoice: Invoice): void {
// header
console.log(`Invoice ${invoice.id}`);
console.log(`Customer: ${invoice.customer.name}`);
console.log(`Issued: ${invoice.issuedAt.toISOString().slice(0, 10)}`);
// line items
let subtotal = 0;
for (const item of invoice.items) {
const lineTotal = item.price * item.quantity;
subtotal += lineTotal;
console.log(`${item.name} x${item.quantity} @ ${item.price} = ${lineTotal}`);
}
// totals
console.log(`Subtotal: ${subtotal}`);
const tax = subtotal * invoice.taxRate;
console.log(`Tax: ${tax}`);
console.log(`Total: ${subtotal + tax}`);
}
The comments mark three fragments. Each comment is a name waiting to be written.
Extraction 1: header
Name: printInvoiceHeader. It reads invoice, so invoice becomes a parameter. Nothing comes back.
function printInvoice(invoice: Invoice): void {
printInvoiceHeader(invoice);
// line items and totals unchanged for now
}
function printInvoiceHeader(invoice: Invoice): void {
console.log(`Invoice ${invoice.id}`);
console.log(`Customer: ${invoice.customer.name}`);
console.log(`Issued: ${invoice.issuedAt.toISOString().slice(0, 10)}`);
}
Extraction 2: line items
The loop is one job: print each line and add up the subtotal.
itemis the loop variable → stays local.lineTotalis declared and used only inside → stays local.subtotalis declared outside, written inside, and read after → must come back as the return value.
function printInvoice(invoice: Invoice): void {
printInvoiceHeader(invoice);
const subtotal = printLineItems(invoice.items);
// totals unchanged for now
}
function printLineItems(items: InvoiceItem[]): number {
let subtotal = 0;
for (const item of items) {
const lineTotal = item.price * item.quantity;
subtotal += lineTotal;
console.log(`${item.name} x${item.quantity} @ ${item.price} = ${lineTotal}`);
}
return subtotal;
}
Note what the extraction exposed: printLineItems both prints and computes. That is a real design question, but it is not this refactoring's job to answer it. Extract first; then decide whether to separate the query from the modifier.
Extraction 3: totals
Name: printInvoiceTotals. It reads subtotal and taxRate, so both become parameters; tax is local.
function printInvoice(invoice: Invoice): void {
printInvoiceHeader(invoice);
const subtotal = printLineItems(invoice.items);
printInvoiceTotals(subtotal, invoice.taxRate);
}
function printInvoiceTotals(subtotal: number, taxRate: number): void {
console.log(`Subtotal: ${subtotal}`);
const tax = subtotal * taxRate;
console.log(`Tax: ${tax}`);
console.log(`Total: ${subtotal + tax}`);
}
After
function printInvoice(invoice: Invoice): void {
printInvoiceHeader(invoice);
const subtotal = printLineItems(invoice.items);
printInvoiceTotals(subtotal, invoice.taxRate);
}
function printInvoiceHeader(invoice: Invoice): void { /* … */ }
function printLineItems(items: InvoiceItem[]): number { /* … */ }
function printInvoiceTotals(subtotal: number, taxRate: number): void { /* … */ }
printInvoice now reads as three named steps. Output is unchanged, and each step can be read, tested, and changed on its own.
A smaller case: naming a condition
Extraction is also how you name a boolean expression:
// before
if (order.customer.isPremium && order.total > 100 && order.destination !== "remote") {
return 0;
}
// after
if (hasFreeShipping(order)) {
return 0;
}
function hasFreeShipping(order: Order): boolean {
return order.customer.isPremium
&& order.total > 100
&& order.destination !== "remote";
}
This is the mechanical seed of Decompose Conditional, but the move is still Extract Function: one expression, one name, same behavior.
A non-example
function multiplyPriceByQuantity(price: number, quantity: number): number {
return price * quantity;
}
Unless lineTotal is a domain concept the file actually talks about, this name restates the code and adds no vocabulary. Extract when the name tells the reader something the expression does not.
Related refactorings
Extract Function often opens the door to a second move. Name the follow-up; do not perform it silently.
- Replace Temp with Query — when the extracted function is just a calculation assigned to a temporary.
- Decompose Conditional — when the fragment is a condition; Extract Function is its mechanical step.
- Introduce Parameter Object — when the extraction needs too many parameters.
- Move Function — when the extracted function belongs on another object.
- Separate Query from Modifier — when extraction exposes a function that both returns a value and changes state.
- Inline Function — the inverse; use it when an extraction added indirection without adding meaning.
Running this skill on a file
When invoked with @extract_function:
-
Confirm the target. Use the file named by the user. If none is named, ask for one. Read it completely before proposing anything.
-
Inventory candidates. For each candidate, report:
- location (function and line range),
- the smell (comment, mixed abstraction, duplication, multi-job loop or conditional, long function),
- the proposed name and destination,
- inputs, outputs, and side effects,
- risk: low (pure and local), medium (mutates locals or instance state), high (ordering, error behavior, or public API involved).
Order candidates safest first. Keep the list short; the best two or three are more useful than ten.
-
Propose before editing. Present the plan and wait for approval. Do not change files on the first pass.
-
Apply one extraction at a time. Use the smallest edit that achieves the move; do not rewrite the file wholesale. Match the file's existing style and idioms.
-
Run existing checks after each step. Do not add tests unless asked. If no checks exist, show the diff and state what was not verified.
-
Report. Say what moved, what stayed, what the extraction exposed, and which candidates remain. If an extraction revealed a follow-up refactoring, name it instead of doing it silently.
-
Stop and ask if the extraction would change behavior, if no honest name exists, or if the checks fail in a way that is not obviously caused by the move. Revert that step and report it.
Checklist
- The new name states intent, not mechanics.
- The fragment moved as-is; no behavior changed.
- Every outer variable is passed, returned, or made local deliberately.
- Evaluation order and side effects are preserved.
- The call site reads better than the block did.
- The new function sits near its caller and is no more visible than necessary.
- Checks pass, or the unverified risk is stated.