不必要的'其他'声明 [英] Unnecessary 'else' statement

查看:149
本文介绍了不必要的'其他'声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,在Eclipse中,您可以启用不必要的'else'语句检查将在 if-then-else 上触发并提前返回。而且,根据我的经验,使用此类声明时有两种最可能的情况:

As you know, in Eclipse you can turn on "Unnecessary 'else' statement" check that will trigger on if-then-else with premature return. And, from my experience, there are two most possible situations when use such statement:

1)预检:

if (!validate(arg1)) {
    return false;
}
doLotOfStuff();

2)检查后:

doLotOfStuff();
if (condition) { 
    return foo; 
} else {
    return bar; 
}

在第二种情况下,如果触发器打开,Eclipse会建议你将代码更改为:

In the second case, if the trigger is on, Eclipse will suggest you to change the code to:

doLotOfStuff();
if (condition) { 
    return foo; 
} 
return bar; 

但是,我认为返回 else 语句更具可读性,因为它类似于业务逻辑的直接映射。所以我很好奇这个不必要的'其他'声明代码约定是否广泛使用或者带有 else 语句的代码更可取?

However, I think that the return with else statement is more readable as it is like direct mapping of business logic. So I am curios if this "Unnecessary 'else' statement" code convention is widespread or code with else statement is more preferable?

推荐答案

通常我更喜欢代码的结构遵循底层业务逻辑的结构。在这种情况下,我的方法将取决于 condition 所代表的内容。如果是错误检查,例如,通常不会被命中但偶尔会被使用,那么第二种形式的不对称性与逻辑的不对称性相匹配。

Generally I would prefer the structure of the code to follow the structure of the underlying "business" logic. In this case, my approach would depend what condition represents. If it is an error check, for example, which won't normally be hit but might occasionally be used, then the asymmetry of the second form matches the asymmetry of the logic.

doLotOfStuff();
if (condition) { 
    return foo; 
} 
return bar; 

但是如果这两种可能性合理且只是它们之间的选择,我会允许它的结构用于显示对称性的代码。

But if either possibility is reasonable and it's simply a choice between them, I would allow the structure of the code to show that symmetry.

doLotOfStuff();
if (condition) { 
    return foo; 
} else {
    return bar; 
}

代码可供程序员阅读,而不是编译器。

The code is there for the programmer to read, not the compiler.

这篇关于不必要的'其他'声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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