Why this prompt works
This refactor code prompt makes "keep the behaviour exactly the same" the first rule, because the biggest risk in any cleanup is a quiet change in what the code does. Listing what must not change, such as public names and return formats, protects the code that calls this function.
Asking for a numbered list of changes with reasons makes the result easy to review in a pull request. Separating possible bugs from the refactor keeps two kinds of change apart, so a cleanup never slips in a behaviour change nobody approved.
How to use this prompt
- Tap "Copy prompt".
- Replace every part in [square brackets] with your own details.
- Paste it into ChatGPT or Claude and send.
- Ask a follow-up like "make it shorter" or "give me 3 more options" to fine-tune it.
Variations to try
Split a long function
- Type
- Text
- Fill in
- 3 blanks
- Copies
- Be the first
Modernise old syntax
- Type
- Text
- Fill in
- 5 blanks
- Copies
- Be the first
Remove duplication
- Type
- Text
- Fill in
- 2 blanks
- Copies
- Be the first
Make it your own
- Add your linter rules or style guide so the output passes CI on the first try.
- Ask for type hints or TypeScript types as part of the refactor.
- Add "Explain each change for a junior developer" if the refactor is for teaching.
Common problems and fixes
- The refactor changes behaviour. Write or ask for tests first, then refactor, and run them after.
- The AI adds clever but hard-to-read code. Add "prefer simple code a junior developer can read over shorter code".
FAQ
Should I refactor and fix bugs at the same time?
No. Refactor first with tests passing, then fix bugs in a separate change. It makes both easier to review.
How big a piece of code can I paste?
One function or class at a time works best. For whole files, ask for a refactoring plan first.