Refactoring changes how code is built without changing what it does, in steps small enough that the tests stay green after every one. Refactoring toward patterns, the idea behind Joshua Kerievsky's book Refactoring to Patterns (2004), treats Strategy, State and Factory as destinations you reach in those small steps when the code starts asking for them, instead of designs you guess at up front. This lesson takes a switch on a type string to the Strategy pattern in five steps, shows the same moves for State and for factories, and covers the habits that keep every step safe.
Think of it like
Renovating a house you live in
You cannot move out while the kitchen is redone, so the work happens one room at a time, and every evening the water runs and the lights work. Before touching a wall you find out what runs through it (that is the characterization test). Each change is small enough to undo, and at no point is the house a building site with no working bathroom. Months later the house has a new layout, and nobody ever had to live without it.
What refactoring is, and what it is not
Martin Fowler defines a refactoring as a change to the internal structure of software that makes it easier to understand and cheaper to modify without changing its observable behavior. Two words in that sentence carry the weight: structure, because the goal is a better shape, and observable, because callers, tests and users must not be able to tell the difference.
- Refactoring
- One small, named, behavior-preserving change, such as Extract Function or Move Function. Many of them in a row make a large change to the design.
- Characterization test
- A test that records what the code does today, right or wrong, so that any accidental change shows up (Michael Feathers, Working Effectively with Legacy Code, 2004).
- Two hats
- Kent Beck's rule, quoted in Fowler's book: at any moment you are either adding behavior or refactoring, never both. Switch hats often, but know which one you are wearing.
- Refactoring toward a pattern
- A sequence of refactorings whose end result is a known pattern. You stop as soon as the code is good enough, even if the pattern is only partly there.
- Not a rewrite. A rewrite replaces working code and hopes the new code matches it. Refactoring keeps the code working at every step.
- Not a feature. If a test has to change because the behavior changed, that step was not a refactoring. Do it with the other hat on, in its own commit.
- Not a phase. Refactoring happens a few minutes at a time, usually right before adding a feature, not as a project that stops feature work for a month.
The safety net: characterization tests
Feathers defines legacy code as code without tests. Before refactoring such code, you need tests, and you cannot write them from a specification you do not have. So you write tests that describe what the code does now: call it, see what comes back, and assert exactly that.
- 1
Call the code
Pick a small entry point, such as
order.cost(), and call it with realistic input in a test. - 2
Assert a value you know is wrong
Write
expect(cost).toBe(0)and run the test. The failure message tells you the real value. - 3
Pin the real value
Change the assertion to the value the code returned, even if it looks like a bug. The test now characterizes today's behavior.
- 4
Cover every branch
Add inputs until every branch of the code you will touch has run under a test. A coverage report shows the gaps.
describe("Order.cost, as it behaves today", () => {
it("standard: 5 plus 1 per kg", () => {
expect(new Order("standard", 4).cost()).toBe(9);
});
it("express: 12 plus 2 per kg", () => {
expect(new Order("express", 4).cost()).toBe(20);
});
it("pickup is free", () => {
expect(new Order("pickup", 4).cost()).toBe(0);
});
it("throws for an unknown method", () => {
expect(() => new Order("drone", 4).cost()).toThrow("drone");
});
});What the visualizer shows
The visualizer at the top of the page takes shipping code from a switch on a type string to the Strategy pattern in five steps. Choose a step in the step picker. Each step opens on the code as it was before that step; press Apply step to perform the refactoring. The class diagram then marks every class the step touched (edited +6 −12, new class), and the Refactoring step panel beside the code counts them.
- The tests never change. The client program at the bottom of the code panel is the characterization test suite: three orders, one per shipping method. Press Play in any step, before or after applying it, and the three
cost()calls return 9, 20 and 0. - The objects change. Step 2 adds self-calls (the loop under each order). Step 3 adds the
Order «class»box, because orders now come from the static factory. Step 4 adds one shipping object per order, created insidecost(). In step 5 the factory creates it, and each order keeps it in itsratefield. - The switch moves. In steps 1 to 4 the
switchruns inside everycost()call. In step 5 it runs once per order, insideOrder.of(watch the highlightedcaseline), andcost()never branches.
| Step | Classes touched | Lines changed in existing classes |
|---|---|---|
| 1. Characterization tests | None (no code change) | 0 |
| 2. Extract Function | Order edited | 15 (+12 −3) |
| 3. Replace Constructor with Factory Function | Order edited | 5 (+5) |
| 4. Move Function | Order edited; Standard, Express, Pickup new | 18 (+6 −12) |
| 5. Replace Conditional with Polymorphism | Order and the three rate classes edited; Rate new | 30 |
Order and 2 in each rate class, whose declaration line gains implements Rate (one line removed, one added).Walkthrough: from a switch to Strategy
class Order {
constructor(public method: string, public kg: number) {}
cost() {
switch (this.method) {
case "standard": return 5 + this.kg;
case "express": return 12 + 2 * this.kg;
case "pickup": return 0;
}
throw new Error(this.method);
}
}- 1
Pin the behavior
Three characterization tests, one per
case: 9, 20 and 0 for a 4 kg parcel. Run them after every following step; if one turns red, undo the step instead of debugging it. - 2
Extract Function
Give each formula a name:
standardCost(),expressCost(),pickupCost(). Theswitchnow only chooses which method to call. Nothing moved yet, but each formula is a unit that can be moved in one piece. - 3
Replace Constructor with Factory Function
Add
static of(method, kg)that just calls the constructor, and change every caller (here, the tests) to use it. The constructor is now called from one place, so step 5 can change its parameters without touching any caller. - 4
Move Function
Move each formula into a class of its own (
Standard,Express,Pickup), each withcost(kg). TheswitchinOrder.cost()now delegates:return new Standard().cost(this.kg). This middle state is not pretty, and that is fine: it works, the tests pass, and the next step is short. - 5
Replace Conditional with Polymorphism
The three classes already share a method, so give them an interface,
Rate.Ordertakes aRatein its constructor instead of themethodstring,cost()becomesthis.rate.cost(this.kg), and theswitchmoves into the factory, which picks the rate once. The result is the Strategy pattern:Orderis the context,Ratethe strategy interface.
interface Rate {
cost(kg: number): number;
}
class Standard implements Rate { cost(kg: number) { return 5 + kg; } }
class Express implements Rate { cost(kg: number) { return 12 + 2 * kg; } }
class Pickup implements Rate { cost(kg: number) { return 0; } }
class Order {
constructor(private rate: Rate, public kg: number) {}
static of(method: string, kg: number): Order {
switch (method) {
case "standard": return new Order(new Standard(), kg);
case "express": return new Order(new Express(), kg);
case "pickup": return new Order(new Pickup(), kg);
}
throw new Error(method);
}
cost() {
return this.rate.cost(this.kg);
}
}The core refactorings
| Refactoring | What it does | Reach for it when |
|---|---|---|
| Extract Function (Extract Method) | Turns a block into a named function and calls it | A block needs a comment to explain it, or you want to move or reuse it |
| Inline Function | Replaces calls with the body and deletes the function | A function's body is as clear as its name, or you are regrouping code |
| Move Function (Move Method) | Moves a function to the class whose data it uses | Feature Envy: it talks more to another class than to its own |
| Extract Class | Splits a class's fields and methods into a new class | A God Object, or a group of fields that are always used together |
| Introduce Parameter Object | Replaces a group of parameters with one object | The same parameters travel together through many signatures |
| Replace Primitive with Object (Replace Data Value with Object) | Wraps a raw value in a small class with its own rules | Primitive Obsession: validation or formatting repeated for the same kind of value |
| Replace Conditional with Polymorphism | Turns each branch of a type-based conditional into a class | The same switch on a type code appears in several places |
| Replace Type Code with Subclasses | Turns a type field into a subclass per value | Behavior differs by type and the type never changes for an object |
| Replace Constructor with Factory Function (Replace Constructor with Factory Method) | Callers use a named creation function instead of new | You want to choose the class at creation time, or change the constructor safely |
| Introduce Special Case (Introduce Null Object) | Replaces a special value such as null with an object that handles it | The same null or "unknown" check is repeated in many callers |
Modern IDEs automate the mechanical ones (rename, extract, inline, move, change signature), and an automated refactoring is far safer than the same edit by hand. The first such tool was the Smalltalk Refactoring Browser, built by John Brant and Don Roberts in the 1990s.
Recipe: status flags to State
Kerievsky calls this one Replace State-Altering Conditionals with State. The smell is a status field that every method checks before deciding whether it is allowed and what the next status is. The code below is the starting point of the second implementation at the bottom of the page.
class Order {
status = "new";
pay() {
if (this.status !== "new") {
throw new Error(`cannot pay when ${this.status}`);
}
this.status = "paid";
}
ship() {
if (this.status !== "paid") {
throw new Error(`cannot ship when ${this.status}`);
}
this.status = "shipped";
}
cancel() {
if (this.status !== "new" && this.status !== "paid") {
throw new Error(`cannot cancel when ${this.status}`);
}
this.status = "cancelled";
}
}- 1
Pin every transition
One characterization test per allowed move and per refused move: pay then ship works, ship before pay throws, cancel after ship throws.
- 2
Create one class per status value
Add a base class (or interface)
OrderStatewithpay(),ship()andcancel()that throw by default, and one subclass per status:New,Paid,Shipped,Cancelled. - 3
Move the transitions
Move each allowed branch into the state where it is allowed:
New.pay()returns aPaid,Paid.ship()returns aShipped. Refused moves need no code, because the base class already throws. - 4
Delegate from the context
Orderholds astatefield and each method becomes one line,this.state = this.state.pay(). Keep astatusgetter that returns the state's name so callers and tests do not change. - 5
Delete the string checks
When no
ifon the status string is left, the refactoring is done: the lifecycle is now visible as classes and arrows. See State.
Recipe: scattered constructors to a factory
When new SomeClass(true, false, null, 3) appears in twenty places, and the choice of class is made by an if at each call site, creation knowledge is spread across the code base. Kerievsky gives a family of refactorings for it: Replace Constructors with Creation Methods (named static methods such as Loan.termLoan(...) instead of overloaded constructors), Move Creation Knowledge to Factory (gather the scattered choices into one factory class), Encapsulate Classes with Factory, and Introduce Polymorphic Creation with Factory Method. Fowler's Replace Constructor with Factory Function is the first step of all of them, and it is step 3 in the visualizer.
// Before: callers pass positional flags.
// new Loan(1000, false, false, 3); // what do false, false and 3 mean?
// After Replace Constructors with Creation Methods:
class Loan {
private constructor(
readonly amount: number,
readonly revolving: boolean,
readonly secured: boolean,
readonly years: number,
) {}
static termLoan(amount: number, years: number): Loan {
return new Loan(amount, false, false, years);
}
static revolvingCredit(amount: number): Loan {
return new Loan(amount, true, false, 0);
}
}
const loan = Loan.termLoan(1000, 3); // says what it createsFrom there, a factory that picks the class at runtime is a short step (Factory Method), a family of related products leads to Abstract Factory, and an object with many optional parts leads to Builder.
More destinations
| Starting smell | Kerievsky's refactoring | Destination |
|---|---|---|
A switch that picks one of several algorithms | Replace Conditional Logic with Strategy | Strategy |
| Status checks in every method | Replace State-Altering Conditionals with State | State |
A big if/switch that dispatches requests to handling code | Replace Conditional Dispatcher with Command | Command |
| Optional extra behavior added with flags inside a class | Move Embellishment to Decorator | Decorator |
| Two subclasses with the same algorithm outline and different steps | Form Template Method | Template Method |
| A class that calls specific listeners directly | Replace Hard-Coded Notifications with Observer | Observer |
Repeated if (x == null) checks | Introduce Null Object | Null Object |
| Tree-shaped data built from strings or nested lists | Replace Implicit Tree with Composite | Composite |
| Two classes that do the same job with different interfaces | Unify Interfaces with Adapter, Extract Adapter | Adapter |
| A Singleton that does not need to be one | Inline Singleton | Away from Singleton, toward Dependency Injection |
Working safely in a real codebase
- Run the tests after every step, and when they go red, undo the step rather than debugging forward. A step you can undo in seconds is the right size.
- Commit on every green. Small refactoring commits are easy to review and easy to revert, and they are separate from the commit that changes behavior.
- Use the IDE's automated refactorings for renames, extracts, moves and signature changes. They update every call site, including ones you would miss by hand.
- Change public APIs in two phases. Parallel change (also called expand and contract) adds the new form next to the old one, migrates callers, then removes the old form. That is what step 3 does with
Order.of. - Swap a large component behind an abstraction. Branch by abstraction introduces an interface in front of the old implementation, builds the new one behind it, and switches over when it is ready; the trunk stays releasable throughout.
- Replace a whole system gradually with the Strangler Fig pattern: route one feature at a time to new code until the old system can be removed.
When to refactor, and when not to
Refactor when
- The next feature is hard to add because of the current structure
- You understood confusing code by reading it: put that understanding into names
- The same change has now been made in three places (Don Roberts's rule of three, quoted by Fowler)
- You are reviewing or fixing a bug in code you will touch again soon
Hold off when
- There are no tests and you cannot add any yet; write characterization tests first
- The code works, is stable, and nobody needs to change it
- It is about to be deleted or replaced
- You are in the middle of an incident: restore service first, refactor afterwards
| Refactoring | Rewrite | |
|---|---|---|
| Behavior during the work | Unchanged after every step | Unknown until the new version is finished |
| Can stop at any point | Yes, every step is shippable | No, a half-finished rewrite has no value |
| Risk | Small, caught by tests at each step | Large: old bugs that callers rely on, and features the old code had that nobody listed |
| Typical size | Minutes per step, days for a full journey | Weeks to years |
| Use it for | Almost all design improvement | Code that is truly beyond repair, or a platform change; even then, prefer a gradual Strangler Fig replacement |
Implementation
The visualizer's refactoring as a complete program: the starting LegacyOrder with a switch on the shipping method, and the final Order with a Rate strategy chosen once by the factory Order.of. The characterization tests run against both versions and print the same results.
from abc import ABC, abstractmethod
from typing import Callable
# Starting point: a switch on a type string in every cost() call.
class LegacyOrder:
def __init__(self, method: str, kg: int) -> None:
self.method = method
self.kg = kg
def cost(self) -> int:
match self.method:
case "standard":
return 5 + self.kg
case "express":
return 12 + 2 * self.kg
case "pickup":
return 0
raise ValueError(f"unknown method: {self.method}")
# Destination: Strategy. Each rate is a class; the factory picks one.
class Rate(ABC):
@abstractmethod
def cost(self, kg: int) -> int: ...
class Standard(Rate):
def cost(self, kg: int) -> int:
return 5 + kg
class Express(Rate):
def cost(self, kg: int) -> int:
return 12 + 2 * kg
class Pickup(Rate):
def cost(self, kg: int) -> int:
return 0
class Order:
def __init__(self, rate: Rate, kg: int) -> None:
self._rate = rate
self.kg = kg
# The only branch on the method name; it runs once, at creation.
@classmethod
def of(cls, method: str, kg: int) -> "Order":
rates: dict[str, Callable[[], Rate]] = {
"standard": Standard,
"express": Express,
"pickup": Pickup,
}
if method not in rates:
raise ValueError(f"unknown method: {method}")
return cls(rates[method](), kg)
def cost(self) -> int:
return self._rate.cost(self.kg)
# Characterization tests: the same expectations for both versions.
CASES = [("standard", 9), ("express", 20), ("pickup", 0)]
def check(label: str, cost: Callable[[str], int]) -> None:
for method, want in CASES:
got = cost(method)
print(f"{label} {method}: {got} {'ok' if got == want else 'FAIL'}")
if __name__ == "__main__":
check("legacy", lambda m: LegacyOrder(m, 4).cost())
check("strategy", lambda m: Order.of(m, 4).cost())
# Prints "standard: 9 ok", "express: 20 ok" and "pickup: 0 ok"
# for both versions.Key takeaways
- A refactoring changes structure, never observable behavior, and each step is small enough to verify with tests and undo in seconds.
- Characterization tests come first: they record what the code does today (bugs included), so any accidental change turns a test red.
- In the visualizer, five steps (tests, Extract Function, Replace Constructor with Factory Function, Move Function, Replace Conditional with Polymorphism) turn a
switchinto Strategy, and the tests return 9, 20 and 0 at every step. - Patterns are destinations, not starting points: move toward Strategy, State or a factory when real changes show the need, and stop as soon as the code is good enough.
- The same recipe shape works for State (status checks become state classes) and for factories (scattered constructors become named creation methods, then a factory).
- Keep refactoring commits separate from behavior changes, use IDE refactorings, and change public APIs in two phases (parallel change).
Common pitfalls
- Refactoring and changing behavior in the same step. When a test fails you cannot tell which change broke it; wear one hat at a time.
- Taking big steps. If the tests are red for an hour, the step was too large; undo it and find a smaller one.
- Refactoring without tests, or with tests that only check that the code runs. Characterization tests must assert actual values for every branch you touch.
- Fixing a suspicious result while refactoring. Callers may depend on it; pin it in a test, finish the refactoring, then fix it as a separate behavior change.
- Treating the pattern as the goal. A three-case
switchthat never changes does not need Strategy; stopping after Extract Function is a fine outcome.
Interview tips
- When asked to improve messy code, start by saying how you would keep behavior safe (characterization tests), then name each step (Extract Function, Move Function, Replace Conditional with Polymorphism). Interviewers listen for small, named, testable steps.
- Know the difference between a refactoring and a rewrite, and argue for the refactoring with concrete risks: lost edge cases, a long period with no shippable code, and old bugs that callers depend on.
- Mention preparatory refactoring ("make the change easy, then make the easy change") and parallel change for public APIs. Both show you have refactored a live system, not just a kata.
Real-world applications
- Preparing legacy code for a feature: pin behavior with tests, then refactor only the part the feature needs.
- Replacing type-code conditionals with Strategy or State in pricing, shipping, workflow and lifecycle code.
- Moving creation logic into factories before introducing dependency injection or plugins.
- Large-scale changes with automated refactoring tools (IDE refactorings, codemods such as jscodeshift, OpenRewrite recipes for Java).
- Gradual replacement of old services with the strangler fig pattern and branch by abstraction, keeping the main branch releasable.
Test yourself
What does every step in the visualizer's five-step refactoring have in common?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.