Are singleline if statements or if statements without braces bad practice?

前端 未结 12 2094
天涯浪人
天涯浪人 2021-01-01 17:10
if (condition) { /* do something */ }
else { /* do something */ }

if (condition)
    /* do something */
else
    /* do something */

I was told tha

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 17:29

    This is more coding style than anything else. That said, my personal opinion is that your second example is potentially quite harmful. It's easy enough to accidentally "add a second line to the block" in languages where braces are the only way to create blocks. But in PHP, where an alternate syntax exists, this is even less likely to set off the necessary warning bells:

    if ($_GET["asdf"]==1):
        /* do something */
    else:
        /* do something */
    endif;
    

    Rule of thumb: if you're going to put your "do something" on a separate line, use braces; if you're not going to use braces, put it on the same line!

提交回复
热议问题