When to use Case and If/Else?

Anthony Chang
3 min readJun 21, 2018

--

Often times I find myself overusing the if/elsif/else statement. My mind automatically thinks to use the if/elsif/else statements whenever I need to see if a certain condition is true or false. But what happens when there are an endless amount of conditions you have to account for?! I end up having to write a huge block of code and the code ends up looking like a mess. Don’t get me wrong, I love if/elsif/else statements, BUT theres a time and place for everything.

The If/Else Statement

The if/else statement allows us to create different paths of code depending on if a certain condition is true. For example in this code we are checking to see where the hungry level is over certain values. If the hungry level is over 7 then we want to put out “Your stomach is growling..I need to eat!!” elsif put out “I’m slightly hungry but I can wait to eat.” else puts out “I’m so full from the last meal..”

The if/else statement will always run the top line of code first to see if the condition returns true and then will run the following elsif if the previous condition returns false until the end statement.

Using the if/elsif/else statement can come in handy when you’re having to check for limited amount of conditional statements, but when the conditional statements start to become overwhelming or there are if/else statements inside other if/else statements it can be hard to follow and isn’t very user friendly to look at.

THE CASE STATEMENT

The case statement uses case, when, and else as keywords. I found case statements most handy when you want to test a single value for several conditions. For example in this CLI, the case statement is used for the single value, response. The case statement checks to see specifically what the variable response input will be and outputs certain methods based on the response.

I felt that when using the case statements instead of if/else statements I was able to be more specific with my conditions which is what I wanted.

The case statement can also be used with range of numbers that a value can fall under. For example it can see whether the value of grade is between 100 to 90, 89 to 80, 79–70, 69–60 or below and print to the screen the grade associated with it.

The Verdict

From my understanding I feel that its better to use case statements when theres multiple conditions involved. Looking at a bunch of if/else statements that are nested together can get bothersome to read so using a case statement in this instance is much more user friendly and easier to read. From personal experience during my first project I had a bunch of if/else statements in my run file. It made the file look clunky and messy and hard to visually see. When I switched over to the case statements it made it much more concise and readable. I’m excited to write more code to see where eat instance of using if/else and case statements will be most efficient!

--

--