更好的 Java 方法语法? 早回来还是晚回来?

发布于 2024-07-21 17:05:32 字数 696 浏览 9 评论 0原文

重复: 一个函数应该只有一个 return 语句吗?

通常,您可能有一种方法可以检查多个返回 语句条件并返回状态(现在假设为布尔值)。 是定义一个标志,在方法期间设置它,然后在最后返回它更好:

boolean validate(DomainObject o) {
  boolean valid = false;
  if (o.property == x) {
     valid = true;
  } else if (o.property2 == y) {
     valid = true;
  } ...
  return valid; 
}

还是在知道方法的结果后简单地返回更好/更正确?

boolean validate(DomainObject o) {

  if (o.property == x) {
     return true;
  } else if (o.property2 == y) {
     return true;
  } ...
  return false; 
}

现在显然可能有 try/catch 块和所有其他类型的条件,但我认为这个概念很清楚。 意见?

Duplicate: Should a function have only one return statement?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

找回味觉 2024-07-28 17:05:33

如果您将调用该方法数千次,那么尽早返回可以更好地实现[稍微]提高的性能。

如果没有,那么我更喜欢延迟返回,因为它可以提高可读性。

请记住,程序员通常花在阅读上的时间比编写代码的时间多,因此您可以采取任何措施来提高可读性肯定会受到欢迎。

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.

夏至、离别 2024-07-28 17:05:33

与大多数编码风格一样,这实际上是一个偏好问题,但许多人认为保护子句成为最佳实践。

As with most coding styles, it's really a matter of preference, but guard clauses are considered by many to be a best practice.

三生殊途 2024-07-28 17:05:33

我更喜欢早点返回并避免深嵌套。 在方法开始时尤其如此:测试任何简单的东西,如果可以尽早退出(或抛出异常)。

如果它位于方法的中间,那么它更像是一个判断调用。

请注意,我会立即重构您的示例以使用单个 if

boolean validate(DomainObject o) {    
  if (o.property == x || o.property2 == y) {
     return true;
  } ...
  return false; 
}

我意识到这只是一个玩具示例,但我的观点是,寻找更多方法来简化代码总是值得的:)

I prefer returning early and avoiding deep nesting. This is particularly true 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:

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 :)

风渺 2024-07-28 17:05:33

我唯一会说你绝对不应该提前返回的是,如果你无法轻松地在一个屏幕中看到每个返回(无论使用相同代码库的人的标准是什么),你至少应该添加注释,表明如果有提前返回,该函数可以提前返回。

我唯一会说你绝对应该早点返回的情况是,如果你的代码看起来像......

boolean valid = true;
if( condition1 ) {
   valid = false;
}
if( valid ) {
   ...
   if( condition2 ) {
      valid = false;
   }
}
if( valid ) {
   ...
   if( condition3 ) {
      valid = false;
   }
}
... (etc)

但是,如果你发现自己处于这两种情况之一......你可能应该重构该函数。

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.

一个人练习一个人 2024-07-28 17:05:33

对我来说,这是一种没有正确答案的宗教战争话题。 反对提前返回的论点本质上可以归结为这样一个事实:只有一个函数可以退出的点会减少代码中可能的路径数量,从而至少在理论上减少出现错误的机会。 我个人的风格是,在需要提前返回的情况下这样做,在需要限制为一个返回声明的情况下,我会这样做。

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.

守望孤独 2024-07-28 17:05:33

如果不存在例外情况,我更愿意尽可能立即返回。

标志变量很容易被错误地管理,而且我一般反对标志变量。 不返回也可能会让维护者认为可以完成进一步的工作(如果方法很长)。

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).

半岛未凉 2024-07-28 17:05:33

有两个因素相互影响。

第一个因素是易于调试。 如果您立即返回(如第二个代码片段所示),有时调试大函数会变得困难,因为很难找到这些返回语句,特别是如果它们被错误地放在那里。

第二个因素是易于实施。 如果您在函数开头检查参数的基本正确性,并且在函数完成之前有很长一段代码,则可能必须将整个代码放入条件循环中。 如果不这样做,在某些时候该参数可能会被用于一些长时间的计算,浪费时间,因为无论如何它最终都会被拒绝。

所以,答案可能是这样的:

If the function is small, 
        save the return status in a variable and return at the end. 
else 
        return immediately.

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.
女皇必胜 2024-07-28 17:05:33

就我个人而言,我更喜欢第二种方法。 这对我来说简单明了,但我确实知道有些人必须在函数中只有一个返回。

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.

凉宸 2024-07-28 17:05:33

老实说我认为这取决于具体情况。 就我个人而言,我同时使用这两种方法,并根据哪一种使代码更清晰、更易于阅读来决定。

如果您有大量嵌套的 if 语句(或任何其他控制结构)并且可能会感到困惑,那么我会在语句内返回

不要太担心这种情况下的“最佳实践”,因为更重要的是代码清晰易懂。 使用适合具体情况的方法。

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

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.

吃不饱 2024-07-28 17:05:33

对于这种情况,我更喜欢:

boolean validate (DomainObject o) {
    if (o.property == x ||
        o.property2 == y ||
        ...) {
          return true;
    } else {
          return false;
}

一般来说,我喜欢使用提前返回来处理错误情况,并在最后返回来返回计算结果。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文