CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 3 of 7 · 1 min read

The growing chain

Spot the smell.

Here is a price calculator for the meeting room booking system of Level 0. The price depends on the kind of customer.

static double price(String kind, double base) {
    if (kind.equals("STAFF"))  return 0;
    if (kind.equals("MEMBER")) return base * 0.8;
    return base;
}

For a base price of 100, a member pays 80. The code is short and works. Now a student discount of 50 percent is requested. A developer opens price and adds a third if. Next month a corporate rate arrives, then a holiday offer. Each time the same method is edited, tested again, and released again. Every other caller of the method is exposed to every new mistake.

This is the smell to learn: a chain of if or switch statements that checks a kind or a type, and grows whenever a new kind appears. Two quick tests find it. First, does a new business case force an edit to an old method? Second, does the same chain appear in more than one place, so that a new kind forces several edits?

Switch smell

A switch smell is an if chain or switch that branches on the kind of a thing, and must be edited every time a new kind is added.

Example: the price method above, which gains one branch per customer type.

Check yourself: 1. What base price and kind give a result of 80? 2. What two questions find the switch smell? 3. Why does editing the method put other callers at risk?