Hello, today I am writing again and this post I am going to introduce you to how we incur in a frequently common code smell called Switch Statements, is caused by the abusive use of the switch statements in our code.
The use of the switch structure is perfectly valid
I do not seek to try to avoid its use in 100% of cases but in a large percentage in which it will harm us.
The abusive use of the switch statements.
As I mentioned above, it is not always advisable to eliminate the switch, an example of this is the design patterns, in particular I would highlight the so-called Factory Method or Abstract Factory, it is very frequent to see its use.
Let's see an example of a switch statement that is not very advisable to use:
We will replace the switch with a simple object which will allow us to search by key.
I have created a small example to show one of the most common ways to eliminate this smell, especially in functional programming, the example could be more complicated if instead of emojis with function calls, but the way to proceed would be the same.
To correct this smell in object-oriented programming, it is common to use polymorphism if necessary, we must always analyze our code beforehand.
- Less code.
- Improves legibility.
- Improves maintainability, you can export this object and use in a others parts of your application.
Thanks for reading me 😊