Switch Statements vs if-else statements

Harvey Limbo
2 min readApr 1, 2021

--

For today’s short article, I’ll be going over some good rules of thumb when to use switch statements over if else statements and vice versa. While these may not be universally hard rules to follow for every coding project, its important to know the pros and cons of using switch statements and if-else statements.

Switch Statements

  • Good to use if there is only 1 condition to compare against. In the above example, the code only needs to compare against the powerUpID variable, so it would make using the switch statement here ideal.
  • Can optionally include a default case where if the powerUpID doesn’t meet any of the set cases above, it will have a case to run default logic under. Since I setup powerUpID to be an enum of type PowerUpType , I don’t need to worry about an unsupported case as they will all be enumerated through the PowerUpType enum.
  • Must include the break keyword after finishing a case to prevent the compiler from checking all other cases.
  • Switch statements can support multiple lines under the case block and right before the break keyword but the code can become harder to read. In my opinion, this is where if-else statements shine as the brackets help separate blocks of logic out into more readable chunks. Another option would be to group the blocks of logic into its own helper function so that the case block only has 1 line followed by the break keyword.

if-else Statements

  • Good to use if there are more than 1 conditions that need to be fulfilled via && operator (AND) or the || operator (OR).
  • Similar to how break keyword works, else statement only runs if the previous if statement is false. In other words, if the first if statement in the above example is true, the compiler will skip all other else if statements.
  • A drawback of if-else statements is that you may have to compare against the same variable multiple times with different values. For example, writing down if (powerUpID == PowerUpType.TRIPLE_SHOT) and if (powerUpID == PowerUpType.SPEED_BOOST) can become repetitive for the first half of the if statement and would be better suited to use a switch statement instead to avoid having to write if(powerUpID == multiple times for different cases.

Thanks for reading! :)

--

--

Harvey Limbo
Harvey Limbo

No responses yet