Is there any appreciable difference between if and if-else?

前端 未结 9 946
执笔经年
执笔经年 2021-01-12 06:55

Given the following code snippets, is there any appreciable difference?

public boolean foo(int input) {
   if(input > 10) {
       doStuff();
       retur         


        
9条回答
  •  [愿得一人]
    2021-01-12 07:50

    With the second example you state very clearly that both conditions are mutually exclusive.
    With the first one, it is not so clear, and in the (unlikely) event that an assignment to input is added between both ifs, the logic would change.
    Suppose someone in the future adds input = 0 before the second if.
    Of course this is unlikely to happen, but if we are talking about maintainability here, if-else says clearly that there are mutually exclusive conditions, while a bunch of ifs don't, and they are not so dependent between each other as are if-else blocks.

    edit:Now that I see, in this particular example, the return clause forces the mutual exclusivity, but again, we're talking about maintainability and readability.

    Anyway, about performance, if this is coded in Java you shouldn't care for performance of a couple of if blocks, if it were embedded C in a really slow hardware, maybe, but certainly not with java.

提交回复
热议问题