是否有充分的理由说明为什么在函数中只有一个return语句是更好的做法?
或者,一旦逻辑正确就可以从函数返回,这意味着函数中可能有很多返回语句?
我发现自己使用了以下练习,但每次使用它时,我内心都会有些畏缩.基本上,它是参数的前提条件测试,以确定是否应该完成实际工作.
public static void doSomething(List<String> things)
{
if(things == null || things.size() <= 0)
return;
//...snip... do actual work
}
Run Code Online (Sandbox Code Playgroud) 当我看到别人的代码时,我主要看到两种类型的方法样式。
一个看起来像这样,有许多嵌套的 if:
void doSomething(Thing thing) {
if (thing.hasOwner()) {
Entity owner = thing.getOwner();
if (owner instanceof Human) {
Human humanOwner = (Human) owner;
if (humanOwner.getAge() > 20) {
//...
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
而另一种风格,看起来像这样:
void doSomething(Thing thing) {
if (!thing.hasOwner()) {
return;
}
Entity owner = thing.getOwner();
if (!(owner instanceof Human)) {
return;
}
Human humanOwner = (Human) owner;
if (humanOwner.getAge() <= 20) {
return;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,这两种代码样式有名称吗?如果,他们叫什么。