开发者

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 开发者_JS百科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?


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


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();


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.


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.


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;
}


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;


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!


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


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 !


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.


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 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;


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜