wiki / Coding / coding-behavior-preserving-refactor
intermediateCodingrefactoringtechnical-debttestingsoftware-engineering

Plan and execute a behavior-preserving refactor

Refactors code through an explicit contract inventory, stepwise plan, and verification list — without changing observable behavior.

The prompt — fill the [BRACKETS]0 copies
Refactor the code below. Goal: [WHAT SHOULD IMPROVE — E.G. SPLIT A 300-LINE FUNCTION, REMOVE DUPLICATION, ISOLATE I/O FROM LOGIC]. Constraint: external behavior must not change — same inputs, same outputs, same side effects, same error behavior.

Proceed in this order:

1. Behavior inventory: before touching anything, list the observable behaviors of the current code, including edge cases and error paths. This is the contract the refactor must preserve. Flag any behavior that looks accidental (a probable bug) — preserve it anyway, but list it separately so I can decide whether to fix it in a follow-up.

2. Plan: propose the refactor as a sequence of small steps, each of which leaves the code working. Name each step's type (extract function, inline variable, move to module, introduce parameter, etc.). If a step changes a public signature, call it out — that is an API change, not a pure refactor, and needs my approval.

3. Execute: apply the steps and show the final code. Where a step involved a judgment call (a name, a module boundary), note the alternative you rejected and why, in one line.

4. Verification: state how I can confirm behavior was preserved — which existing tests cover the contract from step 1, and write tests for any listed behavior that has no coverage.

Do not improve anything outside the stated goal, even obvious things — list them at the end as candidates instead.

Code:
[PASTE CODE]
Existing tests, if any:
[PASTE TESTS OR WRITE "NONE"]
Open in Promptly Suggest an edit
Updated 2026-08-18 1 revision
Crafted with precision by MnexWeb