Switch Statements and Why They Are Useful

The newest powerup I added is the shield, which allows the player to hit an enemy once without taking damage.

Previously, we created a modular system to using powerups. Today I’d like to elaborate more on the key part, which is the point where we decide which powerup to give to the player.

Previously, we used multiple if-statements in order to control the method that we call on the player. This is a bit clunky and it requires the computer to evaluate the same variable _powerupID again and again.

A better way is to use a switch statement. Switch statements are broken up into cases that are used to determine which action we should take. If the switch expression matches a case, then the code will execute everything in that case. Then, it will continue through cases below that one until it reaches a break statement, which tells it to stop. Here we put break in every single case, since we don’t ever want more than one case to execute.

Switch statements are useful because they arrange the different code paths in a much more readable and intuitive way. It’s especially nice to have to evaluate the condition only once and just see which cases match. Finally, switch statements make it really easy to add on more functionality, since all you have to do is add a new case.

Remember to use switch statements whenever we would have to write a bunch of similar looking conditions. This will save a lot of time over the course of working on the project.

I’m a passionate and talented software engineer seeking an opportunity in game development.