Is it a bad practice to use an if-statement withou

2019-01-01 12:50发布

I've seen code like this:

if(statement)
    do this;
else
    do this;

I don't like that, I think this is cleaner and more readable

if(statement){
    do this;
}else{
    do this;
}

Is this simply a matter of preference or would one way be recommended over the other?

15条回答
弹指情弦暗扣
2楼-- · 2019-01-01 13:48

I agree with most answers in the fact that it is better to be explicit in your code and use braces. Personally I would adopt a set of coding standards and ensure that everyone on the team knows them and conforms. Where I work we use coding standards published by IDesign.net for .NET projects.

查看更多
几人难应
3楼-- · 2019-01-01 13:52

My general pattern is that if it fits on one line, I'll do:

if(true) do_something();

If there's an else clause, or if the code I want to execute on true is of significant length, braces all the way:

if(true) {
    do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}

if(false) {
    do_something();
} else {
    do_something_else();
}

Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.

查看更多
呛了眼睛熬了心
4楼-- · 2019-01-01 13:53

Having the braces right from the first moment should help to prevent you from ever having to debug this:

if (statement)
     do this;
else
     do this;
     do that;
查看更多
登录 后发表回答