Workflow L3 · Workflows informational

Refactor With Claude in Named, Behaviour-Preserving Steps

What it is

Refactoring by asking Claude for one named, behaviour-preserving move at a time — extract this function, rename that concept, inline this variable — each verifiable on its own.

one named move at a time01Extract02Rename03Inline04Verify
Each step is a refactor with a name — and a green test after it.

Why it works

A refactor should never change behaviour. Big 'clean this up' rewrites quietly do, and you can't tell which change caused a regression. Named single moves keep each step reviewable and reversible, and a passing test after each one proves behaviour held.

When to use it

Improving existing code you intend to keep — reducing duplication, clarifying names, untangling a long function. Best with tests in place to confirm nothing changed.

When not to use it

When you actually want new behaviour, that's not refactoring — say so, and treat it as a change with its own review.

Prompt

Refactor this code one step at a time, preserving behaviour exactly.

Start with a single named move (e.g. 'extract the validation into its own function'), show only that diff, and tell me how to confirm behaviour is unchanged. Wait for me before the next step.

<code>

Example

Faced with a 90-line handler, Claude first extracts three helpers (behaviour identical, tests green), then renames a misleading variable — each a small diff you can actually review.

Advanced version

Ask Claude to list the sequence of named moves first, as a plan, before executing any. Reviewing the plan catches a bad direction before a single line changes — the same instinct as designing before you code.

Common mistakes

  • Accepting a big rewrite labelled 'refactor' that silently alters behaviour.
  • Refactoring without tests, so 'preserves behaviour' is a hope, not a fact.
  • Letting Claude bundle a bug fix into the refactor, mixing two kinds of change in one diff.

Related