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

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

    Having been trained in Jackson Structured Programming in the late '80s, my ingrained philosophy was always "a function should have a single entry-point and a single exit-point"; this meant I wrote code according to Style 2.

    In the last few years I have come to realise that code written in this style is often overcomplex and hard to read/maintain, and I have switched to Style 1.

    Who says old dogs can't learn new tricks? ;)

提交回复
热议问题