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

前端 未结 12 2095
天涯浪人
天涯浪人 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:31

    Those are two lines long, so not really a single line.

    There's nothing wrong with single line ifs when it makes the code easier to read.

    For example, something like this:

    if (last_item) print ", and " else print ", "
    

    is much better than

    if (last_iem)
    {
        print ", and "
    }
    else
    {
        print ", "
    }
    
    0 讨论(0)
  • 2021-01-01 17:39

    Generally non-readable code is a bad practice. The single line is more efficient in your typing and saves line numbers but come back to it a year from now or while you're scanning for bugs and it'll make it more difficult.

    In my opinion, yes it's bad practice to have single line if statements.

    The computer doesn't really care (as far as I can tell) but you should always write your code like it's going to be maintained by a serial killer that knows where you live.

    Readable! Easily self-discernable.

    0 讨论(0)
  • 2021-01-01 17:39

    I have seen so many third party code with silly issues, that I prefer to use braces all the time. That said I have never felt good on

    if(){}
    else (){}
    

    I use if(){} on the same line when it is a short instruction and it is alone. If there is an else use the long:

    if(checkSomething)
    {
       //dosomething
    }
    else
    {
       //doanotherthing
    }
    
    0 讨论(0)
  • 2021-01-01 17:40

    The problem I've seen is developers not recognizing the {}-less-if when they add code to one of the conditions. Example:

    //before
    if(something)
        statement;
    
    //after
    if(something)
        statement;
        addedstatement;
    

    Obviously, this won't do what they expect.

    0 讨论(0)
  • 2021-01-01 17:42

    Have you ever seen code like this in C or C++?

        /*  Warning:  bogus C code!  */
    
    if (some condition)
            if (another condition)
                    do_something(fancy);
    else
            this_sucks(badluck);
    

    Either the indentation is wrong, or the program is buggy, because an "else" always applies to the nearest "if", unless you use braces.

    (Let's just use python. No brackets, just pure clean whitespaces. :P)

    0 讨论(0)
  • 2021-01-01 17:47

    One major benefit of using multiple lines is ease of debugging. If you have an if else statement all on one line and the debugger tells you that line x blew up, it's more difficult to determine which part of the statement failed. Multiple lines also makes it easier to step through your code using a debugger.

    0 讨论(0)
提交回复
热议问题