if和if-else之间有明显的区别吗? [英] Is there any appreciable difference between if and if-else?

查看:138
本文介绍了if和if-else之间有明显的区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码段,是否有任何明显的区别?

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

public boolean foo(int input) {
   if(input > 10) {
       doStuff();
       return true;
   }
   if(input == 0) {
       doOtherStuff();
       return true;
   }

   return false;
}

vs。

public boolean foo(int input) {
   if(input > 10) {
      doStuff();
      return true;
   } else if(input == 0) {
      doOtherStuff();
      return true;
   } else {
      return false;
   }
}

一段代码...

public boolean foo(int input) {
   boolean toBeReturned = false;
   if(input > 10) {
      doStuff();
      toBeReturned = true;
   } else if(input == 0) {
      doOtherStuff();
      toBeReturned = true;
   }

   return toBeReturned;
}

有明显的性能差异吗?你觉得一个人比其他人更容易维护/可读吗?

Is there any perceptible performance difference? Do you feel one is more or less maintainable/readable than the others?

推荐答案

在第二个例子中,你非常清楚地表明两个条件是互斥的。

一个,它不是那么清楚,并且在(不可能)事件中,在两个if之间添加输入的赋值,逻辑将改变。

假设未来有人在第二个之前添加 input = 0

当然这不太可能发生,但是如果我们谈论可维护性这里,if-else清楚地说明了有互斥的条件,而一束ifs没有,并且它们之间不是如此相互依赖的if-else块。

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.

编辑:现在我看到,在这个特定的例子中,return子语强制互斥,但是同样,我们在谈论可维护性和可读性。

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.

无论如何,关于性能,如果这是用Java编码,你不应该关心几个if块的性能,如果它是嵌入在一个真正慢的硬件,也许,但肯定不是与java。

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.

这篇关于if和if-else之间有明显的区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆