更好的 Java 方法语法?早退还是晚退?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/884429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Better Java method Syntax? Return early or late?
提问by Gandalf
Often times you might have a method that checks numerous conditions and returns a status (lets say boolean for now). Is it better to define a flag, set it during the method, and return it at the end :
很多时候你可能有一个方法来检查多个条件并返回一个状态(现在可以说是布尔值)。定义一个标志,在方法期间设置它,并在最后返回它是否更好:
boolean validate(DomainObject o) {
boolean valid = false;
if (o.property == x) {
valid = true;
} else if (o.property2 == y) {
valid = true;
} ...
return valid;
}
or is it better/more correct to simply return once you know the method's outcome?
还是在知道方法的结果后简单地返回更好/更正确?
boolean validate(DomainObject o) {
if (o.property == x) {
return true;
} else if (o.property2 == y) {
return true;
} ...
return false;
}
Now obviously there could be try/catch blocks and all other kinds of conditions, but I think the concept is clear. Opinions?
现在显然可以有 try/catch 块和所有其他类型的条件,但我认为这个概念很清楚。意见?
回答by Seb
If it's a method you'll be calling thousands of times, then early return is better to achieve a [slightly] increased performance.
如果它是一个您将调用数千次的方法,那么提前返回更好地实现 [略微] 提高的性能。
If not, then I'd prefer late return, since it improves readability.
如果没有,那么我更喜欢延迟返回,因为它提高了可读性。
Remember programmers usually spend more time reading than writing code, so anything you can do to improve readability will be certainly welcome.
请记住,程序员通常花更多的时间阅读而不是编写代码,因此您可以做的任何事情来提高可读性肯定会受到欢迎。
回答by Jon Skeet
I prefer returning early and avoiding deep nesting. This is particularlytrue right at the start of the method: test anything that's simple, and get out (or throw an exception) if you can do so really early.
我更喜欢早点返回并避免深度嵌套。这在方法开始时尤其正确:测试任何简单的东西,如果可以尽早退出(或抛出异常)。
If it's right in the middle of a method, it's more of a judgement call.
如果它正好在一个方法的中间,它更像是一个判断调用。
Note that I'd refactor your example straight away to use a single if:
请注意,我会立即重构您的示例以使用单个if:
boolean validate(DomainObject o) {
if (o.property == x || o.property2 == y) {
return true;
} ...
return false;
}
I realise this was only a toy example, but my point is that it's always worth looking for more ways to simplify your code :)
我意识到这只是一个玩具示例,但我的观点是寻找更多方法来简化代码总是值得的:)
回答by Bill the Lizard
As with most coding styles, it's really a matter of preference, but guard clausesare considered by many to be a best practice.
与大多数编码风格一样,这确实是一个偏好问题,但许多人认为保护子句是最佳实践。
回答by Illandril
The only time I would say you definitely shouldn't return early is if you can't easily see every return within a single screen (whatever the standard might be for people working on the same code base), you should at the very least be adding comments indicating that the function can return early if there is an early return.
我唯一一次要说你绝对不应该早点返回是如果你不能在一个屏幕中轻松看到每个返回(无论标准对于在相同代码库上工作的人来说是什么),你至少应该是添加注释,表明如果有提前返回,该函数可以提前返回。
The only time I would say you definitely should return early is if your code looks like...
我唯一一次说你绝对应该早点回来是如果你的代码看起来像......
boolean valid = true;
if( condition1 ) {
valid = false;
}
if( valid ) {
...
if( condition2 ) {
valid = false;
}
}
if( valid ) {
...
if( condition3 ) {
valid = false;
}
}
... (etc)
If you find yourself in either of these situations, however... you should probably be refactoring the function.
但是,如果您发现自己处于这两种情况中的任何一种情况……您可能应该重构该函数。
回答by shsteimer
To me, this is sort of one of those religious war topics with no correct answer. The argument against returning early essentially boils down to the fact that having one and only one point where a function can exit reduces the number of possible paths through your code, thus, in theory at least, reducing the chances for bugs. My personal style is to, in situations where it makes sense to return early do so, and in situations where it makes sense to limit to one return statement I do that.
对我来说,这是一种没有正确答案的宗教War话题。反对提前返回的论点基本上归结为这样一个事实,即只有一个函数可以退出的点会减少通过代码的可能路径的数量,因此,至少在理论上,减少了出现错误的机会。我的个人风格是,在需要提前返回的情况下这样做,而在限制为一个返回语句的情况下我这样做是有意义的。
回答by Ben S
If exceptions aren't part of the picture, I prefer returning immediately when I can.
如果异常不是图片的一部分,我更喜欢尽可能立即返回。
It can be easy to mismanage the flag variable and I'm against flag variables in general. Not returning also might make a maintainer think that further work might be done (if the method is long).
标志变量很容易管理不善,我一般反对标志变量。不返回也可能使维护者认为可能会完成进一步的工作(如果方法很长)。
回答by euphoria83
There are two factors pulling against each other.
有两个因素相互拉动。
The first factor is ease of debugging. If you return immediately (as shown in your second code snippet), it sometimes becomes difficult to debug a big function since it is hard to find these return statements, specially if they were put there by mistake.
第一个因素是易于调试。如果您立即返回(如您的第二个代码片段所示),有时很难调试一个大函数,因为很难找到这些返回语句,特别是如果它们被错误地放在那里。
The second factor is ease of implementation. If you are checking basic correctness of arguments at the beginning of the function and there is a long piece of code before the function finishes, you might have to put that entire code in a condition loop. If you don't, at some point the argument might get used for some long calculation, wasting time, because it would ultimately be rejected anyways.
第二个因素是易于实施。如果您正在检查函数开头参数的基本正确性,并且在函数完成之前有一段很长的代码,您可能必须将整个代码放入条件循环中。如果你不这样做,在某些时候,这个参数可能会被用于一些长时间的计算,浪费时间,因为它最终会被拒绝。
So, the answer could be like this:
所以,答案可能是这样的:
If the function is small,
save the return status in a variable and return at the end.
else
return immediately.
回答by user49117
For this case, I prefer:
对于这种情况,我更喜欢:
boolean validate (DomainObject o) {
if (o.property == x ||
o.property2 == y ||
...) {
return true;
} else {
return false;
}
In general, I like to use early return to handle error conditions, and return at the end to return computed results.
一般来说,我喜欢使用提前返回来处理错误情况,并在最后返回以返回计算结果。
回答by Tom Neyland
Honestly I think it depends on the situation. Personally I use both, and I decide based on which one will make the code more clear and easy to read.
老实说,我认为这取决于情况。就我个人而言,我同时使用这两种方法,我会根据哪一种使代码更清晰易读来决定。
If you have heavily nested if statements (or any other control structure) and it may get confusing, then I would return inside the statements
如果你有大量嵌套的 if 语句(或任何其他控制结构)并且可能会让人感到困惑,那么我会在语句中返回
Don't worry too much about what is 'best practice' in this case, as it is more important that the code is clear and easy to understand. Use what feels right for the situation.
在这种情况下,不要太担心什么是“最佳实践”,因为代码清晰易懂更为重要。使用适合情况的方法。
回答by CookieOfFortune
Personally, I like the second method better. It is straightforward and clearer to me, but I do know there are people who must have only one return in a function.
就我个人而言,我更喜欢第二种方法。对我来说这很简单明了,但我知道有些人必须在一个函数中只有一个返回值。

