Refactor without changing behavior

Extracts or restructures code while proving the public behavior stays identical.

Coding refactortestssafety Verified 2026-11-02

When to use it

When a function has grown past reading size but is covered by tests you cannot afford to rewrite.

The prompt

Copy into your assistant
Refactor the code below without changing its observable behavior.

Constraints:
- Public signatures stay identical.
- No new dependencies.
- No behavior changes, including error types, ordering, and side effects.
- If you cannot preserve behavior with confidence, stop and say which line makes it unsafe.

Before writing code, list:
1. The observable contract (inputs, outputs, errors, side effects).
2. Which existing tests cover it, if any are shown.
3. The single riskiest line for behavior preservation.

Then output the refactored code, followed by a one-paragraph note on what a reviewer should check.

Code:
<code>

What to change

If there are no tests, say so explicitly — the model will then write thin characterisation checks first instead of refactoring blind.

Why it works

Asking for the contract before the code forces the model to read the function instead of pattern-matching it. The 'riskiest line' question surfaces exactly where a silent regression would hide.

More coding prompts

Going deeper

More prompts

All prompts