As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center提供指导。




已关闭8年。




为什么每个人都告诉我编写这样的代码是一种不好的做法?
if (foo)
    Bar();

//or

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

关于省略花括号的最大论据是,有时花括号可能是花括号的两倍。例如,以下代码为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));

您还可以获得将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
}

花括号的最常见参数涉及维护编程,以及在原始if语句及其预期结果之间插入代码会引起的问题:
if (foo)
    Bar();
    Biz();

问题:
  • 是否要使用该语言提供的更紧凑的语法是错误的吗?设计这些语言的人很聪明,我无法想象他们会放一个总是很难使用的功能。
  • 我们应该还是不应该编写代码,以便最低的公分母可以理解并且使用它时没有问题?
  • 还有我缺少的论点吗?
  • 最佳答案

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

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

    除此之外,我倾向于使用:
    if(foo) bar();
    

    可以解决上述情况。

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

    10-05 18:12