Code Smells: Switch Statements

Sometimes when we write our code. We use If or Switch-Case statements or even create our own hashmap statements to sort our type of data. For example when we want to create a conversion table that converts unit type to the millimeter. We will create:

Why this is a problem

In object-oriented programming, we will rarely see switch and case. Why? Because most of the times a switch can be scattered in different places in the program. When a new condition is added, we have to find all the switch everywhere and modify it. It will create a dependency for a class on the switch statements.

How to solve

As a rule of thumb, when we see a switch-case or too many if statement in a code, we should start thinking about Polymorphism. This tutorial would provide you how to do polymorphism well. This blog would be updated to include this polymorphism solution.

When to Ignore

  • When it performs such a simple operation like comparing two number, or something that does not have the branch behavior.
  • When input parser decide to parse and send the parser result.
  • When switch-case or branch operators are used by factory design patterns to select a created class.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade