lundi 29 décembre 2014

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 conslusions 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. I wrote the code in Ruby but I assume the answer is language agnostic. If it isn't, I would like to know why.


Aucun commentaire:

Enregistrer un commentaire