Search code examples
if-statementconditional-statementsconventions

Is it preferred to use else or else-if for the final branch of a conditional


What's preferred

if n > 0
  # do something
elsif n == 0
  # do something
elsif n < 0
  # do something
end

or

if n > 0
  # do something
elsif n == 0
  # do something
else
  # do something
end

I was using else for awhile. I recently switched to doing elsif. My conclusions are the first option adds readability at the cost of more typing, but could confuse some people if they expect an else. I don't have enough experience to know if the first option would create more readability or more confusion and if there are other pros/cons I've missed.

For my specific example, where the scope of else is comparable to the previous conditions and what it does catch can be expressed as a simple condition, is using else preferable for the final branch? Also, would a different conditional influence the answer? I wrote the code in Ruby but I assume the answer is language agnostic. If it isn't, I would also like to know why.


Solution

  • You should know every execution path through your conditional logic regardless. That being said, a simple else for the remaining case is usually the most clear. If you only have an else if it makes the next guy scratch his head and wonder if you are missing something. If it makes you feel better to say "else what" then put an inline comment in else # n < 0

    edit after your edit:

    For my specific example, where the scope of else is comparable to the previous conditions and what it does catch can be expressed as a simple condition, is using else preferable for the final branch? Also, would a different conditional influence the answer? I wrote the code in Ruby but I assume the answer is language agnostic. If it isn't, I would also like to know why.

    Yes, else is still preferable. I can't think of any scenario that changes this answer. Having the else implies completeness in your logic. Not having the else will be distracting - others (or you at a later date) will have to spend more time scrutinizing the code to double check to make sure all conditions are being handled. In fact the coding standard I abide by, the Embedded C Coding Standard by BARR Group says this:

    "Any if statement with an else if clause shall end with an else clause. ... This is the equivalent of requiring a default case in every switch."

    This echos MISRA rule 14.10

    All if ... else if constructs shall be terminated with an else clause.

    *All of my examples pertain to C, but as you said in the post, this is someone agnostic to the language being used.