views:

567

answers:

12

Duplicate: Should a function have only one return statement? and Single return or multiple return statements?

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

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.

shsteimer
A: 

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.

CookieOfFortune
+1  A: 

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

Bill the Lizard
This is not a matter of guard clause; it's a matter of returning different values depending on parameters. Nobody talked about parameters being right or wrong, or the need of having preconditions.
Seb
@Seb: Guard clauses are similar to, not the same as, preconditions. Guard clauses aren't restricted to parameter validation, either. You can use a guard clause to quickly return in trivial cases, resulting in multiple return points, which is what the question is about.
Bill the Lizard
+3  A: 

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.

Seb
How is late return more readable? To me it's convoluted to return late. I infer from it that the method isn't done doing what it needs to if it hasn't returned.
Ben S
It's more readable because you don't cut the process flow in the middle of it. Instead, you save the state and return at the end of the method.
Seb
I find the flag way less readable precisely because you have to follow exactly each condition, method call, etc. to know if someone else touched the flag before returning, whereas with the other alternative you are certain that when property is equal to x you will get true, no matter what else happens there.
Vinko Vrsalovic
A: 

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

Ben S
A: 

I think you should return as soon as possible.

Since the return is as soon as possible, this increases the efficiency (yeah, only a little bit) of the method.

It also helps you a lot when debugging your code. I think this increases the readability also a little bit. Also if the method is very complicated, you can be sure that your method will not do things that it is not supposed to do (even though if it does, there is something else wrong with the code).

Niyaz
A: 

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.

instanceofTom
A: 

The latter, unless readability is a must.

James
Readability *is* a must - which is why I prefer the latter. It reduces the level of nesting, and reduces the amount of context the reader needs to remember. It also means that *if* the reader is in the first couple of conditions, they don't need to read any of the rest of the code.
Jon Skeet
I meant in terms of having declaring a more descriptive variable name for the particular function I didn't mean in general.
James
A: 

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

Jon Skeet
A: 

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.

A: 

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.
euphoria83
+1  A: 

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.

Illandril
+1 for your last line; you should indeed be pulling out smaller methods if the function gets to be too long.
Hace