Lions, and Tigers, and… Magic Numbers!?
Enums, switch statements and avoiding magic numbers
Yesterday we took a look at extending our power up system to include a new power up, the speed power up. Today we are adding another power up, the shield power up. Since a lot of the process of adding another power up is the same, I’m going to discuss something related instead of going over the step by step of adding our third power up. That would be avoiding magic numbers.
A magic number in programming is a raw value used without any clear indicator of what the value stands for. In our example above, it isn’t clear what the values of 0 and 1 stand for. We can infer that they have something to do with a type but not what each value represents. It can make debugging or even just reading code very difficult when your code is littered with magic numbers. For that reason, it is recommended, as good programming practice, to avoid magic numbers when ever possible. There are a few ways to do this, including assigning the number to a descriptive variable, using a constant variable is the value doesn’t change, using a static class that returns the magic values using descriptive names, or in the case of integer identifiers, you can sometimes use an Enum like we did in our previous article.
Because we initially chose to identify our power ups by an incrementing integer id (0, 1, 2, etc.) we can easily convert this to an Enum giving us the same behavior with an easily accessible name for readability.
Another advantage to using an Enum in this case is that it synergizes well with our switch statement making that even easier to read and understand at a glance!
Extending our switch statement and our Enum is as easy as adding a new value to the Enum and adding a new case for the Enum to the switch statement. Now we can focus on the behaviour of the activated shield power-up rather than the addition of the new collectable which should be straightforward and largely the same as adding the other power-up collectables.
Today we took a look at magic numbers and one way to avoid them in our code. Tomorrow we will look at adding some UI to our game so the user has some feedback! If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.