/refactor-safely: behavior-preserving refactor with characterization tests
A Claude Code slash command for refactoring a named function, class or module without changing behavior: it pins current behavior with tests first, then changes the code in small verified steps.
Skill in Engineering by AISkillHub Library
What it does
Refactors break things when behavior changes slip in alongside structural changes. `/refactor-safely` gives Claude Code a strict procedure that keeps those separate.
**The procedure** 1. **Scope**: you name the target and the goal (for example "split `OrderService.checkout` into smaller functions" or "replace the switch on `type` with a lookup table"). Claude lists the public surface that must not change: exported names, signatures, return shapes, side effects, errors thrown. 2. **Pin behavior**: checks existing test coverage of the target. If coverage is thin, it writes characterization tests that record current behavior, including odd edge cases, and runs them green before touching the code. 3. **Small steps**: performs one mechanical change at a time (extract function, rename local, inline variable, move code, replace conditional) and runs the tests after each step. 4. **Stop on red**: if a test fails, it undoes that step rather than "fixing" the test. 5. **Report**: lists each step, final test results, and anything it noticed but did not change, such as suspected bugs (which are preserved, not fixed, in a refactor).
**What it will not do** It will not change public interfaces unless you ask, fix bugs mid-refactor, reformat unrelated code, or combine the refactor with feature work. If the target has no test runner available, it stops and tells you rather than refactoring blind.
**Example** `/refactor-safely src/pricing/discounts.ts: flatten the nested ifs in applyDiscount` Result: 9 characterization tests added, 4 steps, all green, one suspected bug noted (negative quantities produce a negative discount) and left unchanged.
How to use it
1. Save the file below as `.claude/commands/refactor-safely.md`. 2. Run `/refactor-safely <target>: <goal>`, for example `/refactor-safely app/Services/InvoiceService.php: extract tax calculation into its own class`. 3. Commit or stash first so the refactor is a clean, reviewable diff. 4. Keep the characterization tests if they are useful; delete any that only pin accidental behavior after review.
Files
Save each file at the path shown, relative to your project root.