Skip to content

Lesson 7 of 9 · 24m

Refactoring Safely: Behavior-Preserving Change Under Control

Refactoring is disciplined behavior preservation: characterization tests, small steps, seams, and verification loops that let you change shape without changing outcomes.

Refactoring is not "cleaning up while I'm in here." It is changing the structure of code without changing observable behavior. If behavior changes, you are doing feature work or bug fixing — sometimes necessary, but never free. Mixing the two is how a simple rename becomes a production incident.

Establish a safety net before moving

Ideal tests specify behavior at the boundary you are refactoring beneath. Legacy systems often do not have those tests. Start with characterization tests: tests that record what the system currently does, even when the behavior is ugly.

def test_invoice_totals_for_mixed_discount_case():
    invoice = build_invoice(lines=mixed_discount_fixture())
    assert calculate_invoice(invoice).total_cents == 18423

That number may encode a bug. Do not fix it yet. Pin it so that structural movement does not accidentally alter it. Once the structure is safe, change behavior deliberately in a separate commit.

Work in small reversible steps

A reliable sequence:

  1. Run the existing tests.
  2. Make one mechanical move.
  3. Run focused tests.
  4. Commit or checkpoint.
  5. Repeat.

Use moves with known semantics: rename, extract function, inline variable, move method, encapsulate field, replace conditional with polymorphism, introduce parameter object. Large rewrites feel fast because the cost is deferred until integration.

Create seams before exploiting them

A seam is a place where behavior can be altered without editing every call site. Michael Feathers popularized the idea because legacy code rarely offers clean seams. Introduce one carefully:

// before
export function syncUsers() {
  const rows = db.query("select * from users");
}

// after: dependency can be supplied in tests
export function syncUsers(queryUsers = defaultUserQuery) {
  const rows = queryUsers();
}

The first refactor can be ugly if it creates a controlled seam. That is acceptable. You are buying future leverage.

Separate movement from behavior change

The reviewable commit pattern is: mechanical refactor first, behavior change second. Do not combine extraction, renames, policy changes, and dependency upgrades in one diff unless the change is tiny. When tests fail, you need to know whether structure or policy caused it.

Verify at the right level

  • Unit tests catch logic regressions in extracted pieces.
  • Characterization tests catch behavioral drift at boundaries.
  • Type checks and compiler exhaustiveness catch broken call graphs.
  • Smoke tests catch wiring and composition errors.
  • Production telemetry catches what your local assumptions missed.

Field notes

  • If you cannot roll back a refactor step, the step is too big.
  • IDE automated refactors are safer than manual search-and-replace because they understand references.
  • A red test during pure refactoring means you changed behavior or your safety net misunderstood it. Stop and diagnose before proceeding.

Was this lesson helpful?

Sign in to rate