Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General programming - else or else if for clarity

In a situation where a variable could have two different values, and you do something if its one, something differnent if its the other, would you just do:

if(myVariable == FIRST_POSSIBLE_VALUE) { ... }
else { ... }

or would you do:

if(myVariable == FIRST_POSSIBLE_VALUE) { ... }
else if (myVariable == SECOND_POSSIBLE_VALUE) { ... }

for clarity, in a situation where a reader wouldn't necessarily be able to tell that they do the same thing (but the else if does a "needless" expression)? So what would you do? Thanks!

EDIT: There is actually about a lot more different options for something like this: ternary operator, if-else, if-elseif, if-elseif-else, -if-else(with assert), switch. Each one has its place, but its hard to decide..

like image 533
mk12 Avatar asked Dec 06 '22 05:12

mk12


1 Answers

I always prefer just plain else when there is no other possible state of the variable(ie, checking for null and all that). I may add a comment saying what the variable is if it isn't the first conditional, but that is only in cases where its like

if(color==red){
....
}else{ //our theme only allows for red and yellow, so the color must be yellow.
....
}

Also, this saves some time for the processor cause it won't have to check a useless variable(or worse in OOP, where checking that variable can take quite a few dereferences, function calls, and memory reads)

I never do something like

if(file.is_open==1){
....
}else if(file.is_open==0){
....

}

as is_open is a boolean, it is pointless to specify that because the only option left is 0, also this can save a little bit of typing when you must refactor your code to use is_open() instead, as now you only must change one line instead of two.

and 'else if' statements I think should be turned to switches if there is more than 1 'else if', unless of course the language makes it impossible(such as how C can't handle strings in switches)

like image 198
Earlz Avatar answered Jan 06 '23 05:01

Earlz