Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it wrong to use braces for variable scope purposes?
    text
    copied!<p>I sometimes use braces to isolate a block of code to avoid using by mistake a variable later. For example, when I put several <code>SqlCommand</code>s in the same method, I frequently copy-paste blocks of code, ending by mixing the names and executing twice some commands. Adding braces helps to avoid this situation, because using a wrong <code>SqlCommand</code> in a wrong place will result in an error. Here's an illustration:</p> <pre><code>Collection&lt;string&gt; existingCategories = new Collection&lt;string&gt;(); // Here a beginning of a block { SqlCommand getCategories = new SqlCommand("select Title from Movie.Category where SourceId = @sourceId", sqlConnection, sqlTransaction); getCategories.Parameters.AddWithValue("@sourceId", sourceId); using (SqlDataReader categoriesReader = getCategories.ExecuteReader(System.Data.CommandBehavior.SingleResult)) { while (categoriesReader.Read()) { existingCategories.Add(categoriesReader["Title"].ToString()); } } } if (!existingCategories.Contains(newCategory)) { SqlCommand addCategory = new SqlCommand("insert into Movie.Category (SourceId, Title) values (@sourceId, @title)", sqlConnection, sqlTransaction); // Now try to make a mistake and write/copy-paste getCategories instead of addCategory. It will not compile. addCategory.Parameters.AddWithValue("@sourceId", sourceId); addCategory.Parameters.AddWithValue("@title", newCategory); addCategory.ExecuteNonQuery(); } </code></pre> <p>Now, StyleCop displays a warning every time a block follows an empty line. On the other hand, not putting an empty line would make the code much harder to understand.</p> <pre><code>// Something like: Collection&lt;string&gt; existingCategories = new Collection&lt;string&gt;(); { // Code here } // can be understood as (is it easy to notice that semicolon is missing?): Collection&lt;string&gt; existingCategories = new Collection&lt;string&gt;() { // Code here } </code></pre> <p>So,</p> <ol> <li><p>Is there <strong>something wrong</strong> in using braces to create blocks of code just for variable scope purposes?</p></li> <li><p>If it's all right, how to make it more readable without violating StyleCop rules?</p></li> </ol>
 

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