Refactoring Safely

Prompt refactors that change structure while provably preserving behavior: one goal at a time, tests first, small diffs.

TL;DR

  1. Refactoring changes structure, not behavior; make that the explicit rule in your prompt.
  2. Target one smell at a time and keep diffs small so you can verify behavior is unchanged.
  3. Have tests in place first; they are your proof the refactor preserved behavior.

Set The Rule

    Behavior Preserved

    Make 'no behavior change' the first and firmest constraint.

    "Refactor only. Same inputs ->
    same outputs."
    Keep The API

    Protect exported signatures that other code depends on.

    "Do not change public signatures
    or exports."
    Tests Stay Green

    Require the existing test suite to keep passing.

    "All current tests must still pass."

Name The Target

    One Smell

    Address a single, specific issue per refactor.

    "Remove the duplication between
    parseA and parseB."
    Concrete Technique

    Name the refactoring you want, not a vague 'improve'.

    "Extract a pure `validate()`; replace
    nested ifs with early returns."
    Scope It

    Bound the refactor to one function or file at a time.

    "Only touch orders.ts for now."

Safety Net First

    Characterize

    If tests are missing, capture current behavior before changing anything.

    "Write tests that pin the current
    behavior of this function."
    Run Before

    Confirm the suite is green before the refactor starts.

    npm test  # green baseline
    Run After

    A still-green suite is your evidence behavior was preserved.

    npm test  # still green = safe

Review Small Diffs

    As A Diff

    Ask for a diff so moved code and changed logic are both visible.

    "Return a unified diff."
    Spot Logic Changes

    Scan for any change that is not purely structural.

    Moved lines = fine.
    Changed conditionals = inspect.
    Iterate

    Land one small refactor, verify, then prompt the next.

    Refactor -> test -> commit -> repeat.

Tips

  1. Say 'do not change behavior or the public API' and 'keep tests green' as hard constraints.
  2. Ask for the refactor as a diff so you can see exactly what moved and catch accidental logic changes.

Warnings

  1. Models often 'improve' behavior while refactoring; that is a behavior change in disguise, and a risk.
  2. A big sweeping refactor is hard to review; prefer a sequence of small, verifiable steps.

In Practice

FAQ