Reputation: 216
In a simple if-else case (where the denominator of a fraction will need to be checked for a value of zero for each entry), does a correct arrangement of the statements even exist?
For example:
if (!(denominator == 0))
{
quotient = numerator / denominator;
System.out.println(numerator + " / " + denominator + " = " + quotient);
}
else
{
System.out.println("Division by zero is not allowed.");
}
or
if (denominator == 0)
{
System.out.println("Division by zero is not allowed.");
}
else
{
quotient = numerator / denominator;
System.out.println(numerator + " / " + denominator + " = " + quotient);
}
I know this is a trivial example, but I am curious if there is any benefit to giving consideration to the ordering of the if-else statements (in a case such as above). For less trivial testing of input/values, I can understand the consensus answer put forth here: Best Practice on IF/ELSE Statement Order.
Apologies in advance if this is a bad question (or one with what should have an obvious answer). My intent is to increase the general efficiency of my coding. Although, I doubt that there is any significant difference between the two examples that I have given. My newbie analysis indicates that the denominator will be tested for zero either way therefore negating any benefit of testing for the "normal case". Please correct/enlighten me if I am wrong.
TIA
Upvotes: 1
Views: 1154
Reputation: 41823
Another answer here mentions Code Complete (a great book) as an example of having the most normal case first. I agree with this completely. However, as your behaviour isn't "if(normal) doSomething (otherwise rare case) doSomethingRarer" I don't think this applies. Insted McConnell's advice of exit early seems appropriate:
/* Probably should be throw new Exception(".."); */
if (denominator == 0)
return "Division by zero is not allowed.";
quotient = numerator / denominator;
return(numerator + " / " + denominator + " = " + quotient);
Upvotes: 4
Reputation: 15211
In the end, it's the compiler's job to order this sort of thing for maximal performance. When it comes to a detail this trivial, your primary concern should nearly always be for simple and readable code. So the second example would get my vote because there's (marginally) less to it.
Upvotes: 0
Reputation: 106806
Steve McConnell has some advice in Code Complete. He suggest that the non-abnormal or most frequently used branch of the if statement should appear first. (Your first code example.)
With regards to performance there should be no difference.
Upvotes: 2