Refactoring prompt to clean up messy code
Refactor a piece of code towards one goal you choose while keeping its behaviour the same, with each step explained and any risky change flagged.
- Category
- Coding
- Tags
- RefactoringCode review
- Added
- Added
Fill in the prompt
The prompt below changes as you type, and Copy prompt copies it filled in. What you type stays in this browser. Leave a box empty to fill it in after you paste.
The prompt
Refactor this {{language}} code. The goal: {{goal}}
{{code}}
Rules:
- Keep the behaviour exactly the same, including error cases and what gets logged. If a change would alter behaviour, list it separately as a suggestion and don't make it.
- Keep the public interface unless the goal says otherwise.
- Prefer small, named steps over a rewrite. Each step should leave the code working.
- Don't add abstractions, layers or patterns the goal doesn't need.
Reply with:
1. The steps you took, one line each, in order.
2. The refactored code.
3. Anything that looks like a bug you noticed but didn't fix.
4. The tests I should run, or write, to be sure nothing changed.
Replace each {{highlighted part}} with your own text before you send it.
How to use it
Use {{goal}} to say what better means for this code. "Make it cleaner" gets you a rewrite in the model's favourite style. "Split the 200-line handler into functions I can test on their own" gets you something you can review in one sitting.
Paste the code into {{code}}. Name the language and its version in {{language}}, because idioms change between versions, and without a version the model reaches for the newest syntax your build may not support.
Example for {{goal}}: "Remove the nested ifs and make the validation rules readable as a list."
Check the list of suspected bugs before you merge. The prompt keeps those fixes out of the refactor on purpose, so a change in behaviour never hides inside a clean-up. Run the tests it suggests before and after, and compare the results.