javacoding-stylereturn-path

Better Java method Syntax? Return early or late?


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?


Solution

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