我有时使用大括号来隔离代码块,以避免以后错误地使用变量。例如,当我SqlCommand
在同一个方法中放置多个 s 时,我经常复制粘贴代码块,最后混合名称并执行两次某些命令。添加大括号有助于避免这种情况,因为SqlCommand
在错误的地方使用错误会导致错误。这是一个插图:
Collection<string> existingCategories = new Collection<string>();
// 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();
}
现在,StyleCop 会在每次块跟随空行时显示警告。另一方面,不放空行会使代码更难理解。
// Something like:
Collection<string> existingCategories = new Collection<string>();
{
// Code here
}
// can be understood as (is it easy to notice that semicolon is missing?):
Collection<string> existingCategories = new Collection<string>()
{
// Code here
}
所以,
仅出于可变范围的目的使用大括号创建代码块有什么问题吗?
If it's all right, how to make it more readable without violating StyleCop rules?