Switching over to cleaner code — A quick tip on switch statements and why you should use them.

Luke Duckett
2 min readApr 13, 2021

You have 15 different powerups in your game. Do you really want 15 if/else statements?

When you want to add another powerup in you have to go back and edit your else statements, cutting, and moving code. This is where switch statements come in.

Switch statements are tidier, more performant, and are easier to read. They are also very easy to expand upon. They are called by using the keyword “switch” and passing in a parameter to check.

You can then provide a “case” which is what we check against the switch statement parameter. If there's a match we run the code under our case statement. To end a case we use the keyword “break” before adding our next case.

We also have a default case that is called if we do not get a match (similar to our else in an “if” statement”

Now let's show how easy it is to add a new check to a switch statement.

And as we can see our powerups still work as expected

That’s all for now.

--

--

Luke Duckett

🎮 First Nations Unity Dev from Wonnarua country 🏞️ | From Player to Lifelong Learner: Crafting Games, Debugging Code, and Embracing New Technology