C# 为什么省略花括号被认为是一种不好的做法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/359732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:29:18  来源:igfitidea点击:

Why is it considered a bad practice to omit curly braces?

javac#c++ccoding-style

提问by Bob

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#.

我省略大括号的最大论据是,有时它们的行数可能是其两倍。例如,这里有一些代码可以在 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 usingstogether without having to indent a million times.

您还可以获得链接usings在一起的额外好处,而无需缩进一百万次。

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 语句与其预期结果之间插入代码所带来的问题:

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?
  1. 想要使用该语言提供的更紧凑的语法是错误的吗?设计这些语言的人很聪明,我无法想象他们会添加一个总是不好使用的功能。
  2. 我们应该还是不应该编写代码,以便最低公分母可以理解并且使用它没有问题?
  3. 还有另一个我想念的论点吗?

采纳答案by Zachary Yates

Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():

实际上,唯一一次真正让我感到困扰的是我在调试时并注释掉了 bar():

if(foo)
  // bar();
doSomethingElse();

Other than that, I tend to use:

除此之外,我倾向于使用:

if(foo) bar();

Which takes care of the above case.

它处理上述情况。

EDITThanks for clarifying the question, I agree, we should not write code to the lowest common denominator.

编辑感谢您澄清问题,我同意,我们不应该将代码编写为最小公分母。

回答by Elie

Let's say you have some code:

假设您有一些代码:

if (foo)
    bar();

and then someone else comes along and adds:

然后其他人出现并补充说:

if (foo)
    snafu();
    bar();

According to the way it's written, bar(); is now executed unconditionally. By including the curly braces, you prevent this kind of accidental error. Code should be written in such a way as to make such mistakes difficult or impossible to make. If I was doing a code review and saw the missing braces, especially spread across multiple lines, I would create a defect. In cases where it is justified, keep it on one line so that the chance of making such an error is again kept to a minimum.

根据它的写法, bar(); 现在无条件执行。通过包含花括号,可以防止这种意外错误。代码的编写方式应该使此类错误难以或不可能发生。如果我在进行代码审查并看到缺少​​的大括号,特别是分散在多行中,我会创建一个缺陷。在合理的情况下,将其保留在一行上,以便再次将发生此类错误的机会降至最低。

回答by George Stocker

Your maintanence programmer may forget to add curly braces later if he/she adds logic to the app. So the following happens:

如果您的维护程序员向应用程序添加逻辑,他/她可能会忘记添加花括号。所以会发生以下情况:

if(foo)
bar();
bar(delete);

Instead of

代替

if(foo) {
bar();
}
 bar(delete);

回答by Tom Ritter

There are always exceptions, but I would argue against omitting braces only when it's in one of the forms:

总有例外,但我反对仅在以下形式之一时省略大括号:

if(x == y)
   for(/* loop */)
   {
      //200 lines
   }

//rampion's example:
for(/* loop */)
{
   for(/* loop */)
      for(/* loop */)
      {
         //several lines
      }
}
if(x == y)
   for(/* loop */)
   {
      //200 lines
   }

//rampion's example:
for(/* loop */)
{
   for(/* loop */)
      for(/* loop */)
      {
         //several lines
      }
}

Otherwise, I have no problem with it.

否则,我没有问题。

回答by Jon Skeet

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).

我偶尔会使用最底层的代码(多个 using 语句),但除此之外我总是把大括号放在里面。我只是发现它使代码更清晰。从不仅仅是缩进可以明显看出语句是块的一部分(因此可能是 if 等的一部分)。

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.)

虫子咬我(或者更确切地说是“我和同事”——我实际上并没有介绍这个虫子)一次。尽管我们当时的编码标准建议在任何地方使用大括号,但事实并非如此。我花了很长时间才发现——因为你看到了你想看到的。(这是大约 10 年前。也许我现在会更快找到它。)

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.)

当然,如果你使用“行尾大括号”,它会减少产生的额外行,但我个人不喜欢这种风格。(我在工作中使用它,发现它没有我预期的那么令人不快,但它仍然有点令人不快。)

回答by joshperry

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

大多数情况下,它是根深蒂固的编码标准,无论是对于公司还是 FOSS 项目。

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.

另外,想象一下有人每天不止一次在 Python 和 Cish 语言之间切换......在 Python 中,缩进是语言块语义的一部分,很容易犯像你引用的那样的错误。

回答by rampion

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, if, what have you have you)和语句结尾的分离。

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
}

回答by chills42

I agree that "if you are smart enough to get someone to pay you to write code, you should be smart enough to not rely solely on indentation to see the flow of the code."

我同意“如果你足够聪明,可以让某人付钱给你写代码,你应该足够聪明,不要仅仅依靠缩进来查看代码的流程。”

However... mistakes can be made, and this one is a pain to debug... especially if you're coming in looking at someone else's code.

但是……错误是可能发生的,而这个错误很难调试……尤其是当您查看其他人的代码时。

回答by Treb

It is a tradeof, shorter code (better readable) versus more secure code (less error prone).

这是一种权衡,更短的代码(更好的可读性)与更安全的代码(更不容易出错)。

My 2 cents:

我的 2 美分:

  1. There is a reason for this rule. It has been developed by countless programmers through long working hours, stretching into the night or next morning, trying to fix a bug that was caused by a little oversight.
  2. You have t decide for yourself if the tradeof is worth it.
  3. In my experience it is, I am one of those countless programmers who was working into the night to find the cause for a nasty bug. The cause was me being lazy.
  1. 这条规则是有原因的。它由无数程序员通过长时间的工作开发,一直持续到晚上或第二天早上,试图修复由一个小小的疏忽引起的错误。
  2. 您不必自己决定权衡是否值得。
  3. 根据我的经验,我是无数程序员中的一员,他们一直工作到深夜,以寻找令人讨厌的错误的原因。原因是我懒。

回答by Nathan Prather

in order to keep the code with braces from taking up lots of space, I use the technique recommended in the book Code Complete:

为了不让带大括号的代码占用大量空间,我使用了Code Complete一书中推荐的技术:

if (...) {
    foo();
    bar();
}
else {
    ...
}