为什么我们使用if,else if而不是多个if块如果body是一个return语句 [英] Why we use if, else if instead of multiple if block if the body is a return statement

查看:291
本文介绍了为什么我们使用if,else if而不是多个if块如果body是一个return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是习惯使用if,else-if语句,而不是多个if语句。

I am always in the habit of using if, else-if statement instead of multiple if statements.

示例:

int val = -1;
if (a == b1) {
   return c1;
} else if (a == b2) {
   return c2;
} ...
...
} else {
   return c11;
}

如何与示例2比较:

if (a == b1) {
   return c1;
}
if (a == b2) {
   return c2;
}
....

if (a == b11) {
   return c11;
}

我知道功能明智他们是一样的。但是它是最好的做法,如果else - 如果,或不是?它是由我的一个朋友提出,当我指出他可以不同结构的代码库,使它更清洁。这已经是我的一个习惯,但我从来没有问为什么。

I know functionality wise they are the same. But is it best practice to do if else-if, or not? It's raised by one of my friends when I pointed out he could structure the code base differently to make it cleaner. It's already a habit for me for long but I have never asked why.

推荐答案

if-elseif-else 语句停止比较它找到一个是真的。 if-if-if 执行每次比较。第一个更高效。

if-elseif-else statements stop doing comparisons as soon as it finds one that's true. if-if-if does every comparison. The first is more efficient.

编辑:在注释中指出您执行返回每个如果块。在这些情况下,或在控制将离开方法(异常)的情况下,做多个如果语句和做 if-elseif -else 语句。

It's been pointed out in comments that you do a return within each if block. In these cases, or in cases where control will leave the method (exceptions), there is no difference between doing multiple if statements and doing if-elseif-else statements.

但是,最好的做法是使用 if-elseif-else 无论如何。假设你改变你的代码,使你不在每个如果块中做 return 然后,为了保持高效,您还必须更改为 if-elseif-else 成语。让它 if-elseif-else 从头开始保存您的编辑在未来,更清楚的人阅读你的代码(见证我的错误解释,我刚刚给你通过做一个跳过你的代码!)。

However, it's best practice to use if-elseif-else anyhow. Suppose you change your code such that you don't do a return in every if block. Then, to remain efficient, you'd also have to change to an if-elseif-else idiom. Having it be if-elseif-else from the beginning saves you edits in the future, and is clearer to people reading your code (witness the misinterpretation I just gave you by doing a skim-over of your code!).

这篇关于为什么我们使用if,else if而不是多个if块如果body是一个return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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