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

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

    Style 1 is what the Linux kernel indirectly recommends.

    From http://www.kernel.org/doc/Documentation/CodingStyle, chapter 1:

    Now, some people will claim that having 8-character indentations makes the code move too far to the right, and makes it hard to read on a 80-character terminal screen. The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.

    Style 2 adds levels of indentation, ergo, it is discouraged.

    Personally, I like style 1 as well. Style 2 makes it harder to match up closing braces in functions that have several guard tests.

提交回复
热议问题