Code Smell | Switch Statements

Code Smell | Switch Statements featured image

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.


Cause

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.


Example

Let's see an example of a switch statement that is not very advisable to use:

const getFruitEmoji = (fruit: string) => { switch (fruit) { case 'apple': return '🍎' case 'banana': return '🍌' case 'orange': return '🍊' case 'pineapple': return '🍍' default: return '🍇' } }

Solution

We will replace the switch with a simple object which will allow us to search by key.

const getFruitEmoji = (fruit: string) => { const FRUIT_EMOJI_MAP = { apple: '🍎', banana: '🍌', orange: '🍊', pineapple: '🍍', } return fruitEmojiMap[fruit] || '🍇' }

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.


Benefits

  • Less code.
  • Improves legibility.
  • Improves maintainability, you can export this object and use in a others parts of your application.

Thanks for reading me 😊