Mandatory use of braces

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

    Depending on the language, having braces for a single lined conditional statement or loop statement is not mandatory. In fact, I would remove them to have fewer lines of code.

    C++:

    Version 1:

    class InvalidOperation{};
    
    //...
    Divide(10, 0);
    //...
    Divide(int a, in b)
    {
       if(b == 0 ) throw InvalidOperation();
       return a/b;
    }
    

    Version 2:

    class InvalidOperation{};
    
    //...
    Divide(10, 0);
    //...
    Divide(int a, in b)
    {
       if(b == 0 )
       { 
          throw InvalidOperation();
       }
       return a/b;
    }
    

    C#:

    Version 1:

    foreach(string s in myList)
       Console.WriteLine(s);
    

    Version2:

    foreach(string s in myList)
    {
       Console.WriteLine(s);
    }
    

    Depending on your perspective, version 1 or version 2 will be more readable. The answer is rather subjective.

提交回复
热议问题