Day 22: Switch Statements to the Rescue
For our power ups we will end up having a lot of else if statements if we decided to add 20 power ups. Having a lot of if statements start to look not clean. If this would to get to 20, it’ll become a little hard to read as well. So we’ll switch to a switch statement.
All we need to do is add the switch keyword and put the condition in parentheses.
Next to see what the condition is equal to. We do this by using the case key word. Followed by a number of the power up ID.
After each case you will input the code that is needed to be done. Every case statement needs to have a break as well. The break lets the program know that the case has finished what it was asked to do.
At the end, you can have a default case. This is selected if none of the cases have been selected. The thing about default is that it is not required.
When it comes to switch statements they can be very useful, but they can become a mess. Jason Weimann talks about code smells with switches.