如果不需要,应该保留还是放弃? [英] Should 'else' be kept or dropped in cases where it's not needed?

查看:135
本文介绍了如果不需要,应该保留还是放弃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个琐碎的问题,但我一直在想的东西。



在风格方面(我假设性能是一样的)



例如,以下哪项更好:

  if(x <10)
doSomething();
else if(x> 20)
doSomethingElse();

  if(x <10)
doSomething();
if(x> 20)
doSomethingElse();

另一种情况:

  if(x< 10)
return;
else doSomething();

  if(x <10)
return;
doSomething();

感谢,



Luke

解决方案

在第一个例子中,肯定保留 else



(即如果你这样做:

  if(x <10)
doSomething();
if(x> 20)
doSomethingElse();



但是,如果你执行以下操作:pre>

  if(x <10)
doSomething();
else if(x> 20 )
doSomethingElse();

第二部分只有在第一部分为假时才被评估。 [如果x <10,你甚至不想检查x> 20,这浪费了评估...])



第二个是个人设计决策;选择哪些更吸引你,适合特定的逻辑更多,或遵循贵公司的标准,如果他们有任何。


This is a sort of trivial question but something I've been wondering about.

In terms of style (I assume the performance is identical), is it better to keep an 'else' in an if statement where it's not necessary?

For example, which of the following is better:

if (x < 10)
  doSomething();
 else if (x > 20)
  doSomethingElse();

or

if (x < 10)
 doSomething();
if (x > 20)
 doSomethingElse();

Another case:

if (x < 10)
 return;
else doSomething();

or

if (x < 10)
 return;
doSomething();

Thanks,

Luke

解决方案

In the first example, definitely keep the else in - it prevents an extra evaluation if the first part is true.

(i.e. if you do:

    if (x < 10) 
     doSomething(); 
   if (x > 20) 
    doSomethingElse();

both ifs are always evaluated.

However, if you do:

if (x < 10)
  doSomething();
else if (x > 20)
  doSomethingElse();

the second part is only evaluated if the first is false. [If x < 10, you don't even want to check if x > 20, it's a waste of an evaluation...])

The second is a personal design decision; choose which appeals more to you, fits the particular logic more, or follows your company's standards if they have any.

这篇关于如果不需要,应该保留还是放弃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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