Why is it considered a bad practice to omit curly

2018-12-31 04:49发布

Why does everyone tell me writing code like this is a bad practice?

if (foo)
    Bar();

//or

for(int i = 0 i < count; i++)
    Bar(i);

My biggest argument for omitting the curly braces is that it can sometimes be twice as many lines with them. For example, here is some code to paint a glow effect for a label in C#.

using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
{
    for (int x = 0; x <= GlowAmount; x++)
    {
        for (int y = 0; y <= GlowAmount; y++)
        {
            g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
        }
     }
 }
 //versus
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
    for (int x = 0; x <= GlowAmount; x++)
        for (int y = 0; y <= GlowAmount; y++)
            g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));

You can also get the added benefit of chaining usings together without having to indent a million times.

using (Graphics g = Graphics.FromImage(bmp))
{
    using (Brush brush = new SolidBrush(backgroundColor))
    {
        using (Pen pen = new Pen(Color.FromArgb(penColor)))
        {
            //do lots of work
        }
    }
 }
//versus
using (Graphics g = Graphics.FromImage(bmp))
using (Brush brush = new SolidBrush(backgroundColor))
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
    //do lots of work
}

The most common argument for curly braces revolves around maintance programming, and the problems that would ensue by inserting code between the original if statement and its intended result:

if (foo)
    Bar();
    Biz();

Questions:

  1. Is it wrong to want to use the more compact syntax which the language offers? The people that design these languages are smart, I can't imagine they would put a feature which is always bad to use.
  2. Should we or Shouldn't we write code so the lowest common denominator can understand and have no problems working with it?
  3. Is there another argument that I'm missing?

30条回答
流年柔荑漫光年
2楼-- · 2018-12-31 05:43

I occasionally use the very bottom code (multiple using statements), but other than that I always put the braces in. I just find it makes the code clearer. It's blatantly obvious from more than just indentation that a statement is part of a block (and thus probably part of an if etc).

I have seen the

if (...)
    foo();
    bar();

bug bite me (or rather "me and colleagues" - I didn't actually introduce the bug) once. This was despite the fact that our coding standards at the time recommended using braces everywhere. It took me a surprisingly long time to spot - because you see what you want to see. (This was about 10 years ago. Maybe I'd find it faster now.)

Of course if you use "brace at the end of the line" it reduces the extra lines incurred, but I personally dislike that style anyway. (I use it at work, and have found it less unpleasant than I expected, but it's still a bit unpleasant.)

查看更多
梦醉为红颜
3楼-- · 2018-12-31 05:44

Most times it is ingrained as a coding standard, whether for a company or an FOSS project.

Ultimately someone else will need to grok your code and it is a major time drain for each developer to have to figure out the specific style of the section of code they are working on.

Also, imagine that someone is going between Python and a Cish language more than once a day... In Python indenting is part of the block symantics of the language and it would be quite easy to make a mistake like the one you quote.

查看更多
笑指拈花
4楼-- · 2018-12-31 05:44

I always omit them when appropriate, such as in your first example. Clean, concise code I can see and understand by glancing at is easier to maintain, debug and understand than code I have to scroll through and read line by line. I think most programmers will agree with this.

It is easy for it to get out of hand if you start doing multiple nesting, if/else clauses and so on, but I think most programmers should be able to tell where to draw the line.

I see it kind of like the argument for if ( foo == 0 ) vs if ( 0 == foo ). The latter may prevent bugs for new programmers (and maybe even occasionally for veterans), while the former is easier to quickly read and understand when you're maintaining code.

查看更多
浮光初槿花落
5楼-- · 2018-12-31 05:45

One of the main issues is when you have regions of one-liners and non-one liners, along with separation from the control statment (for, if, what have you) and the end of the statment.

For example:

for (...)
{
  for (...)
    for (...) 
    {
      // a couple pages of code
    }
  // which for block is ending here?  A good text editor will tell you, 
  // but it's not obvious when you're reading the code
}
查看更多
爱死公子算了
6楼-- · 2018-12-31 05:47

Out of the three conventions:

if(addCurleyBraces()) bugFreeSofware.hooray();

and:

if(addCurleyBraces())
    bugFreeSofware.hooray();

and (which represent any indentation style using an opening and a closing brace):

if(addCurleyBraces()) {
    bugFreeSofware.hooray();
}

I prefer the last one as:

  • I find it easier to read if all the if-statements are written in a uniform way.
  • It may make the software a tiny bit more robust and bug free. However all modern IDE's and advanced text editors have nice auto-indenting features which I think everyone should use as long as it doesn't mess up comment formatting or go against team standards (in a lot of cases it's possible to create a custom formatting scheme and share it with the team). My point here is that if indentation is done correctly risk of bug introduction is reduced a bit.
  • I prefer the boolean expression and statement(s) to execute to be on different lines. I like to be able to mark a row for debugging purposes. Even if I'm using an IDE where I may mark a statement and step to it, it's an interactive operation and I might forget where I started to debug or at least it will take me a little bit more time to step through the code several times (as I have to mark the position manually each time during debugging).
查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 05:48

To be blunt I see it as:

Good programmers program defensively, Bad programmers don't.

Since there are several examples above and my own similar experiences with bugs related to forgetting braces then I learned the hard way to ALWAYS PUT BRACES.

Anything else is choosing personal style over safety and that's clearly bad programming.

Joel even mentions this in Making Wrong Code Look Wrong

Once you get bit by a bug because of missing braces you learn that missing braces look wrong because you know it's a potential place for another bug to occur.

查看更多
登录 后发表回答