# Code Smell 36 - Switch/case/elseif/else/if statements

*First programming lesson: Control structures. Senior developer lesson: avoid them.*

# Problems

*   Too many decisions together
    
*   Coupling
    
*   Duplicated code
    
*   Violation of [Open/Closed Principle](https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle).
    
*   A new condition should not change the main algorithm.
    
*   Nulls
    

# Solutions

1.  Polymorphism
    
2.  Create hierarchies/compose objects following *Open closed principle*.
    
3.  Use [State pattern](https://en.wikipedia.org/wiki/State_pattern) to model transitions.
    
4.  Use [Strategy Pattern](https://en.wikipedia.org/wiki/Strategy_pattern)/[Method Object](https://wiki.c2.com/?MethodObject) to choose for branches.
    

# Examples

*   Discrete Values
    
*   State transition
    
*   Algorithm choice.
    

# Sample Code

## Wrong

%[https://gist.github.com/mcsee/fd1c07ce153817a5572cb3cb84ae1007] 

## Right

%[https://gist.github.com/mcsee/ef02daf9882bbf6a6f12820b31e19920] 

# Detection

Since there are [valid cases](https://maximilianocontieri.com/how-to-get-rid-of-annoying-ifs-forever) for If/else usages, we should not pull the plug and forbid these instructions. We can put a ratio of if statements/other statements as a warning instead.

# Relations

%[https://maximilianocontieri.com/code-smell-12-null] 

# More info

%[https://maximilianocontieri.com/how-to-get-rid-of-annoying-ifs-forever] 

%[https://refactoring.guru/es/replace-conditional-with-polymorphism] 

# Credits

Photo by [Adarsh Kummur](https://unsplash.com/@akummur) on [Unsplash](https://unsplash.com/s/photos/tree)

> If debugging is the process of removing software bugs, then programming must be the process of putting them in.

*Edsger Dijkstra*

%[https://mcsee.hashnode.dev/software-engineering-great-quotes] 

* * *

This article is part of the CodeSmell Series.

%[https://mcsee.hashnode.dev/how-to-find-the-stinky-parts-of-your-code]
