Overview
Refactoring is changing a program's internal structure without changing its observable behavior, in small reversible steps, to make it cheaper to understand and modify. The canonical treatment is Martin Fowler's Refactoring (2nd ed., 2018): a catalog of named transformations triggered by named code smells, executed under a safety net of tests.
Key points
- Small steps, always compiling, always green: the discipline is the sequence of tiny behavior-preserving moves, not the end state.
- Smells → refactorings: long method → Extract Function; feature envy → Move Function; primitive obsession → Replace Primitive with Object; switch on type → Replace Conditional with Polymorphism; data clumps → Introduce Parameter Object…
- The core catalog: Extract/Inline Function & Variable, Rename, Move, Change Function Declaration, Replace Temp with Query, Split Phase, Encapsulate Variable/Collection.
- Tests first: no safety net, no refactoring — with legacy code, start with characterization tests and seams (Feathers, Working Effectively with Legacy Code).
- Opportunistic, not scheduled: prefer the boy-scout rule and preparatory refactoring ("make the change easy, then make the easy change") over big-bang cleanup projects.
- Know when to stop: refactoring serves the next change; polishing code nobody touches is waste.
- To explore: strangler-fig pattern for large-scale rewrites, IDE-assisted vs. manual refactoring, refactoring at the architecture level.
Practice
- Tennis Refactoring Kata (source) — warm-up: an hour of Extract/Rename/Inline on working-but-awful code, tests already green.
- Parrot Refactoring Kata (source) — the canonical Replace Conditional with Polymorphism drill, one smell one refactoring.
- Theatrical Players Refactoring Kata (source) — the opening example of Fowler's Refactoring 2nd ed.; replay his move sequence, then diverge and compare.
- Samman kata descriptions & learning hours (source) — Emily Bache's structured material for deliberate, repeatable refactoring practice sessions.
- Gilded Rose — legacy rescue (exercise) — the full discipline end to end: characterization tests first, then small steps to a design that welcomes the next feature.
Related
- TDD — refactor is the third step of the cycle.
- Clean code — the target state refactoring moves toward.
- Hexagonal architecture — a common destination when refactoring tangled applications.