Switch Statements to the Rescue

Bob Hilbig
1 min readSep 27, 2021

We’ve created a number of powerups for our ship. We’ve created functions to handle each powerup being collected. We’ve created a couple If statements to handle those powerups.
But what if we need more?
Those If statements are going to start getting cumbersome as a programmer to read.

Maintenance is annoying.
Maintenance is easier. More options on switches too!

When you begin to have many options consider using a switch statement. It looks neater and, depending on the conditions of the switch, perform better over time.

What you should avoid is nested switch statements. According to this article, nested switches take an oddly long time to compute. If you run into this, consider using nested Ifs, but if you have a lot you may try to reconsider how your code is structured.

Options on a switch include:
Break: exits the switch statement.
Goto: direct the program to another location, such as a different case in the switch statement.
Return: exits the function.

--

--