Skip to the content.

Refactor safely

A refactor changes structure, never behavior. If behavior changes, it is a feature or a fix and belongs in a separate commit.

Before touching code

  1. Name the goal in one sentence: “split OrderService so pricing can be tested without a database”. Refactoring without a goal produces churn.
  2. Find the safety net. Run the tests that cover the code. Check coverage of the specific functions (pytest --cov=pkg.module, vitest --coverage, go test -cover ./pkg/...). If the code you will move is not covered, write characterization tests first (see the characterization-tests skill).
  3. Find every caller. Search for the symbol, including string references (reflection, DI containers, templates, serialized names, config files, SQL). Public APIs and anything serialized need extra care.

The step loop

Make one small, mechanical change at a time, then run the tests. Commit when green. Typical steps:

Smell Step
Long function Extract function for a coherent block; give it a name that says what, not how
Unclear name Rename (use the IDE/LSP rename when available; it catches references grep misses)
Duplicated logic Extract the shared part; only merge when the copies change for the same reasons
Function doing two things Split into two, called in sequence, then move each to where it belongs
Deep nesting Guard clauses / early returns
Long parameter list Introduce a parameter object or pass the owning object
Feature envy (method uses another object’s data more than its own) Move the method
Type switch repeated in several places Replace conditional with polymorphism or a lookup table
Global or hidden dependency Pass it in (dependency injection) so tests can substitute it

Rules:

Done