Refactor legacy code without breaking it
Get a step-by-step refactoring plan for messy code, with safety tests first and small changes you can review and ship one at a time.
- Published
- Works with
- ChatGPT, Claude and Gemini
- Level
- Advanced
Rewriting old code in one go is how working features break. Safe refactoring means pinning current behaviour with tests, then making small changes that each keep the tests green. This prompt makes the AI work that way and stops it from quietly changing what the code does.
The prompt
You are a senior engineer who specialises in legacy code. Help me refactor this code safely.
Language and framework:
What the code does:
Main problems I see:
Constraints:
Code:
Work in this order:
1. Explain what the code currently does, including edge cases and odd behaviour. Flag anything that looks like a bug but don't fix it yet — list it separately.
2. Write characterisation tests that capture the current behaviour, including the odd parts.
3. Propose a sequence of 4–8 small refactoring steps (extract function, rename, remove duplication, etc.). Each step must keep behaviour identical.
4. Show the code after each step, with a one-line reason.
5. Finish with the final version and a list of the possible bugs from step 1 for me to decide on.
Do not change behaviour, invent APIs or add libraries. If something is unclear, ask instead of assuming.
How to use it
- Include the callers or tests if the function's use isn't obvious from the code alone.
- Run the characterisation tests on the original code first; they must pass before you refactor.
- Commit after each step so any break is easy to find and undo.
Tips
- For large files, refactor one function per conversation.
- Fix the flagged bugs in separate commits after the refactor, not during it.
Frequently asked questions
What does this prompt do?
Get a step-by-step refactoring plan for messy code, with safety tests first and small changes you can review and ship one at a time.
Which AI tools does it work with?
It is written for ChatGPT, Claude and Gemini. It also works in other AI tools that accept text prompts, with small changes.
What do I need to fill in?
5 blanks: language / framework and version; short description; e.g. long function, duplication, hard to test; public api must not change, no new dependencies, etc.; paste code. Click each blue blank on the page, type your details and press Copy prompt.
Is this prompt free to use?
Yes. You can copy and use it for personal and commercial work.