If Statement Alternatives

What is the first thing that come to your mind when you read an article with a catchy title like “You don’t actually NEED if statements…

If Statement Alternatives
Photo by Author

What is the first thing that come to your mind when you read an article with a catchy title like “You don’t actually NEED if statements (ever)”?

While i was scheming through Medium, i found a post with that interesting title. Being curious, i clicked to see what the fuss it’s all about. Well, i gotta say, disappointed.

What kind of code base doesn’t contains if else statement?, i wonder

People tend to avoid if else statement. I admit it’s true, but only part of it is true, people tend to avoid “else” and never an if. Else statement makes your code harder to read when the if block is too long. Actually, when something’s too long, it’s a sign that you need to extract functions and stuffs to make your easier to read.

Nested if statement makes the code harder to read. That’s true. However, in the post, he show people how to avoid if statement by using switch statement instead. However, nesting switch statement is something that’s even considered illegal, the word “bad” is not descriptive enough for this act.

Ternary operator look better. Agree! Let’s dive into this a little bit

let result = a ? b : c;

This makes your code looks shorter, especially when you follow some coding convention and put the “{“ on a separate line. Like this:

if(condition){ 
 
} 
else{ 
 
}

That’s a pretty good use case. However, is it entirely good to always go for ternary operator? I have seen people write code this way:

var result = person.Cars.Where(x => x.CarName == "Toyota").Any(x => x.LicencePlate =="ABC") 
? "Legal" 
: (person.Bike.Any(x => x.Year > 2010))? "Legal" : "Illegal")

Well, the code gets ugly pretty quick. In that case, neither if else nor switch statement nor ternary operator could save you. What to do is to extract these 2 expressions and compute the result before using these results to make the better to read.

Final Thoughts.

Instead of telling people how to any kind of syntax, teach them how to write better code instead, the root cause of bad code doesn’t come from the syntax, it’s the way you write and express your code.