Too many ifs? Lets switch that!

If if if if if if if if this if that if else… It can be really easy to get caught up in using too many if statements in your code. There can be so many decisions to be made in a game if the player does one of a thousand things. Thankfully there is an alternative way and it is in what is called a “switch” statement.

Previously in my code for my Powerups, I was using an if statement to check what Powerup ID the powerup had to determine what it would do.

However, using the much cleaner “switch” statement, we can break it down between cases. By telling the switch statement that each case# is a PowerupID, we have just easily linked it up to a variable to determine what the powerup is. So here, I have IDs 0–2 and each have their own respective code instructions.

Much cleaner, easier to look at, and easier to add on to!

I would say if you have more than 2 or 3 if statements in a set, a switch would be the way to go. I am going to have quite the number of powerups by the end so better to do this earlier than later!

See you on the next post!




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Monitor Nginx using Netdata on CentOS 7

Bug Bugger Buggest !

Mocking Techniques for Go

Xeus is now a Jupyter subproject

How to Setup WordPress with Nginx and HHVM on Ubuntu 16.04

How Scrum Helps Developers Build Technical Skills and Flexible Architecture

CS373 Fall 2021: Blog #12

The Best CakeFest Talks, So Far | CakePHP blog

Get the Medium app

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
Edward Kim

Edward Kim

More from Medium

THE HOLE: Looking for Connection in Isolation

Keeping the Faith: A Love Letter to Final Fantasy XIV’s English Localization

Video Games and Roleplay in Therapy? What you need to know.

Arcade Fire, Arctic Monkeys and LCD Soundsystem: 2022 Signals the Return of the Big Noughties Bands