Refactoring toward a pattern
- Lesson 31 of 32
- 10 min
- Intermediate
- 12 steps
A `price()` with one `if` per customer kind works fine, until one more kind arrives. You will move it toward Strategy in small steps, with the tests green after each one, and see what to do when a step goes wrong.
- Per-kind ifs in price()
- 0
- Tests passing
- 4
- request
- response
- failed request
Step 1 of 12
Problem
One discount per kind, one if per kind
Your shop computes prices with price(kind, b): a student pays half and a senior pays 70 %. Each kind is an if inside the same function, and price("student", 100) returns 50.
With two branches it reads well and works. Nobody needs a pattern yet, and that is fine: you do not start from the pattern.
What changed
- price() with two branches
Step 2 of 12
Problem
The change that asks for a third if
Product asks for a teacher discount: teacher pays 80 %. The easy way is to paste a third if just like the other two.
That is the signal: the change makes you repeat the same thing again, inside a function that already works. Before adding the branch, ask whether you should first change the shape of the code so that adding a kind is easy.
What changed
- price(), about to grow again
Step 3 of 12
Concept
Refactoring is not rewriting
Martin Fowler defines refactoring as restructuring existing code by altering its internal structure without changing its external behavior, through a series of small transformations that preserve that behavior.
Rewriting is something else: throwing the function away and redoing it in one jump. When you refactor, price("student", 100) still returns 50 after every step.
Step 4 of 12
Technique
First, tests that pin what it does today
Before you move a line, write tests that call price() the way checkout does: a student, a senior and a kind with no discount. All three pass: that is your green point.
If you inherit code without tests, start the same way: write tests that record what the code does today, even if it looks odd, and do not fix it in the same step. Without that net you are not refactoring, you are guessing.
What changed
- 3 green tests
Step 5 of 12
Concept
The pattern is the destination, not the starting point
Fowler's refactoring catalog has a recipe for this case, Replace Conditional with Polymorphism: each branch of a per-kind if moves to its own piece. It is the road to Strategy, which you saw in its lesson.
Joshua Kerievsky wrote *Refactoring to Patterns* (Addison-Wesley, 2004) about this idea: reaching a pattern from code that already exists, through small refactorings, instead of designing it all up front. Here the plan is four steps, and the tests run after each one.
What changed
- a 4-step plan
Step 6 of 12
Solution
Step 1: student moves to a map
You create a byKind map with one function per kind. Its type, Discount, is a function that takes the price and returns the discounted price. You move only student, price() looks it up in the map first, and you delete the student if.
You run the tests: 3 of 3 green. For a while the map and the senior if live side by side, and that is fine: the pattern does not have to be complete in the first step. You commit and go on.
What changed
- byKind with student
- the student if
Step 7 of 12
Problem
Step 2: senior moves and a test fails
You move senior to the map and delete its if. While typing the function a mistake slips in: b * 0.07 instead of b * 0.7. The senior test expects 70 and gets 7.
There are no per-kind ifs left, but one test is red: the behavior changed, so this step is not a refactoring. Because the step was small, you know exactly where to look.
What changed
- senior in the map, with a bug
- the senior if
Step 8 of 12
Technique
Go back to the last green and redo the step
Do not pile fixes on top of red. Go back to the last green state, for example with git restore, which discards the changes since the step 1 commit, and redo the step with senior: (b) => b * 0.7.
The tests are back to 3 of 3. With small steps and one commit per green, a mistake costs you undoing one step, not redoing the whole refactoring.
What changed
- b * 0.07
- b * 0.7
Step 9 of 12
Solution
You reached Strategy without designing it first
What is left is cleaning up price(): it looks up byKind and delegates, or returns the price as is when the kind has no discount. It no longer asks which kind it is.
Every function in the map fits the same Discount type: that is Strategy, written with functions. You did not draw it on day one; it showed up when the code asked for it, with the tests green at every step.
What changed
- if (d) … return b
- return d ? d(b) : b
Step 10 of 12
Solution
Now adding teacher is one line
Only now do you make the change you were asked for: one line in byKind, teacher: (b) => b * 0.8, and a new test that expects 80 for a price of 100.
price() is not touched and the tests go from 3 to 4, all green. First you changed the shape of the code so the change would be easy; then you made the easy change.
What changed
- teacher in byKind
- 1 more test
Step 11 of 12
Trade-off
When not to refactor toward a pattern
If the code will be deleted soon, or it has no tests and there is no time to write them, leave it as it is. And with two branches that do not grow, the if is enough: a map and a type for two fixed cases is design nobody asked for.
Fowler sums up what building something just in case costs (YAGNI): building it, the delay to everything else, carrying it through every change, and repairing it if the design was the wrong one. Refactoring when the real need arrives does not go against YAGNI, because it makes the code easier to change. What the method costs: while you migrate, old and new code live together, so finish the migration instead of leaving it halfway.
Step 12 of 12
Summary
Small steps toward the pattern, always green
Start simple. When a change makes you repeat the same if, write tests that pin what the code does and move it toward the pattern in small steps that do not change what it returns.
If a test turns red, go back to the last green and redo the step. Once you get there, the change you were asked for is easy. If the code will be deleted soon, or there are no tests and no time to write them, do not start.
← → step · R replay · Space pause
You will learn
- Spot the signal: a change that makes you repeat the same `if`. (covered)
- Tell refactoring apart from rewriting. (covered)
- Write tests that pin what the code does before the first change. (covered)
- Reach the pattern in small steps and go back to the last green when one fails. (covered)
- Know when not to refactor toward a pattern. (covered)