Code Smell | Switch Statements

Code Smell | Switch Statements

January 11, 2023

codequality
refactorit
code-smell

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


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:

type Fruit = 'apple' | 'banana' | 'orange' | 'pineapple' | 'raspberry'
 
const getFruitEmoji = (fruit: Fruit) => {
    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.

type Fruit = 'apple' | 'banana' | 'orange' | 'pineapple' | 'raspberry'
 
const getFruitEmoji = (fruit: Fruit) => {
    const FRUIT_EMOJI_MAP = {
        apple: '🍎',
        banana: '🍌',
        orange: '🍊',
        pineapple: '🍍',
        raspberry: '🍇',
    }
 
    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 😊