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#.
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 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 }
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();
Questions:
- 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.
- Should we or Shouldn’t we write code so the lowest common denominator can understand and have no problems working with it?
- Is there another argument that I’m missing?
Actually, the only time that’s ever really bit me was when I was debugging, and commented out bar():
Other than that, I tend to use:
Which takes care of the above case.
EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.