开发者

Best Practice for IF/ELSE Statement Order (when one case is never allowed)

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 开发者_C百科(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


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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜