ChatGPT解决这个技术问题 Extra ChatGPT

Is it a bad practice to use an if-statement without curly braces? [closed]

Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 7 years ago. Improve this question

I've seen code like this:

if(statement)
    do this;
else
    do this;

However, I think this is more readable:

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

Since both methods work, is this simply a matter of preference which to use or would one way be recommended over the other?

In my opinion it's bad, because you start relying on whitespace indentation which is almost never fully consistent. It derails the reader's train of thought when they have to worry about such things.
It's a good practice to use it > blog.codecentric.de/en/2014/02/curly-braces

c
clee

The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.

Maintainability-wise, it's always smarter to use the second form.

EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html


And you should always code for maintainability. After all, I'm pretty sure the compiler doesn't care which form you use. Your coworkers, however may be pist if you introduce a bug because of a silly curly brace error.
Or you could use a language that doesn't use brackets for code blocks...
@lins314159 - No, I mean like python. Because I'm chauvinistic in this regard.
Further proof mistakes can (and do) happen: imperialviolet.org/2014/02/22/applebug.html
Claiming that the SSL bug is an argument in favor of braces is disingenuous. It is not as if the developer intended to write if (…) { goto L; goto L; } but forgot the braces. It is purely coincidental that ``if (…) { goto L; goto L; }` happens not to be a security bug, because it is still a bug (just not one with security consequences). On another example, things could go in the opposite direction and the braceless code could be accidentally safe. On a third example, the braceless code would be bug-free initially and the developer would introduce a typo while adding the braces.
d
doynax

One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:

if(one)
    if(two)
        foo();
    else
        bar();

From this:

if(one)
    if(two)
        foo();
else
    bar();

This is a far more serious problem than the one mentioned in the top answer (adding a second statement).
indeed, this answer actually took me from reading these answers cynically to being mildly concerned i may have actually made this mistake.
If anyone else was wondering like I was which way C actually interprets it, a test I did with GCC interprets this code in the first way. tpcg.io/NIYeqx
"ambiguity" is the wrong term. There is no ambiguity whatsoever in how the parser will see this: the else binds greedily to the nearest, innermost if. The problem arises where C or similar languages are being coded by people who don't know this, don't think about it, or didn't have enough coffee yet - so they write code that they think will do one thing, but the language spec says the parser has to do something else, which might be very different. And yes, that's another rock-solid argument in favour of always including braces even if the grammar flags them as theoretically 'unnecessary'.
From what I have seen (the "dangling else problem") the human-readable grammar is ambiguous, but either the parser defaults to the mentioned option, or the grammar is rewritten to be less readable, but unambiguous.
M
Matchu

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.


Although, as easy as it is to write if(true){ do_something(); }, why take the chance on having another programmer introduce a serious bug down the road (lookup Apple's "goto fail" total ssl code screwup).
No amount of brackets will free the maintainer from using his brain. I support the idea of "no brackets if it fits in one line" because, well, for me such an if is just a version of the ternary if operator where one doesn't need to do anything in the "after :" part of ternary. And why would anyone introduce brackets to ternary if?
I don't agree at all that ultimately it is subjective, nor that it only affects style and readability. As someone who has wasted time trying to debug issues that it turned out were caused by missing block delimiters (and not noticing their absence), because I had to use a coding style that omits them when 'unnecessary' - and who has read about numerous terrible bugs very arguably caused by such coding styles - I think this is a very objective, practical issue. Sure, with a style mandating delimiters, we can still forget them, but surely - at least - muscle memory makes us far less likely to.
Just wait until a prettifier is applied and your 1-liner is a 2-liner. Just use the braces.
M
Marcus Harrison

The "rule" I follow is this:

If the "if" statement is testing in order to do something (I.E. call functions, configure variables etc.), use braces.

if($test)
{
    doSomething();
}

This is because I feel you need to make it clear what functions are being called and where the flow of the program is going, under what conditions. Having the programmer understand exactly what functions are called and what variables are set in this condition is important to helping them understand exactly what your program is doing.

If the "if" statement is testing in order to stop doing something (I.E. flow control within a loop or function), use a single line.

if($test) continue;
if($test) break;
if($test) return;

In this case, what's important to the programmer is discovering quickly what the exceptional cases are where you don't want the code to run, and that is all coverred in $test, not in the execution block.


P
Pentium10

I am using the code formatter of the IDE I use. That might differ, but it can be setup in the Preferences/Options.

I like this one:

if (statement)
{
    // comment to denote in words the case
    do this;
    // keep this block simple, if more than 10-15 lines needed, I add a function for it
}
else
{
    do this;
}

This being an entirely subjective style issue, I personally don't like the redundancy of the brace-only lines. But hey.
I support this style. Most people read code from left to right and it sort of makes our eyes anchored to left edge of screen. It helps to visually separate and extract code to logical blocks of steps.
I've always preferred this style. Much easier to find the corresponding closing parenthesis. So it takes a lot of space ? Use a smaller font.
I always find it easier to "scan" through code when the braces are on separate lines. That goes for everything; classes, methods, if- and while-statements, et cetera. Never liked having that first brace on the same line...
Whitespace is cheap, especially when you have a code folding capable IDE.
M
Matt Bishop

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;

That seems to be the accepted rationale, but (to play devil's advocate here) wouldn't a single additional syntax-highlighting rule also solve this, while saving one line?
So will having an IDE that corrects the indentation when you hit ; :)
Why would a programmer who knows C don't notice, that there is no } after the second do that? The missing brace would trigger me immediately. Only a Python dev could fall for this one. If code in C is intended with no sign of new scope, it is not forming a new scope, it is usually used to signal a continuation of the line above, even if that line above is else.
l
leepowers

Use braces for all if statements even the simple ones. Or, rewrite a simple if statement to use the ternary operator:

if (someFlag) {
 someVar= 'someVal1';
} else {
 someVar= 'someVal2';
}

Looks much nicer like this:

someVar= someFlag ? 'someVal1' : 'someVal2';

But only use the ternary operator if you are absolutely sure there's nothing else that needs to go in the if/else blocks!


C
Community

I prefer using braces. Adding braces makes it easier to read and modify.

Here are some links for the use of braces:

Prefer Multiline if

Omitting Braces: Not Just A Matter Of Style

Stack Overflow


t
thomas.g

From my experience the only (very) slight advantage of the first form is code readability, the second form adds "noise".

But with modern IDEs and code autogeneration (or autocompletion) I strongly recommend using the second form, you won't spend extra time typing curly braces and you'll avoid some of the most frequent bugs.

There are enough energy consuming bugs, people just shoudn't open doors for big wastes of time.

One of the most important rule to remember when writing code is consistency. Every line of code should be written the same way, no matter who wrote it. Being rigorous prevents bugs from "happening" ;)

This is the same with naming clearly & explicitly your variables, methods, files or with correctly indenting them...

When my students accept this fact, they stop fighting against their own sourcecode and they start to see coding as a really interesting, stimulating and creative activity. They challenge their minds, not their nerves !


N
Nate Heinrich

Personally I use the first style only throw an exception or return from a method prematurely. Like argument Checking at the beginning of a function, because in these cases, rarely do I have have more than one thing to do, and there is never an else.

Example:

if (argument == null)
    throw new ArgumentNullException("argument");

if (argument < 0)
    return false;

Otherwise I use the second style.


G
Grant Paul

It is a matter of preference. I personally use both styles, if I am reasonably sure that I won't need to add anymore statements, I use the first style, but if that is possible, I use the second. Since you cannot add anymore statements to the first style, I have heard some people recommend against using it. However, the second method does incur an additional line of code and if you (or your project) uses this kind of coding style, the first method is very much preferred for simple if statements:

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

However, I think the best solution to this problem is in Python. With the whitespace-based block structure, you don't have two different methods of creating an if statement: you only have one:

if statement:
    do this
else:
    do this

While that does have the "issue" that you can't use the braces at all, you do gain the benefit that it is no more lines that the first style and it has the power to add more statements.


I by myself think the way how Python handles if-else statements is very ugly, but then again, I'm no Python programmer (yet)
J
Joe

I have always tried to make my code standard and look as close to the same as possible. This makes it easier for others to read it when they are in charge of updating it. If you do your first example and add a line to it in the middle it will fail.

Won't work:

if(statement) do this; and this; else do this;


S
Simon

My personal preference is using a mixture of whitespace and brackets like this:

if( statement ) {

    // let's do this

} else {

    // well that sucks

}

I think this looks clean and makes my code very easy to read and most importantly - debug.


K
Kane

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.


f
fastcodejava

I prefer putting a curly brace. But sometimes, ternary operator helps.

In stead of :

int x = 0;
if (condition) {
    x = 30;
} else {
    x = 10;
}

One should simply do : int x = condition ? 30 : 20;

Also imagine a case :

if (condition)
    x = 30;
else if (condition1)
    x = 10;
else if (condition2)
    x = 20;

It would be much better if you put the curly brace in.