Community코딩 & 개발github.com

extract-function

Turn a coherent block of code into a well-named function without changing behavior. Use when a block needs a comment to be understood, a function is long or mixes levels of abstraction, logic is duplicated, or a loop or conditional arm does several jobs. Scans the target file, proposes candidates and names, and edits only after approval.

extract-function란 무엇인가요?

extract-function is a Claude Code agent skill that turn a coherent block of code into a well-named function without changing behavior. Use when a block needs a comment to be understood, a function is long or mixes levels of abstraction, logic is duplicated, or a loop or conditional arm does several jobs. Scans the target file, proposes candidates and names, and edits only after approval.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Bouzidi-Youssef/refactor-skill/tree/HEAD/.opencode/skills/extract_function

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

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 if arm 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) for a * b).
  • You cannot name it without and, handle, process, manage, or helper. 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

  1. Read the whole file. Know the fragment's inputs, outputs, side effects, and what runs after it.
  2. 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.
  3. Work on one extraction at a time, and run the checks after each one.

Steps

  1. Pick one fragment. Prefer the clearest intent and the smallest blast radius. When fragments nest, extract the innermost first.
  2. Name it after intent, not mechanics. A verb phrase that says what the caller gets: calculateOutstandingBalance, isEligibleForDiscount, printInvoiceHeader. Not loopOverItems, doCalculation, handleData.
  3. Choose the destination using the table below.
  4. Copy, do not improve. Move the fragment as-is. Resist renaming, reordering, or "fixing" while moving. One change at a time keeps failures attributable.
  5. Resolve variables using the table below.
  6. Replace the fragment with a call. Keep the argument order meaningful at the call site.
  7. Run the checks. If they fail, fix only what the extraction broke. If the fix requires a behavior change, stop and report.
  8. 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.
  9. 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

SituationAction
Declared and used only inside the fragmentMove the declaration into the new function.
Declared outside, only read insidePass it as a parameter, or capture it if the destination is a nested function.
Declared outside, read inside and used afterPass it as a parameter.
Declared outside, assigned inside, read afterReturn it.
Several variables assigned inside and read afterReturn a small result object, or split the extraction.
A parameter is reassigned inside the fragmentPrefer returning the new value over mutating the parameter.
Instance field read or writtenMake 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 valuePass 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

FragmentDestination
Uses instance statePrivate method on the same class
Pure, used by one callerModule-level function, or a nested function where the language supports it
Pure, used across the moduleModule-level function; export only if a caller outside the module needs it
Belongs to another conceptMethod on that object (the extraction is then followed by Move Function)

Naming

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

  • item is the loop variable → stays local.
  • lineTotal is declared and used only inside → stays local.
  • subtotal is 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:

  1. Confirm the target. Use the file named by the user. If none is named, ask for one. Read it completely before proposing anything.

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

  3. Propose before editing. Present the plan and wait for approval. Do not change files on the first pass.

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

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

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

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

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

extract-class

Split a class or module that has multiple responsibilities into smaller cohesive units. Use when a class has distinct clusters of fields and methods that change together, when a subset of behavior belongs to a separate concept, or when a class is hard to name because it does too much. Scans the target file, proposes extraction boundaries, and edits only after approval.

inline-function

Replace a function call with the function's body when the indirection adds no meaning. Use when a function body is as clear as its name, a wrapper only delegates, a helper is used once and forces unnecessary navigation, or bad factoring should be undone by inlining before re-extracting. Scans the target file, proposes candidates, and edits only after approval.

refactoring-router

Entry-point refactoring and rewrite skill. Use when the user wants to refactor, clean up, improve, simplify, or rewrite a codebase/file/module and needs smell-driven analysis, technique selection, or a new implementation approach. Detects refactor vs rewrite intent, asks type/mode/risk/scope/depth or ambition, then dispatches specialized subagents in an automatic loop. Triggers: "refactor this", "rewrite this", "clean this up", "improve this codebase", "reimplement this".

remove-dead-code

Delete code that is never executed, never referenced, or no longer reachable. Use when you find unused functions, variables, imports, parameters, branches, or files; when obsolete compatibility paths are no longer needed; or when dead code obscures behavior. Scans the target file, proposes safe deletions, and edits only after approval.

관련 스킬