Recently I’ve been asked why switch-case statements should be avoided, it turns out to be a pretty common question, and although I’m pretty happy with the reasoning of switch statements being less readable and maintainable, I had forgotten the source of this wisdom so I thought it would be worth revisiting.
I remember writing about avoiding using switch-case statements in my 2008 article on PHP optimisation tips. However, I only really talked about the fact that “if/else” statements being faster than case/switch statements. With the latest PHP speed improvements, this might not still be true or relevant, yet I still recognise these statements as a code smell. Why?
Let’s understand why Switch Statements are code smell.
Martin Fowler observes that Object Oriented Programming avoids them: “Most times you see a switch statement, you should consider polymorphism. The issue is where the polymorphism should occur.”
Essentially, something else is going on, more often than not. That’s why it is a Code Smell. When you get the Switch Statements Smell, it’s an indication that your code isn’t Object Oriented.
Bob Martin explains that if you follow the Open/closed principle (of SOLID principles), then when you add a new feature, you should be able to do that without changing any old code, simply by extending. Switch statements mean you can’t extend as you have to change the statement.
So there we have it, although there’s nothing inherently wrong with switch statements as such but chances are, there’s a better way.