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

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

    Martin Fowler refers to this refactoring as : "Replace Nested Conditional with Guard Clauses"

    If/else statements also brings cyclomatic complexity. Hence harder to test cases. In order to test all the if/else blocks you might need to input lots of options.

    Where as if there are any guard clauses, you can test them first, and deal with the real logic inside the if/else clauses in a clearer fashion.

提交回复
热议问题