Clean Up Your Conditional Logic With The Switch Statement

Joshua Nielsen
3 min readJun 23, 2021

--

Photo by Pixabay from Pexels

In the last article, we learned about making Unity game objects more modular and reusable. But an aspect to making them more modular means more conditional logic is needed to determine what exactly we’re trying to do with the game object. And when we have a lot of conditions to sift through, our best friend is the subject of today’s article — the switch statement.

Photo by Pixabay from Pexels

No, not that switch.

Stating the problem

Let’s consider an example. Imagine you were working on a user review system where a user can give a review of 1–5 stars. Now imagine you wanted to provide a word that describes what each level of rating means (5 stars is excellent, 4 is good, etc). How to accomplish this?

With the normal if else paradigm, we would need a separate statement for each individual possibility. In our example, that is five separate statements.

Our review system using if else statements

This is just six statements, and it’s already starting to look a bit unwieldy. Imagine if we needed even more than that.

The solution

Enter the subject of the article — the switch statement.

The switch statement acts as something of a shorthand for a series of if else statements. Using our same example as before, the switch statement looks like this:

Our review system using a switch statement

In comparison to the if else statements, with the switch statement we have a variable (in this example, x). This variable is compared to the various case statements within the switch. The case statements are followed by the expected values. So in the example of case 5, that means we are looking at the variable x and if the value of x is 5, then we want to run this code block.

The case statements are capped with a break statement. The break statement is somewhat similar to the semicolon in that it shows where the code block for a particular case ends.

There’s also the default case, which acts essentially the same as an else statement. It covers all values of the variable that don’t match with the specified cases.

If you would like to learn more about the switch statement, check out the official documentation. In the next article, we’ll be taking our first look at building UI elements in Unity. Until then, good luck and happy coding!

--

--

No responses yet