Mandatory use of braces

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

    Another advantage of always using braces is that it makes search-and-replace and similar automated operations easier.

    For example: Suppose I notice that functionB is usually called immediately after functionA, with a similar pattern of arguments, and so I want to refactor that duplicated code into a new combined_function. A regex could easily handle this refactoring if you don't have a powerful enough refactoring tool (^\s+functionA.*?;\n\s+functionB.*?;) but, without braces, a simple regex approach could fail:

    if (x)
      functionA(x);
    else
      functionA(y);
    functionB();
    

    would become

    if (x)
      functionA(x);
    else
      combined_function(y);
    

    More complicated regexes would work in this particular case, but I've found it very handy to be able to use regex-based search-and-replace, one-off Perl scripts, and similar automated code maintenance, so I prefer a coding style that doesn't make that needlessly complicated.

提交回复
热议问题