Skip to content

commandCode quality

Extract Function

Pulls a block of code into a well-named function with few parameters, updates the callers and checks nothing else changed.

npx workspacetemplates add extract-function --tool claude-code

Writes 1 file to .claude/commands/

.claude/commands/extract-function.md16 lines · 1.3 KBFile
---
description: Pulls a block of code into a well-named function with few parameters, updates the callers and checks nothing else changed.
argument-hint: "[file:start-end or description of the block]"
---

Extract a function from: $ARGUMENTS

1. Read the surrounding function. Identify the block and mark every variable it reads (becomes a parameter), writes (becomes a return value) and any side effect (I/O, mutation, logging).
2. Reject the extraction if the block exits the outer function (early return, break, throw) in several ways and the result would need flags. Explain and suggest a different boundary.
3. Choose a verb-noun name that describes the purpose, not the steps. Keep parameters to three or fewer; group related ones into an object only if they already travel together.
4. Prefer a pure function. If it must touch state, keep that visible in the signature.
5. Place it near its only caller if private, or in the right shared module if two places use it. Match the file's style and add types or docstrings as neighbors do.
6. Replace the original block, and replace duplicates elsewhere only when they are truly identical.
7. Run tests and the type check. Add a direct test for the new function when it has logic.

Show the new function and the changed call site. Ask before touching duplicates in other files.

What it does

The easiest way to shorten a long function is to lift a coherent block out of it. Doing that well means choosing a name that says the purpose, passing only what the block needs and returning only what the caller uses.

This command checks which variables the block reads and writes before moving it, so it does not smuggle in hidden state or change evaluation order.

Example

you › /extract-function src/orders/checkout.py lines 88-121

agent › Extracted applyLoyaltyDiscount(order, tier) -> Money, pure, 2 parameters. Replaced the block at line 88; one identical copy exists in cart.py.
3 new tests, suite green.
Update the copy in cart.py too?

Questions

Why would it refuse an extraction?
When the block returns early or throws from several places, a clean function boundary does not exist and forcing one makes the code worse.
Does it also remove copies elsewhere?
Only identical ones, and only after you say yes.
  • Add Error Handling

    CommandCode quality

    Free
  • Add Logging

    CommandCode quality

    Free
  • Add Types

    CommandCode quality

    Free
  • Find Dead Code

    CommandCode quality

    Free