language-agnosticcontrol-flowprogram-flow

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


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. Also assume that methods/functions are short enough not to require editor scrolling.

// 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;
}

Solution

  • I prefer the first style, except that I wouldn't create a variable when there is no need for it. I'd do this:

    // Style 3
    public SomeType aMethod() {
    
      if (!guardCondition()) {
        return null;
      }
    
      SomeType result = new SomeType();
      doStuffToResult(result);
      doMoreStuffToResult(result);
    
      return result;
    }