Mandatory use of braces

前端 未结 21 2316
旧时难觅i
旧时难觅i 2021-02-12 23:26

As part of a code standards document I wrote awhile back, I enforce \"you must always use braces for loops and/or conditional code blocks, even (especially) if they\'re only one

21条回答
  •  一整个雨季
    2021-02-13 00:17

    Here are the unwritten (until now I suppose) rules I go by. I believe it provides readability without sacrificing correctness. It's based on a belief that the short form is in quite a few cases more readable than the long form.

    • Always use braces if any block of the if/else if/else statement has more than one line. Comments count, which means a comment anywhere in the conditional means all sections of the conditional get braces.
    • Optionally use braces when all blocks of the statement are exactly one line.
    • Never place the conditional statement on the same line as the condition. The line after the if statement is always conditionally executed.
    • If the conditional statement itself performs the necessary action, the form will be:

      for (init; term; totalCount++)
      {
          // Intentionally left blank
      }
      

    No need to standardize this in a verbose manner, when you can just say the following:

    Never leave braces out at the expense of readability. When in doubt, choose to use braces.

提交回复
热议问题