Code Smell | Switch Statements

Code Smell | Switch Statements

This code smell is caused by the abusive use of the switch statements.

ยท

2 min read

Hello, today I am writing again and in this post I am going to introduce you to how we incur a frequently common code smell called Switch Statements, which 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:

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 ๐Ÿ˜Š

ย