Why is “else” rarely used after “if x then return”

2019-01-13 03:18发布

This method:

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

can equivalently be written:

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

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

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?

(Related: Should a function have only one return statement?)

23条回答
乱世女痞
2楼-- · 2019-01-13 03:26

It's religious argument and at the end of the day it doesn't matter. I'd even argue that the first form is more readable in some circumstances. If you have large chunks of code in an if-elseif-elseif-else, it's easier, at first glance to see what the default return is.

if (s == null) {
    return false;
}
else if (s.Contains(":))")) {
    return true;
}
else if (s.Contains(":-(")) {
    return false;
}

return s.contains(":)");
查看更多
等我变得足够好
3楼-- · 2019-01-13 03:26

Because there is an optional (switched off by default) warning in eclipse if else is used in such situation ;).

查看更多
可以哭但决不认输i
4楼-- · 2019-01-13 03:33

The else in that case would be redundant, as well as create unnecessary extra indentation for the main code of the function.

查看更多
Emotional °昔
5楼-- · 2019-01-13 03:33

The first form is simply less verbose - when you return a value you automatically leave the scope of the function you're in and return to the caller, so any of the code thereafter will only execute if the IF statement doesn't evaluate to true and subsequently return anything.

查看更多
老娘就宠你
6楼-- · 2019-01-13 03:34

I prefer writing it like this:

boolean containsSmiley(String s) {
    return s != null && s.contains(":)");
}
查看更多
虎瘦雄心在
7楼-- · 2019-01-13 03:34

I'd argue for readability. If you're scanning screens of code trying to figure out what the code does, it's a visual prompt to the developer.

...but it's not really needed because we all comment our code so well, right? :)

查看更多
登录 后发表回答