Better Java method Syntax? Return early or late? [duplicate]

安稳与你 提交于 2019-11-29 15:28:09

问题


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?


回答1:


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.




回答2:


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




回答3:


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




回答4:


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.




回答5:


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.




回答6:


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




回答7:


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.



回答8:


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.




回答9:


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.




回答10:


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.



来源:https://stackoverflow.com/questions/884429/better-java-method-syntax-return-early-or-late

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!