CSE Roadmap

Core tier · about 2 hours · 7 parts

Part 4 of 7 · 2 min read

An if chain turned into polymorphism

Move each branch into its own class.

A made-up example from the room system. A fee depends on the kind of user:

// before
long fee(String kind, long baseCents) {
    if (kind.equals("STAFF")) return 0;
    else if (kind.equals("VISITOR")) return baseCents;
    else if (kind.equals("MEMBER")) return baseCents / 2;
    else throw new IllegalArgumentException(kind);
}

Problems: a misspelled string fails only at run time, and each new kind edits this method. The polymorphic version moves each branch into a class:

interface FeePolicy {
    long fee(long baseCents);
}

class StaffFee implements FeePolicy { public long fee(long b) { return 0; } }
class VisitorFee implements FeePolicy { public long fee(long b) { return b; } }
class MemberFee implements FeePolicy { public long fee(long b) { return b / 2; } }

For a base of 2,000 cents, staff pay 0, visitors 2,000 and members 1,000 (run to confirm). Calling code holds a FeePolicy and calls fee. Adding "STUDENT at 25 percent off" is one new class. This shape is the strategy pattern, which Level 4 covers fully.

Not every if should go. A single test on a value (is the balance enough?) is fine. The signal for polymorphism is a chain of tests on a type or kind that appears in more than one place. (Common practice.)

Common mistake

Replacing every if with a class. Two classes and an interface for one test on a number is more code and no gain.

Check yourself: 1. What fails at run time in the "before" version if the kind is spelled "Staff"? 2. How many places change when a student fee is added in each version? 3. Which pattern does the second version resemble?