# Refactoring Toward a Pattern, One Small Step at a Time

With old code pinned down by tests, you can reshape it toward a pattern in steps so small that each one keeps every test green, running the tests after every step and undoing any step that turns one red; the gym's plan if chain becomes a dictionary of pricing rules, and a new family plan becomes one line.

Journeyman · Software Development · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Refactor toward a pattern in small steps, running the tests after every step
- Plan the order of small steps from a smell to its cure, and undo a step that turns a test red

## Key takeaways

- Refactoring changes the shape of code without changing what it does, so the tests that passed before a step pass after it.
- Move toward a pattern in steps small enough to check one at a time: pull out, move, swap one caller, delete what's no longer used.
- Run the tests after every step. If one goes red, undo the step and take a smaller one, rather than debugging forward.
- The new requirement comes last, on code that's already in the right shape, and then it's a small change of its own.

**Before this:** *Pin It Down: Tests for Code You Didn't Write*, whose pins this lesson keeps green, and *Weekly Deals: Pass the Rule In*, where a rule was first handed in as a function.

The owner's change is here: a **family plan**, $90 a month for the whole family, however many classes they take. The billing code from the last lesson picks each plan's rule with an `if` chain on the plan's name, a smell of choosing, and the sign-up page has the same chain. You could add one more `if`. Or you could move the code toward the shape the smell map points to, so this plan and the next are one line each.

What you can't do is take the function apart in one go and hope. In *Exercise: Green Before, Green After* in Module 1 you ran the tests after every step. That habit is the whole method here, on code that matters more.

![Stepping stones across a stream, close together, each with a small green check mark on its top; a person stands on the third stone, and the far bank is labeled "Done" while the near bank is labeled "Start"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/4e750911dfde4688a59b28b8b7a4c0e9.webp)

## The problem: a big change is a big risk

The billing function has five pins from the last lesson, including the $60 cap and the capital-B `"Basic"` that's billed $0. Changing it in one big edit means that if a pin goes red, you don't know which part of the edit did it. A big change that breaks something takes an afternoon to untangle; a small one that breaks something takes a minute to undo.

So the change is split into steps that are each too small to get wrong:

| Step | What changes | Then |
|---|---|---|
| 1 | Pull each plan's branch out into its own function, `basicRule` and `unlimitedRule` | run the pins |
| 2 | The `if` chain calls those functions instead of doing the math | run the pins |
| 3 | Add a dictionary from each plan's name to its rule, used by nothing yet | run the pins |
| 4 | Point the bill at the dictionary; an unknown name still bills $0 | run the pins |
| 5 | Delete the `if` chain, now unused | run the pins |
| 6 | The new requirement: add the family plan, and a test for it | run everything |

Each step either keeps every pin green, or it's undone and taken again in a smaller piece. That rule is what makes refactoring safe: **refactoring** means changing the shape of code without changing what it does, and the pins are how you know you didn't.

## Halfway: the rules pulled out

After step 2, the rules have names, and the `if` chain still decides which one to call. Nothing a member pays has changed, and the pins say so:

```csharp
Pin("basic, 2 classes", MonthlyBill("basic", 2), 30);
Pin("basic, 6 classes", MonthlyBill("basic", 6), 54);
Pin("basic, 9 classes", MonthlyBill("basic", 9), 60);
Pin("unlimited, 9 classes", MonthlyBill("unlimited", 9), 60);
Pin("Basic, 6 classes", MonthlyBill("Basic", 6), 0);

// Step 1: each plan's rule, pulled out.
int BasicRule(int classes) => Math.Min(60, 30 + Math.Max(0, classes - 4) * 12);
int UnlimitedRule(int classes) => 60;

// Step 2: the chain calls them.
int MonthlyBill(string plan, int classes)
{
    if (plan == "unlimited") { return UnlimitedRule(classes); }
    if (plan == "basic") { return BasicRule(classes); }
    return 0;
}

void Pin(string label, int actual, int expected)
{
    Console.WriteLine(actual == expected
        ? $"pinned: {label}: ${actual}"
        : $"CHANGED: {label}: was ${expected}, now ${actual}");
}
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
```

```java
// Step 1: each plan's rule, pulled out.
int basicRule(int classes) { return Math.min(60, 30 + Math.max(0, classes - 4) * 12); }
int unlimitedRule(int classes) { return 60; }

// Step 2: the chain calls them.
int monthlyBill(String plan, int classes) {
    if (plan.equals("unlimited")) { return unlimitedRule(classes); }
    if (plan.equals("basic")) { return basicRule(classes); }
    return 0;
}

void pin(String label, int actual, int expected) {
    IO.println(actual == expected
        ? "pinned: " + label + ": $" + actual
        : "CHANGED: " + label + ": was $" + expected + ", now $" + actual);
}

void main() {
    pin("basic, 2 classes", monthlyBill("basic", 2), 30);
    pin("basic, 6 classes", monthlyBill("basic", 6), 54);
    pin("basic, 9 classes", monthlyBill("basic", 9), 60);
    pin("unlimited, 9 classes", monthlyBill("unlimited", 9), 60);
    pin("Basic, 6 classes", monthlyBill("Basic", 6), 0);
}
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
```

```python
def basic_rule(classes):
    """Step 1: each plan's rule, pulled out."""
    return min(60, 30 + max(0, classes - 4) * 12)


def unlimited_rule(classes):
    return 60


def monthly_bill(plan, classes):
    """Step 2: the chain calls them."""
    if plan == "unlimited":
        return unlimited_rule(classes)
    if plan == "basic":
        return basic_rule(classes)
    return 0


def pin(label, actual, expected):
    if actual == expected:
        print(f"pinned: {label}: ${actual}")
    else:
        print(f"CHANGED: {label}: was ${expected}, now ${actual}")


pin("basic, 2 classes", monthly_bill("basic", 2), 30)
pin("basic, 6 classes", monthly_bill("basic", 6), 54)
pin("basic, 9 classes", monthly_bill("basic", 9), 60)
pin("unlimited, 9 classes", monthly_bill("unlimited", 9), 60)
pin("Basic, 6 classes", monthly_bill("Basic", 6), 0)
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
```

```javascript
// Step 1: each plan's rule, pulled out.
function basicRule(classes) { return Math.min(60, 30 + Math.max(0, classes - 4) * 12); }
function unlimitedRule(classes) { return 60; }

// Step 2: the chain calls them.
function monthlyBill(plan, classes) {
  if (plan === "unlimited") { return unlimitedRule(classes); }
  if (plan === "basic") { return basicRule(classes); }
  return 0;
}

function pin(label, actual, expected) {
  console.log(actual === expected
    ? `pinned: ${label}: $${actual}`
    : `CHANGED: ${label}: was $${expected}, now $${actual}`);
}

pin("basic, 2 classes", monthlyBill("basic", 2), 30);
pin("basic, 6 classes", monthlyBill("basic", 6), 54);
pin("basic, 9 classes", monthlyBill("basic", 9), 60);
pin("unlimited, 9 classes", monthlyBill("unlimited", 9), 60);
pin("Basic, 6 classes", monthlyBill("Basic", 6), 0);
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
```

```typescript
// Step 1: each plan's rule, pulled out.
function basicRule(classes: number): number { return Math.min(60, 30 + Math.max(0, classes - 4) * 12); }
function unlimitedRule(classes: number): number { return 60; }

// Step 2: the chain calls them.
function monthlyBill(plan: string, classes: number): number {
  if (plan === "unlimited") { return unlimitedRule(classes); }
  if (plan === "basic") { return basicRule(classes); }
  return 0;
}

function pin(label: string, actual: number, expected: number): void {
  console.log(actual === expected
    ? `pinned: ${label}: $${actual}`
    : `CHANGED: ${label}: was $${expected}, now $${actual}`);
}

pin("basic, 2 classes", monthlyBill("basic", 2), 30);
pin("basic, 6 classes", monthlyBill("basic", 6), 54);
pin("basic, 9 classes", monthlyBill("basic", 9), 60);
pin("unlimited, 9 classes", monthlyBill("unlimited", 9), 60);
pin("Basic, 6 classes", monthlyBill("Basic", 6), 0);
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
```

Step 1 is where a slip is most likely. Suppose you'd written the basic rule as `30 + Math.Max(0, classes - 4) * 12` and forgotten the cap: the 9-class pin turns red the moment you run the tests, and the fix is to undo one line. You never get far enough from green to be lost.

## The end: a dictionary of rules

Steps 3 to 5 swap the chain for a dictionary from each plan's name to its rule, which is the Strategy pattern in the function form *Weekly Deals: Pass the Rule In* first used. Only then, in step 6, does the family plan go in, with a new test of its own:

```csharp
Pin("basic, 2 classes", MonthlyBill("basic", 2), 30);
Pin("basic, 6 classes", MonthlyBill("basic", 6), 54);
Pin("basic, 9 classes", MonthlyBill("basic", 9), 60);
Pin("unlimited, 9 classes", MonthlyBill("unlimited", 9), 60);
Pin("Basic, 6 classes", MonthlyBill("Basic", 6), 0);
Pin("family, 9 classes", MonthlyBill("family", 9), 90); // step 6: the new requirement's test

int MonthlyBill(string plan, int classes)
{
    Dictionary<string, Func<int, int>> rules = new Dictionary<string, Func<int, int>>
    {
        ["basic"] = classes => Math.Min(60, 30 + Math.Max(0, classes - 4) * 12),
        ["unlimited"] = classes => 60,
        ["family"] = classes => 90, // step 6: one line
    };
    return rules.TryGetValue(plan, out Func<int, int>? rule) ? rule(classes) : 0;
}

void Pin(string label, int actual, int expected)
{
    Console.WriteLine(actual == expected
        ? $"pinned: {label}: ${actual}"
        : $"CHANGED: {label}: was ${expected}, now ${actual}");
}
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
pinned: family, 9 classes: $90
```

```java
final Map<String, IntUnaryOperator> rules = Map.of(
    "basic", classes -> Math.min(60, 30 + Math.max(0, classes - 4) * 12),
    "unlimited", classes -> 60,
    "family", classes -> 90); // step 6: one line

int monthlyBill(String plan, int classes) {
    IntUnaryOperator rule = rules.get(plan);
    return rule == null ? 0 : rule.applyAsInt(classes);
}

void pin(String label, int actual, int expected) {
    IO.println(actual == expected
        ? "pinned: " + label + ": $" + actual
        : "CHANGED: " + label + ": was $" + expected + ", now $" + actual);
}

void main() {
    pin("basic, 2 classes", monthlyBill("basic", 2), 30);
    pin("basic, 6 classes", monthlyBill("basic", 6), 54);
    pin("basic, 9 classes", monthlyBill("basic", 9), 60);
    pin("unlimited, 9 classes", monthlyBill("unlimited", 9), 60);
    pin("Basic, 6 classes", monthlyBill("Basic", 6), 0);
    pin("family, 9 classes", monthlyBill("family", 9), 90); // step 6: the new requirement's test
}
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
pinned: family, 9 classes: $90
```

```python
RULES = {
    "basic": lambda classes: min(60, 30 + max(0, classes - 4) * 12),
    "unlimited": lambda classes: 60,
    "family": lambda classes: 90,  # step 6: one line
}


def monthly_bill(plan, classes):
    rule = RULES.get(plan)
    return rule(classes) if rule else 0


def pin(label, actual, expected):
    if actual == expected:
        print(f"pinned: {label}: ${actual}")
    else:
        print(f"CHANGED: {label}: was ${expected}, now ${actual}")


pin("basic, 2 classes", monthly_bill("basic", 2), 30)
pin("basic, 6 classes", monthly_bill("basic", 6), 54)
pin("basic, 9 classes", monthly_bill("basic", 9), 60)
pin("unlimited, 9 classes", monthly_bill("unlimited", 9), 60)
pin("Basic, 6 classes", monthly_bill("Basic", 6), 0)
pin("family, 9 classes", monthly_bill("family", 9), 90)  # step 6: the new requirement's test
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
pinned: family, 9 classes: $90
```

```javascript
const rules = {
  basic: (classes) => Math.min(60, 30 + Math.max(0, classes - 4) * 12),
  unlimited: (classes) => 60,
  family: (classes) => 90, // step 6: one line
};

function monthlyBill(plan, classes) {
  const rule = rules[plan];
  return rule ? rule(classes) : 0;
}

function pin(label, actual, expected) {
  console.log(actual === expected
    ? `pinned: ${label}: $${actual}`
    : `CHANGED: ${label}: was $${expected}, now $${actual}`);
}

pin("basic, 2 classes", monthlyBill("basic", 2), 30);
pin("basic, 6 classes", monthlyBill("basic", 6), 54);
pin("basic, 9 classes", monthlyBill("basic", 9), 60);
pin("unlimited, 9 classes", monthlyBill("unlimited", 9), 60);
pin("Basic, 6 classes", monthlyBill("Basic", 6), 0);
pin("family, 9 classes", monthlyBill("family", 9), 90); // step 6: the new requirement's test
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
pinned: family, 9 classes: $90
```

```typescript
const rules: Record<string, (classes: number) => number> = {
  basic: (classes) => Math.min(60, 30 + Math.max(0, classes - 4) * 12),
  unlimited: (classes) => 60,
  family: (classes) => 90, // step 6: one line
};

function monthlyBill(plan: string, classes: number): number {
  const rule = rules[plan];
  return rule ? rule(classes) : 0;
}

function pin(label: string, actual: number, expected: number): void {
  console.log(actual === expected
    ? `pinned: ${label}: $${actual}`
    : `CHANGED: ${label}: was $${expected}, now $${actual}`);
}

pin("basic, 2 classes", monthlyBill("basic", 2), 30);
pin("basic, 6 classes", monthlyBill("basic", 6), 54);
pin("basic, 9 classes", monthlyBill("basic", 9), 60);
pin("unlimited, 9 classes", monthlyBill("unlimited", 9), 60);
pin("Basic, 6 classes", monthlyBill("Basic", 6), 0);
pin("family, 9 classes", monthlyBill("family", 9), 90); // step 6: the new requirement's test
```

```text
pinned: basic, 2 classes: $30
pinned: basic, 6 classes: $54
pinned: basic, 9 classes: $60
pinned: unlimited, 9 classes: $60
pinned: Basic, 6 classes: $0
pinned: family, 9 classes: $90
```

The five old pins never went red, so nothing a member pays has changed: not the cap, and not the capital-B quirk, which is still waiting for the owner's answer. The family plan is one line, and the sign-up page can now use the same dictionary instead of its own chain.

Java's dictionary is a `Map` of `IntUnaryOperator`s, Java's name for "a function from an `int` to an `int`".

## The rules of the road

- **Green before you start.** If the pins aren't green, you don't have a starting point. Fix or pin first.
- **One kind of change per step.** Pull out, *or* move, *or* rename, *or* delete. Never "and also tidy this".
- **Run the tests after every step**, even the ones that "can't" break anything. They're fast, and you'll be surprised.
- **Red means undo, not debug.** Go back to green and take a smaller step. Debugging forward from red is how a ten-minute change becomes a day.
- **Commit at every green**, so undoing is one command.
- **The new feature comes last.** Refactor first, so the feature lands on code that's ready for it. Mixing the two means a red test could be either.

The cycle you know from test-driven development as **red, green, refactor** has refactor as its third step for this reason: shape is changed only while everything is green.

## When not to refactor first

- **When the change is tiny and the smell is mild.** One more `if` in one place may be fine; refactor when the next one comes.
- **When there's no way to test it yet.** Pin it first (*Pin It Down*).
- **When you're about to replace the code.** Moving the furniture in a house you're about to leave doesn't help; the next lesson replaces a system piece by piece instead.

**How often you'll meet it:** every day, once you work with tests (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

A big change to old code is a gamble; a string of small ones, each checked, isn't. Keep the pins green, take one step at a time, and undo the step that goes red. The pattern arrives by the end, and so does the feature.

## Key terms

- [Refactoring](https://www.ask-codey.com/glossary/refactoring)
- [Red, Green, Refactor](https://www.ask-codey.com/glossary/red-green-refactor)
- [Strategy Pattern](https://www.ask-codey.com/glossary/strategy-pattern)

## Cheat sheets

- [Refactoring Toward a Pattern, One Small Step at a Time](https://www.ask-codey.com/cheat-sheets/dp-refactoring-toward-a-pattern-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-refactoring-toward-a-pattern
