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

后端 未结 12 996
孤独总比滥情好
孤独总比滥情好 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:26

    I would say "It depends on..."

    In situations where I have to perform a cleanup sequence with more than 2 or 3 lines before leaving a function/method I would prefer style 2 because the cleanup sequence has to be written and modified only once. That means maintainability is easier.

    In all other cases I would prefer style 1.

提交回复
热议问题