DEV Community

Cover image for How to get rid of switch statements
Robert Bornschein
Robert Bornschein

Posted on

How to get rid of switch statements

Photo by Tim Mossholder from Pexels

Why get rid of switch statements, to begin with?

The answer is simple. Having switch statements is fine, but it could be better.
In the world of code, you will find something called the SOLID principles, which help you in writing clearer, cleaner, better code.

The switch statment

Imagine having to handle a "keydown" event. You want to handle each valid keycode accordingly. This is what you'd find most often.

image

Refactoring

How about this, let's create a class for the key press.
We need the keycode, we need the action it's supposed to take and an added bonus of possibly extra validation.
image

Now what?

Now we instantiate a new Object from our KeyPress class for each keycode you'd need.

image

And now the fun part!

We still need something to manage when and how each different keypress object is being called. This is where the handler comes into play. It'll need a bind method to add new KeysPress objects and a handle method, which is self-explanatory.

image

The moment you have all been waiting for!

That same function with the previous switch statement.
It's tiny. If you don't need any prior validation, it's basically a one-liner.

image

A few last words

Now why would you want to do this? For the sake of maintainability, decreased complexity.
You have essentially closed the handleKeyDown function for modificaiton. But it's still open for extension.

You can simply add new KeyPress Objects, add them to the list in the keyhandler and voila.
Your function still stays the same! That's crazy.

Next time you implement a switch statement like this, simply think of this:

Why not try something new this time?

Top comments (1)

Collapse
 
vaclavhodek profile image
vaclavhodek

The switch - case - break is another reason to love Kotlin's when :-).

when(x) {
  0 -> doA()
  1 -> doB()
  2 -> {
    doC()
    doD()
  }
  else -> doE()
}
Enter fullscreen mode Exit fullscreen mode