Part 3 of 6 · 3 min read
Before and after
From a type switch to a list of rules.
A first version of a pricing method has a switch on the customer type and a bulk rule with raw numbers.
static long priceBefore(Order o) {
long a = o.amount();
switch (o.customerType()) {
case "STUDENT": a = a - a * 10 / 100; break;
case "MEMBER": a = a - a * 15 / 100; break;
default: break;
}
if (o.items() > 5) a = a - 50;
return a;
}
For a student order of 1000 with 2 items (made up), the price is 900. For a member order of 2000 with 6 items, it is 1700 after the member discount and 1650 after the bulk discount. A guest order of 500 with 9 items gives 450. Every new discount needs an edit here, and every edit risks the cases already working.
CC lists smells that this code shows. A type switch is a smell, since the same switch tends to be copied in several places (Level 2, module 2). The raw numbers 10, 15, 5 and 50 are magic numbers, and CC says that numbers in code should hide behind well-named constants. The method also does several jobs.
The refactored version puts the axis behind an interface.
interface Rule { long apply(Order o, long price); }
final class PercentOff implements Rule {
private final String type; private final int percent;
PercentOff(String type, int percent) { this.type = type; this.percent = percent; }
public long apply(Order o, long p) {
return o.customerType().equals(type) ? p - p * percent / 100 : p;
}
}
final class BulkOff implements Rule {
static final int MIN_ITEMS = 5; static final long OFF = 50;
public long apply(Order o, long p) { return o.items() > MIN_ITEMS ? p - OFF : p; }
}
final class Pricer {
private final List<Rule> rules;
Pricer(List<Rule> rules) { this.rules = List.copyOf(rules); }
long price(Order o) {
long p = o.amount();
for (Rule r : rules) p = r.apply(o, p);
return p;
}
}
For the four sample orders, the old method and the new Pricer give the same four prices: 900, 1650, 450 and 300. That match is the proof that the refactoring kept the behaviour.
Now the interviewer says "add a festival discount of 25 off everything". With the new design, this is one new rule and no edited class.
Rule festival = (o, p) -> p - 25;
Added to the list, it brings the student order of 1000 from 900 to 875. The change landed in one place, which is what to say aloud in a round: "that is a new Rule, and Pricer does not change". The rules list is the strategy pattern (Level 4, module 1), and the list as a chain is close to the chain of responsibility (Level 4, module 8).
Check yourself: 1. What does each order return from the old and the new code? 2. Which classes change when the festival rule is added? 3. Name two smells in the old method.