【发布时间】:2010-09-26 11:04:01
【问题描述】:
为什么每个人都告诉我这样写代码是一种不好的做法?
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();
问题:
- 想要使用该语言提供的更紧凑的语法是错误的吗?设计这些语言的人很聪明,我无法想象他们会推出一个总是不好用的功能。
- 我们应该还是不应该编写代码,以便最低公分母能够理解并且使用它没有问题?
- 我还缺少另一个论点吗?
【问题讨论】:
-
我同意你的看法。省略它们。期间。
-
谁在乎它在 2010 年有多少行。显示器宽且便宜且分辨率高!我的显示器是 2048 X 1152,我有两个!当您很容易引入难以发现的细微错误时,可读性比节省 2 条垂直线更重要。
-
显示器宽且便宜,但它们并不高且便宜。垂直空间比水平空间更稀缺。
-
@AdamRuth 把它们转过来 :)
-
所以你不会像 Apple 那样被 2014 年 2 月发现的 SSL 错误搞砸了,哈哈。
标签: java c# c++ c coding-style