DEV Community

Cover image for Code Smell | Switch Statements
Jesús Mejías Leiva for Product Hackers

Posted on • Updated on • Originally published at blog.susomejias.dev

Code Smell | Switch Statements

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:

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 '🍇'
  }
}
Enter fullscreen mode Exit fullscreen mode

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] 
}
Enter fullscreen mode Exit fullscreen mode

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 😊

Top comments (2)

Collapse
 
mcsee profile image
Maxi Contieri

Why don't you create a polymorphic hierarchy of fruits ?

Collapse
 
susomejias profile image
Jesús Mejías Leiva • Edited

It would be a very good option, although for this use case it seems to me that it would introduce unnecessary complexity for simple emojis, although I really appreciate your point of view, this will help me improve my examples so that they are better and clearer.

Greetings and thank you very much for your comment Maxi 😊