为什么省略花括号被认为是一种不好的做法?为什么每个人都告诉我写这样的代码是一种糟糕的做法?if (foo)
Bar();//orfor(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));
}
}
}
//versususing (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
}
}
}//versususing (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();问题:想要使用语言提供的更简洁的语法是错误的吗?设计这些语言的人都很聪明,我无法想象他们会提供一个总是不好使用的特性。我们应该还是不应该编写代码,这样最低的公分母才能理解,并且不存在使用它的问题?我错过了另一个争论吗?
添加回答
举报
0/150
提交
取消