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

后端 未结 12 1025
孤独总比滥情好
孤独总比滥情好 2020-12-28 13:46

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 sat

12条回答
  •  清歌不尽
    2020-12-28 14:30

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

提交回复
热议问题