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
- Name the goal in one sentence: “split
OrderServiceso pricing can be tested without a database”. Refactoring without a goal produces churn. - 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 thecharacterization-testsskill). - 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:
- Tests green after every step. If a step breaks tests, revert it rather than debugging forward.
- Do not mix refactoring with behavior changes in the same commit. Reviewers should be able to verify a refactor commit by “nothing changed”.
- Keep public interfaces stable, or change them with a deprecation path (old name delegates to new, with a warning) when there are external callers.
- Move in parallel for risky changes: build the new structure next to the old, switch callers over one at a time, delete the old one last.
Done
- Tests, linter and typechecker pass.
- Diff shows only structural changes; summarize them as a list of named refactorings (“extracted
compute_tax, movedformat_invoicetoinvoices/format.py”). - Mention anything you deliberately left (with reason) and any behavior that looked like a bug but was preserved on purpose; propose fixing those separately.