Code Smell 36 — Switch/case/elseif/else/if statements

First programming lesson: Control structures. Senior developer lesson: avoid them.

Photo by Adarsh Kummur on Unsplash

Problems:

  • Too many decisions together
  • Coupling
  • Duplicated code
  • Violation of Open/Closed Principle.
  • A new condition should not change the main algorithm.
  • Nulls

Solutions

  1. Polymorphism
  2. Create hierarchies/compose objects following Open closed principle.
  3. Use State pattern to model transitions.
  4. Use Strategy Pattern/Method Object to choose for branches.

Examples

  • Discrete Values
  • State transition
  • Algorithm choice.

Sample Code

Detection

Since there are valid cases for If/else usages, we should not pull the plug and forbid these instructions. We can put a ratio of if statements/other statements as a warning instead.

Relations

More info

If debugging is the process of removing software bugs, then programming must be the process of putting them in.

Edsger Dijkstra

Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

By Dev Genius

The best stories sent monthly to your email. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Maximiliano Contieri

Written by

I’m senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan.

Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store