These types of if-elseif-else blocks appear all over the place, and in no small number (so the less the better). Every time I have to think and decide: Do I want the simpler or the more thorough of the two... and I don't want to think about it anymore.
For example, if I am expecting only one of three integers (0, 1, 2)... don't I want to know (throw or terminate) if I get something else? (In the case of Example #2, the function do_two() could be triggered by any value other than 0 or 1). Obviously, this may depend on if I want my code to break or to continue upon encountering an anomaly, which rigorous testing should detect anyways (but who can ever be sure?). But I am looking for an answer that is appropriate in all, or most, cases. Please explain your answer, if your reasoning differs from my own.
NOTE REGARDING DUPLICATE: I don't think this is a duplicate for two reasons: The answers to the question suggest using switch statements and code abstraction. I don't use switch statements for something this small due to the overhead, nevermind not liking them much at all. Second, if the code can be abstracted, I may still vary well need to run these checks... plus more overhead. My question is aimed at the necessity in covering corner cases using the final else. Most people, in my experience (which is minimal), would jump to using Example #1 if SCRUMing. I think the best point (comment -> answer?) is yes there is a difference and it depends on whether or not I am coding defensively.
Example #1:
if(!is_null(variable) && is_integer(variable))
{
if(variable == 0)
do_zero();
elseif(variable == 1)
do_one();
elseif(variable == 2)
do_two();
else
throw_error();
}
Example #2:
if(!is_null(variable) && is_integer(variable))
{
if(variable == 0)
do_zero();
elseif(variable == 1)
do_one();
else
do_two();
}
variable == 1
even if the earlier test succeeds. This may cause different behavior ifdo_one()
modifiesvariable
. Also note that Example #2 will be slower by a likely trivial amount. In any case, to me, this looks like an obvious switch statement and so shouldn't use if/else at all.