Refactor a Legacy Function Safely Step by Step
Break down a scary legacy function into small, tested steps so refactoring improves the code without breaking production.
Customize this prompt
Fill in the fields below — the prompt text updates automatically. [BRACKETED] words are placeholders you replace.
The prompt
You are a senior developer refactoring a legacy function in [PROJECT_NAME] written in [LANGUAGE]. The function is [FUNCTION_NAME], roughly [LINE_COUNT] lines long, and it currently handles [RESPONSIBILITIES]. Do not rewrite it in one go. First, characterise its behaviour with tests: write tests that capture what it does today, including its quirks, using [TEST_FRAMEWORK]. Then extract one responsibility at a time into a named helper, running the tests after every single extraction, and keep each change small enough to review in under [REVIEW_MINUTES] minutes. Flag any dead code, duplicated logic, or hidden side effects you find, and say explicitly whether each one is safe to remove or needs a product decision. Finish with a before-and-after summary: what got simpler, what behaviour intentionally changed, and what still needs a follow-up ticket in [ISSUE_TRACKER].
How to use it
- Read the function and list every responsibility it handles.
- Write characterisation tests capturing today's behaviour, quirks included.
- Extract one responsibility at a time into a named helper.
- Run the full test suite after every single extraction.
- Flag dead code and side effects, marking what needs a decision.
- Summarise what improved, what changed, and what needs follow-up.
Customization tips
Adjust the extraction size to your review culture, and add a performance check if the function sits on a hot path.
Example use case
Developers inheriting messy, long-lived code who need to improve it without a risky big-bang rewrite.
Frequently asked questions
What if there are no tests at all for the legacy code?
Write characterisation tests first, before touching anything. They lock in today's behaviour so you can prove the refactor did not silently change it.
When should I stop refactoring and rewrite instead?
When the function's behaviour is undocumented, untested and nobody understands it, a careful rewrite with new tests may be cheaper. Even then, keep the old version runnable for comparison.
Share
Tags: refactoring legacy code software development code quality testing developer prompts
Reviewed by the PromptVault editorial team on November 4, 2026.
Source notes: Daily pipeline 20261104 batch 11