为什么省略花括号被认为是一种不好的做法? [英] Why is it considered a bad practice to omit curly braces?
问题描述
为什么每个人都告诉我写这样的代码是不好的做法?
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);
我对省略花括号的最大论据是,有时它们的行数可能是其两倍.例如,这里有一些代码可以在 C# 中为标签绘制发光效果.
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));
您还可以获得将 usings
链接在一起的额外好处,而无需缩进一百万次.
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
}
<小时>
大括号最常见的论点围绕着维护编程,以及在原始 if 语句与其预期结果之间插入代码所带来的问题:
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();
<小时>
问题:
- 想要使用该语言提供的更紧凑的语法是错误的吗?设计这些语言的人很聪明,我无法想象他们会添加一个总是不好用的功能.
- 我们是否应该或不应该编写代码,以便最低公分母可以理解并且可以毫无问题地使用它?
- 还有其他我遗漏的论点吗?
推荐答案
实际上,唯一真正让我痛心的是在调试时,并注释掉了 bar():
Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():
if(foo)
// bar();
doSomethingElse();
除此之外,我倾向于使用:
Other than that, I tend to use:
if(foo) bar();
处理上述情况.
编辑感谢您澄清问题,我同意,我们不应该将代码编写为最小公分母.
EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.
这篇关于为什么省略花括号被认为是一种不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!