Skip to content

commandCode quality

Refactor

Refactors the code you name for clarity in small steps, running the tests after each step so behavior never changes.

npx workspacetemplates add refactor --tool claude-code

Writes 1 file to .claude/commands/

.claude/commands/refactor.md15 lines · 1.1 KBFile
---
description: Refactors the code you name for clarity in small steps, running the tests after each step so behavior never changes.
argument-hint: "[file, function or module]"
---

Refactor for clarity: $ARGUMENTS

1. Read the code and everything that calls it. Write down in two lines what it does today. Behavior must not change.
2. Run the test suite first and note the result. If the code is not covered, add characterization tests that capture current outputs, including odd cases, and run them green before any edit.
3. List the smells you see (long function, deep nesting, duplicated block, unclear names, mixed concerns) and propose at most five steps, smallest first.
4. Do one step at a time: make the change, run the tests, and move on only when green. If a test fails, undo that step with `git checkout -- <file>` on your own edit and rethink; do not edit the tests to pass.
5. Do not change public signatures, file names or formatting unrelated to the task.
6. Stop after the agreed steps; do not keep polishing.

Finish with the list of steps done, the test results after each, and the diff stat. Ask before committing.

What it does

Big-bang refactors break things and are hard to review. This command works in small steps, each one a change that keeps behavior identical, and runs the tests between them so a failure points at one edit.

If the code has no tests, it writes a few that pin down current behavior before touching anything. Each step is commit-sized, so you can stop at any point with working code.

Example

you › /refactor src/billing/invoice.ts calculateTotals

agent › Added 6 characterization tests (green). Steps: 1) extracted taxFor(), 2) replaced nested ifs with early returns, 3) renamed tmp and x to subtotal and discount. Tests green after each step.
Diff: 1 file, +41 -58.
Commit these changes?

Questions

What if there are no tests?
It writes tests that pin the present behavior first, since refactoring without a safety net is guessing.
Will it rename public functions?
Not unless you ask. Public names and signatures stay as they are, so callers keep working.
  • Add Error Handling

    CommandCode quality

    Free
  • Add Logging

    CommandCode quality

    Free
  • Add Types

    CommandCode quality

    Free
  • Extract Function

    CommandCode quality

    Free