Search code examples
if-statementcode-readabilityclarity

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..


Solution

  • Isn't this what assert was made for?

    if (condition1) { ... }
    else { assert(condition2); }
    

    This can be expanded for three-state logic, too.

    if (condition1) { ... }
    elsif (condition2) { ... }
    else { assert(condition3); }
    

    Using assert makes your code readable, easy to maintain, and clear. That being said, asserts and comments are almost interchangeable.