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.

Category: Coding and Development Works with: Claude, ChatGPT Type: Text
Refactor a Messy Function Without Changing Its Behaviour — example preview

Customize this prompt

Fill in the fields below — the prompt text updates automatically. [BRACKETED] words are placeholders you replace.

The prompt

Free to use — see usage notes below.
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

  1. Paste the function and its existing tests.
  2. Generate the refactor plan and behaviour assertions.
  3. Apply one small step at a time, running tests after each.
  4. Check every risky spot against the verification list.
  5. 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

Coding and Development ChatGPT · Claude

Refactor Risk Checklist: Ship Cleaner Code Without Breaking Things

A refactoring risk analyst that maps blast radius, builds a test safety net, and plans incremental, rollback-ready refa…

Coding and Development Claude · ChatGPT

Clean Up a Tangled Helper Function Step by Step, Tests Intact

Plan a safe refactor of a tangled function with a behaviour snapshot, small steps, and a test run after every change.