Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if / else / else if statements, a matter of function or style?

I am comparing data that can have only 3 possible results, less than, greater than, or equal to.

Hence the last statement could be an else or an else / if, and the block would behave the same:

  if(iter.data === data) {
    return iter;
  } else if(data < iter.data) {
    iter = iter.left;

  // else or else if will suffice here
  } else if(data > iter.data) {
    iter = iter.right;
  }

Is there any functional difference I am missing, or is this simply a matter of style?

Is there a good style reference, that covers this if it is only a matter of style?


2 Answers

The compiler/interpreter won't care and will optimize these regardless, but from a mental load standpoint else if implies another comparison, whereas else implies a "fall-through" and most codebases will prefer the latter.

As an added bonus, the fall-through also ensures that one of the branches is always taken. Generally speaking, no branches being taken at all could potentially lead to much weirder bugs than the wrong branch being taken.

like image 74
David Titarenco Avatar answered Oct 25 '25 21:10

David Titarenco


Just for fun, let me add:

switch (true){
  case iter.data === data: return iter;
  case iter.data > data: iter = iter.left; break;
  case iter.data < data: iter = iter.right; break;
}

With the example, I probably would do this though:

if (iter.data === data) {
  return iter;
}
iter = (iter.data > data) ? iter.left : iter.right;

It highlights the different behavior between the branches (return vs assignment), which for me is the most important thing to recognize. And it even has the least lines of code.

But yes, it is a matter of taste.

like image 38
Moritz Ringler Avatar answered Oct 25 '25 23:10

Moritz Ringler