Programming style: should you return early if a guard condition is not satisfied?

Posted by John Topley on Stack Overflow See other posts from Stack Overflow or by John Topley
Published on 2010-05-28T11:31:55Z Indexed on 2010/05/28 11:42 UTC
Read the original article Hit count: 238

One thing I've sometimes wondered is which is the better style out of the two shown below (if any)? Is it better to return immediately if a guard condition hasn't been satisfied, or should you only do the other stuff if the guard condition is satisfied?

For the sake of argument, please assume that the guard condition is a simple test that returns a boolean, such as checking to see if an element is in a collection, rather than something that might affect the control flow by throwing an exception.

// Style 1
public SomeType aMethod() {
  SomeType result = null;

  if (!guardCondition()) {
    return result;
  }

  doStuffToResult(result);
  doMoreStuffToResult(result);

  return result;
}

// Style 2
public SomeType aMethod() {
  SomeType result = null;

  if (guardCondition()) {
    doStuffToResult(result);
    doMoreStuffToResult(result);
  }

  return result;
}

© Stack Overflow or respective owner

Related posts about control-flow

Related posts about program-flow