Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is it considered a bad practice to omit curly braces?
    primarykey
    data
    text
    <p>Why does everyone tell me writing code like this is a bad practice?</p> <pre><code>if (foo) Bar(); //or for(int i = 0 i &lt; count; i++) Bar(i); </code></pre> <p>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#.</p> <pre><code>using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor))) { for (int x = 0; x &lt;= GlowAmount; x++) { for (int y = 0; y &lt;= 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 &lt;= GlowAmount; x++) for (int y = 0; y &lt;= GlowAmount; y++) g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y)); </code></pre> <p>You can also get the added benefit of chaining <code>usings</code> together without having to indent a million times.</p> <pre><code>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 } </code></pre> <hr> <p>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:</p> <pre><code>if (foo) Bar(); Biz(); </code></pre> <hr> <h3>Questions:</h3> <ol> <li>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.</li> <li>Should we or Shouldn't we write code so the lowest common denominator can understand and have no problems working with it? </li> <li>Is there another argument that I'm missing?</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload