Plan a Safe Refactoring
Create a step-by-step refactoring plan that improves code without breaking things — with rollback points and verification at each step.
What it does
Refactoring is how good codebases stay good — but refactoring without a plan is how working code breaks. This prompt produces a sequenced refactoring plan with small, independently verifiable steps. Each step has a rollback point, so if something goes wrong at step 5, you don’t lose steps 1-4.
The Prompt
I need to refactor code safely. Help me plan the approach.
Code to refactor:
[PASTE THE CODE — or describe the module/system if it's too large to paste]
Language/framework: [LANGUAGE AND FRAMEWORK]
Why refactor: [WHAT PROBLEM ARE YOU SOLVING — readability? performance? adding a feature that the current structure makes hard?]
Constraints:
- [TEST COVERAGE: do you have tests? which parts are covered?]
- [DEPLOYMENT: can you deploy incrementally or is it all-or-nothing?]
- [TEAM: are others working in this area concurrently?]
Please produce:
1. ASSESSMENT: What's actually wrong with the current code? Separate "genuinely problematic" from "not how I'd write it." Only refactor what needs refactoring.
2. REFACTORING SEQUENCE: Break the work into the smallest possible steps, ordered so that:
- Each step leaves the code in a working, deployable state
- Each step can be verified independently (specify HOW to verify)
- Each step is a single, reviewable commit
- Earlier steps don't depend on later ones
For each step:
- What changes
- What to verify (specific test, behavior, or assertion)
- Rollback: how to undo this step without affecting others
- Risk: LOW / MEDIUM / HIGH and why
3. DANGER ZONES: Which parts of this refactoring are most likely to introduce bugs? What specific regressions should I watch for?
4. STOP CONDITIONS: Under what circumstances should I abandon this refactoring and revert? (e.g., "if step 3 reveals the module is used by X, the approach changes")
If the code doesn't need refactoring, say so. Not all ugly code is worth changing.
Usage Notes
- “Each step leaves the code in a working state” is the key constraint. If your refactoring plan has a step that breaks things temporarily, it’s not granular enough. Split it further.
- The STOP CONDITIONS step prevents the sunk-cost trap. Refactorings that reveal unexpected complexity should be paused and re-scoped, not pushed through.
- For large-scale refactoring (renaming a core abstraction, splitting a monolith), do this prompt per module rather than for the whole system at once.
- If you don’t have tests for the code you’re refactoring, the first step in your plan should always be “write characterization tests that capture current behavior.” Refactoring without tests is just editing and hoping.
- Pair with the Code Review prompt after each step is complete to catch issues before they compound.