Part 4 of 7 · 2 min read
The rewrite
An interface and one class per case.
The fix has three steps. Name the idea that varies, which here is "a price rule". Write an interface for it. Then write one small class per case, and let the calling class loop over a list.
interface PricingRule {
boolean applies(String kind);
double price(double base);
}
class Staff implements PricingRule {
public boolean applies(String k) { return k.equals("STAFF"); }
public double price(double b) { return 0; }
}
class Member implements PricingRule {
public boolean applies(String k) { return k.equals("MEMBER"); }
public double price(double b) { return b * 0.8; }
}
class Pricer {
private final List<PricingRule> rules;
Pricer(List<PricingRule> rules) { this.rules = List.copyOf(rules); }
double price(String kind, double base) {
for (PricingRule r : rules) {
if (r.applies(kind)) return r.price(base);
}
return base;
}
}
With rules for staff and members, a member at base 100 pays 80, and a student pays the full 100, since no rule matches. Now the student discount arrives. A developer writes one new class and adds it where the Pricer is built.
class Student implements PricingRule {
public boolean applies(String k) { return k.equals("STUDENT"); }
public double price(double b) { return b * 0.5; }
}
Pricer pricer = new Pricer(List.of(new Staff(), new Member(), new Student()));
The student now pays 50 and a guest pays 100. The Pricer, Staff and Member classes were not edited. Only new code was added, plus the one line that lists the rules. That one line is the only place that knows every rule, and it can be moved to a configuration file or a factory later.
The same shape appears in several patterns: strategy (module 1 of Level 4), observer, decorator and command. HF names several of them as ways to meet this principle. Reading them later becomes easier once the shape is familiar.
Read it as
Old code depends on an interface. New cases are new classes behind that interface. Nothing old needs to know the new class exists.
Check yourself: 1. What is the "idea that varies" in the pricing code? 2. What was added to support students, and what stayed the same? 3. Where does the list of rules get built?