Object-Orientation Abusers: Switch Statements
You'll learn: Why excessive switch or if-else chains often signal a missed opportunity for polymorphism and better design.
What's the Problem?
A switch statement smell occurs when you repeatedly use switch (or long if-else chains) on type codes or category values to decide behavior. Each time you add a new type, you must hunt down every related switch and add another case. This violates the Open/Closed Principle—your code isn't open for extension but closed for modification.
The Core Issue
Imagine a payment system checking payment type:
switch (paymentType) {
case CREDIT_CARD:
// credit card logic
case PAYPAL:
// PayPal logic
case BITCOIN:
// Bitcoin logic
}
This same switch appears wherever payment processing happens—calculating fees, validating, logging. Adding a new payment type means changing multiple places. Miss one? Bugs.
The Polymorphic Solution
Instead of switching on types, create a Payment hierarchy where each subclass implements its own behavior. The State or Strategy pattern naturally replaces these switches—each payment type becomes a class with overridden methods. The client code doesn't need to know which type; it just calls the method.
This is what polymorphism is for: letting objects handle their own type-specific behavior without the caller needing conditional logic.
When Switches Are Fine
A single, localized switch that rarely changes (like a factory creating objects) isn't a smell. The problem is scattered, duplicated switches that force shotgun surgery when adding types.
Key Takeaway:
When you find yourself switching on type codes in multiple places, you're probably missing a polymorphic design—refactor toward the Strategy or State pattern for extensibility without modification.