为什么是“其他"在“if x then return"之后很少使用? [英] Why is "else" rarely used after "if x then return"?

查看:19
本文介绍了为什么是“其他"在“if x then return"之后很少使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个方法:

boolean containsSmiley(String s) {
    if (s == null) {
        return false;
    }
    else {
        return s.contains(":)");
    }
}

可以等价地写成:

boolean containsSmiley(String s) {
    if (s == null) {
        return false;
    }

    return s.contains(":)");
}

根据我的经验,第二种形式更常见,尤其是在更复杂的方法中(可能有几个这样的退出点),throw"和return"也是如此.然而,第一种形式可以说使代码的条件结构更加明确.有什么理由更喜欢一个吗?

In my experience, the second form is seen more often, especially in more complex methods (where there may be several such exit points), and the same is true for "throw" as well as "return". Yet the first form arguably makes the conditional structure of the code more explicit. Are there any reasons to prefer one over the other?

(相关:一个函数是否应该只有一个 return 语句?)

推荐答案

以我的经验,这取决于代码.如果我在防范"某事,我会这样做:

In my experience, it depends on the code. If I'm 'guarding' against something, I'll do:

if (inputVar.isBad()) {
    return;
}

doThings();

重点很明确:如果那个陈述是错误的,我不希望函数继续.

The point is clear: If that statement is false, I don't want the function to continue.

另一方面,有些函数有多个选项,在这种情况下,我会这样写:

On the other hand, there are some functions with multiple options, and in that case I would write it like this:

if (inputVar == thingOne) {
    doFirstThing();
} else if (inputVar == secondThing) {
    doSecondThing();
} else {
    doThirdThing();
}

虽然可以写成:

if (inputVar == thingOne) {
    doFirstThing();
    return;
}
if (inputVar == thingTwo) {
    doSecondThing();
    return;
}
doThingThree();
return;

这实际上归结为最清楚地显示代码正在做什么的方式(不一定哪位代码最短或缩进最少).

It really comes down to which way most clearly shows what the code is doing (not necessarily which bit of code is shortest or has the least indentation).

这篇关于为什么是“其他"在“if x then return"之后很少使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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