Part 10 · 1 chapters · ~8 min

Refactoring

Behaviour-preserving change in small steps, tests as the precondition, code smells as prompts, the named catalogue, when to refactor (preparatory, comprehension, litter-pickup, review), and refactoring as evolutionary design, with a Money parameter object and frontend smells mapped to refactorings.

12

Refactoring

The second edition's examples are in JavaScript, which makes it the easiest book on this shelf to apply directly. Learn ten refactorings by name and use the names in code review.

code
// primitive obsession + data clump → Introduce Parameter Object → a value object
// before: amount and currency travel together through twelve functions
function fee(amountKobo: number, currency: string, country: string) { /* … */ }
function format(amountKobo: number, currency: string) { /* … */ }

// after: the clump becomes a type that owns its rules (and its bugs go with it)
class Money {
  private constructor(readonly minor: bigint, readonly currency: 'NGN' | 'KES' | 'GHS') {}
  static of(minor: bigint, currency: Money['currency']) { return new Money(minor, currency); }
  plus(o: Money) { this.same(o); return new Money(this.minor + o.minor, this.currency); }
  private same(o: Money) { if (o.currency !== this.currency) throw new Error('currency mismatch'); }
}
function fee(amount: Money, country: Country) { /* … */ }
function format(amount: Money) { /* … */ }
smell (frontend form)refactoring
a 400-line componentExtract Function / Extract Component; Split Phase (data, then render)
the same switch on status in five componentsReplace Conditional with Polymorphism, or a lookup table / state machine
props drilled through components that do not use themMove Function; context or composition
amount, currency always togetherIntroduce Parameter Object → Money
a boolean parameter that changes behaviourRemove Flag Argument: two explicit functions
the shelf, complete
Ten books and a pattern vocabulary. Read DDIA and A Philosophy of Software Design first, Accelerate and Team Topologies before leading anything, and Release It! before your first serious on-call rotation. Keep Refactoring open while you code.
REFACTORING
Martin Fowler, 1999 (2nd ed. 2018, examples in JavaScript): the catalogue and when to reach for it
swipe the figure sideways, or tap expand for full screen
1/6
Refactoring is behaviour-preserving
Definition: a refactoring is a change to the internal structure of code that does not change its observable behaviour, made in small steps that each keep the code working. The "two hats" rule: at any moment you are either adding functionality or refactoring, never both.