Mandatory use of braces

前端 未结 21 2317
旧时难觅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:04

    Many languanges have a syntax for one liners like this (I'm thinking of perl in particular) to deal with such "ugliness". So something like:

    if (foo)     
    //bar
    else     
    //baz
    

    can be written as a ternary using the ternary operator:

    foo ? bar : baz
    

    and

    while (something is true)
    {
    blah 
    }
    

    can be written as:

    blah while(something is true)
    

    However in languages that don't have this "sugar" I would definitely include the braces. Like you said it prevents needless bugs from creeping in and makes the intention of the programmer clearer.

提交回复
热议问题