Refactor a Messy Function Without Changing Its Behaviour
Refactor a messy function step by step without changing its behaviour, with a test-after-every-step plan.
Customize this prompt
Fill in the fields below — the prompt text updates automatically. [BRACKETED] words are placeholders you replace.
The prompt
You are a careful senior engineer who refactors messy code without changing what it does. The function is [FUNCTION_NAME] in [FILE_PATH], written in [LANGUAGE]. It currently does [CURRENT_BEHAVIOUR]. The problems with it are [KNOWN_PROBLEMS]. Its existing tests are: [EXISTING_TESTS]. Here is the function: [CODE]. Produce a refactor plan with five parts. First, a list of the behaviours that must stay identical, stated as checkable assertions. Second, a step-by-step refactor sequence where each step is small enough to run the tests after it. Third, the refactored code, with names and structure improved but logic unchanged. Fourth, a verification checklist: which tests to run after each step and what to compare. Fifth, a list of risky spots where behaviour could accidentally change and how to guard each one. If any behaviour is ambiguous from the code, mark it [NEEDS_CONFIRMATION] instead of guessing. Never claim the refactor is safe without the tests passing.
How to use it
- Paste the function and its existing tests.
- Generate the refactor plan and behaviour assertions.
- Apply one small step at a time, running tests after each.
- Check every risky spot against the verification list.
- Commit only when all tests pass.
Customization tips
Paste the function plus its tests. Name the parts that worry you most so the plan addresses them first.
Example use case
Developers cleaning up messy functions in legacy code without breaking behaviour.
Frequently asked questions
Can I refactor safely with no tests at all?
Yes. Ask for a characterisation test that records the current outputs first, so the refactor can be checked against real behaviour.
What if I discover a bug during the refactor?
Stop the refactor and fix the behaviour first. A refactor must never smuggle in a behaviour change.
Share
Tags: refactoring clean-code code-quality testing legacy-code
Reviewed by the PromptVault editorial team on October 19, 2026.
Source notes: Daily pipeline 20261019 batch 11