Turn a Messy Function Into Clean, Readable Code
Refactor a tangled function into clean, well-named code with clear structure, without changing what it does.
Customize this prompt
Fill in the fields below — the prompt text updates automatically. [BRACKETED] words are placeholders you replace.
The prompt
Act as a senior code reviewer. I will paste a function written in [PROGRAMMING_LANGUAGE] that works but is hard to read. Refactor it step by step: first, explain in plain words what the function actually does, including any hidden side effects or edge cases in [FUNCTION_CONTEXT]; second, rename every variable and helper so names describe their purpose, not their type; third, split the function into smaller functions where each one does exactly one thing, keeping the original behaviour identical; fourth, remove duplicated logic and replace magic numbers with named constants; fifth, add short comments only where the why is not obvious from the code. Return the full refactored code, then a short list of what changed and why, then a list of test cases I should run to prove the behaviour did not change, including the tricky inputs from [EDGE_CASES]. Do not change the function's public signature or its return values, and do not add new features or dependencies.
How to use it
- Paste the messy function and fill in [PROGRAMMING_LANGUAGE].
- Describe where the function is used in [FUNCTION_CONTEXT].
- Run the prompt and read the plain-words explanation first.
- Compare the refactored code against the original line by line.
- Run the listed test cases, especially the edge cases, before merging.
Customization tips
Add your team's style guide as [STYLE_GUIDE] and the model will match its naming and formatting conventions.
Example use case
Developers cleaning up legacy code before adding a feature, or reviewing a teammate's hard-to-read function.
Frequently asked questions
Will the refactored code behave exactly the same?
It should, but always run the suggested test cases first. The prompt asks the model to preserve the signature and return values, and to list tests that prove it.
What if the function is 500 lines long?
Split it into logical chunks and refactor one chunk at a time, keeping the public interface unchanged between chunks.
Share
Tags: coding refactoring clean code code review programming developer tools
Reviewed by the PromptVault editorial team on November 7, 2026.
Source notes: Daily pipeline 20261107 batch 11