qvib.pro
RU

Refactor without changing behavior

What for: improve code readability and structure without breaking anything — with an explanation for every single change.

бесплатно профи

Структура: правила-ограничители + пошаговые правки

Updated: 02.07.2026

$ You are an engineer who refactors carefully. Rewrite the code below more clea…
Refactor without changing behavior

When to use it

When the code works but is "scary" - long functions, duplication, unreadable — and you need to tidy it up without breaking anything. The role is a careful engineer. Result: clean code + a "before → after → why" log + what to cover with tests.

The prompt (copy and paste)

You are an engineer who refactors carefully. Rewrite the code below more cleanly, WITHOUT changing its external behavior.
CODE: "<PASTE>". LANGUAGE/STYLE: <e.g. TS, no any; PEP8>.

Hard rules:
- Do not change behavior or the public interface. Do not break API names.
- No new dependencies without explicit justification.
- Small safe steps, not a rewrite from scratch.

Deliver: 1) the rewritten code; 2) a list of changes as "before → after → why"; 3) what to check with tests to confirm behavior did not drift.

Filled-in example

In <PASTE> - an 80-line function with three nested ifs and copy-pasted validation. Language: TS, no any.

Expected AI answer: (1) the function is split into 3 small ones (validateInput, computeTotal, format), early returns instead of nesting, types instead of any; (2) the log - "nested ifs → guard clauses, why: readability", "duplicated validation → shared function"; (3) test the same inputs/outputs as before, especially the edge cases where the branching logic changed.

Variations

  • Surgical. "Only remove the duplication" or "only split it into functions" - minimal diff.
  • Toward a pattern. "Rewrite it with dependency injection / as pure functions."
  • Tests first. A combo: first the "Write tests" prompt, then refactor under the protection of characterization tests.

Pro tips

  • The golden rule: refactor with green tests. No tests? Write characterization tests first - otherwise there is nothing to back up "I didn't break anything".
  • "Small steps" is in the prompt for a reason: ask a model to "rewrite it nicely" and it loves to rewrite from scratch and quietly change behavior.
  • The "before → after → why" log is for reviewing the diff: read it, not just the new code, to catch hidden changes in meaning.

Читать по-русски →