
- Updated
Refactor messy code safely
This prompt refactors code to be cleaner while doing exactly the same thing. It renames unclear variables, splits long functions, removes duplication and adds short comments. Run your tests before and after.
Refactor this code to be cleaner without changing what it does. Language: [LANGUAGE] Code: [PASTE] Rename unclear variables, split long functions, remove duplication and add short comments only where the reason is not obvious. Show the new code, then list every change and confirm behaviour is unchanged. Do not add new features.
Run your tests before and after. Refactoring without tests is a gamble.
Get a better result
Your code rewritten with clearer names, shorter functions and less duplication, comments only where the reason is not obvious, plus a list of every change and a confirmation that behaviour is unchanged.
Refactoring should change shape, not behaviour, so the prompt bans new features and asks for confirmation that behaviour is the same. Listing every change makes it reviewable. Running tests before and after, as the tip says, is the real check.
The behaviour quietly changes.
Fix: Run your tests before and after, as the tip says, and compare outputs on a few real inputs.
- New features sneak in. Repeat “do not add features or change the public interface”, and diff the old and new code line by line.
- Pasted code is too long. Refactor one function or file at a time, and give the AI the surrounding context.
Before refactoring, ask the AI to write tests that pin down the current behaviour, then refactor and re-run them.
Do this as a series of small changes instead. Give me only the first change, such as renaming, with a commit message, and wait before the next one.
Guides on this topic
More chat & writing prompts
See all 465 →More like this
- Do a large refactor in small safe stepsClaude Code · Cursor
- Resolve a Git merge conflict safelyClaude · ChatGPT · Claude Code
- Make confusing code easy to readClaude · ChatGPT · Gemini
- Clean a messy spreadsheet with PythonClaude · ChatGPT · Gemini
- Convert code from one language to anotherChatGPT · Gemini · Claude



