Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 57 ยท Anti-Patterns and Refactoring

Refactoring to Patterns

Learn how to refactor messy conditional code to Strategy, State and Factory step by step, with characterization tests that stay green after every small change.

Most of the time you do not design with patterns on a blank page. You meet code that already works, but is hard to change, and you slowly reshape it. Refactoring means changing the structure of code without changing what it does. Refactoring to patterns means using the patterns you know as destinations: you notice a smell, recognize which pattern removes it, and move there in small, safe steps.

This approach avoids two common mistakes. One is adding patterns up front, "just in case" (see speculative generality in Anti-Patterns and Code Smells). The other is leaving a growing if/else chain alone until nobody dares to touch it. Here you will take a small order system and move it, one step at a time, to Strategy, State and Factory Method, with tests proving the behavior never changes.

The safe refactoring loop

Pin behavior Write tests for what the code does today.
Spot the smell Which condition keeps growing?
One small step Extract, move, rename. Nothing more.
Run the tests Green? Continue. Red? Undo the step.
1 / 2

Step zero: pin the behavior with tests

You can only refactor safely if something tells you when you broke it. If the code has no tests, write characterization tests first. They do not check what the code should do. They record what it actually does today, including quirks. When the structure changes and the tests stay green, you know you preserved the behavior.

Our legacy order code has three decisions written as long conditionals: how much shipping costs, which status an order moves to, and how a notice is formatted for each channel. The first example shows the legacy code and the characterization tests. It uses Node's assert module, so a failing check throws an error.

Node.js Legacy code with characterization tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

All the checks pass on the legacy code. That is the safety net. Notice that the suite takes an api object: later we run the same suite against the new code without editing a single assertion.

Step one: switch on a type becomes Strategy

Look at legacyShipping. Every branch answers the same question ("what does this order cost to ship?") in a different way, and each new shipping method means editing the function. That is the smell switch on a type, and the fix is Strategy: one small object per algorithm, looked up by name.

The mechanical steps are:

  1. Extract each branch body into its own function or class with the same signature.
  2. Put them in a registry (a map from name to strategy).
  3. Replace the conditional with a lookup. Run the tests.

After this step, adding "drone delivery" means adding one entry, and the Open/Closed Principle is satisfied: you extend without modifying existing code.

Step two: switch on a status becomes State

legacyAdvance is a nested conditional on the order's current status. The outer if picks the state and the inner if picks the event, which is a state machine written the hard way. The pattern for this smell is State. In this refactor each state becomes a small object that knows its own allowed transitions and rejects anything else. Because the states here differ only in which events are allowed, each state object just holds a small table. If the states later grow real behavior (such as sending different emails), the same objects can take methods.

Step three: switch that creates objects becomes Factory Method

legacyNotice chooses a format by channel. Today the formats are one-liners, but real code would create a different notifier object per channel. The smell is a conditional that decides which object to build, and the pattern is Factory Method. Move the choice into a single createNotifier(channel) function. Callers no longer know the concrete types, and the only place that knows all channels is the factory.

The next example contains the refactored code next to the legacy functions, and runs the same suite against both. Then it adds a new shipping method without changing any existing line of the refactored code.

Node.js The same tests pass on the refactored code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both implementations pass the same 12 checks. The refactoring did not add features, and that is the point: structure changed, behavior did not. Only afterward did we use the new structure to add drone as a single set call.

Rules for refactoring safely

  • Small steps. Each step should take minutes and leave the tests green. If a step goes wrong, undo only that step.
  • Never mix refactoring and new features in one step. Refactor first, commit, then add the feature on top of the cleaner structure.
  • Let tests lead. If code is too tangled to test, first make a tiny seam (extract a function, pass a parameter instead of reading a global) so that you can.
  • Stop when the smell is gone. Do not keep adding patterns because the structure now allows it. Two strategies in a map is fine; a framework is not needed.
  • Check the result is simpler. If the new code is harder to read than the old one, the pattern was the wrong destination. Revert and try something smaller.

When not to refactor to a pattern

If a conditional has two branches and never changes, leave it. A map of three functions is more code than an if, and it only pays off once the list grows or changes often. Patterns are tools for managing change. Where there is no change, there is nothing to manage.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the first step before refactoring code that has no tests?

    Characterization tests pin down what the code does today, so you can tell whether a structural change altered behavior.
  2. 2. A function has an if/else chain choosing an algorithm by a type name. Which pattern is the usual destination?

    Each branch becomes an interchangeable strategy looked up by name, so new algorithms are added without editing the old ones.
  3. 3. Which is a good reason to stop refactoring toward a pattern?

    Patterns are a means to remove a smell. When the smell is gone, extra structure only adds cost.
  4. 4. Why is it bad to add a new feature in the same step as a refactoring?

    Keeping the two apart means a red test always points to the last small structural change.

Summary

  • Refactoring changes structure without changing behavior; refactoring to patterns uses patterns as destinations for a smell you already see.
  • Pin behavior first with characterization tests, then move in small steps that keep the tests green.
  • Switch on a type leads to Strategy, switch on a status leads to State, and a conditional that creates objects leads to Factory Method.
  • Run the same test suite against old and new code to prove nothing changed.
  • Do not mix refactoring with new features, and stop when the smell is gone.

Next lesson: How to Approach a Low-Level Design Problem.