Course contentsShow
← Computer Science
Lesson 2336 of 2,87252. Clean Code and RefactoringFree lesson

Switch Statement Smell

Identify excessive switch or if-else chains that should be replaced with polymorphism or strategy patterns.

Switch Statement Smell

You'll learn how to recognize when long switch or if-else chains signal a deeper design problem that polymorphism can solve.

What Is Switch Statement Smell?

A switch statement smell occurs when you have lengthy switch statements or cascading if-else chains that check the same type or condition in multiple places throughout your code. While switches aren't inherently bad, they become problematic when:

  • The same switch logic appears in several locations
  • You add new cases frequently, requiring changes across multiple files
  • The switch discriminates on type rather than simple values

This violates the Open/Closed Principle—your code isn't open for extension but closed for modification.

The Core Problem

Imagine a payment processing system with this pattern:

if type == "credit_card"
    process credit card
else if type == "paypal"
    process paypal
else if type == "bank_transfer"
    process bank transfer

When you add "cryptocurrency," you must hunt down every similar chain and update it. You've coupled behavior to type-checking logic scattered everywhere.

The Solution: Polymorphism

Instead of switching on types, create a hierarchy where each type knows its own behavior. Replace the switch with a single polymorphic call:

payment.process()

Each payment class (CreditCardPayment, PayPalPayment, etc.) implements process() differently. Adding cryptocurrency? Just create a new class—no existing code changes.

The Strategy Pattern you learned earlier exemplifies this: rather than switching between algorithms, you pass in strategy objects that handle their own execution.

When Switches Are Fine

Simple, stable switches (like days of the week) that don't duplicate across your codebase are perfectly acceptable. The smell emerges when switches repeat or when adding cases means editing distant code.

Key Takeaway: Replace type-checking switch statements that appear in multiple locations with polymorphic objects that encapsulate their own behavior, making your code easier to extend without modification.