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

前端 未结 12 2196
天涯浪人
天涯浪人 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 something that I actually remember from an employment exam a while back. The code was similar to the following:

    if (x == 0)
        x = 2;
    else
        print("x is: %d", x); // debugging!
        x = 4;
    

    Most people here can spot the error, but you can really substitute in anything you want as the "bad code" that was inserted. The more subtle error comes when you have an "old version" of something commented out, and somebody un-comments it, and suddenly the second statement is outside the block.

    Basically, unless it's a small test application to learn a concept fast, I always bracket (and even in the test apps I usually bracket). It just isn't worth the headache later if I don't, even in 5-line-methods.

提交回复
热议问题