가끔 변수를 잘못 사용하는 것을 피하기 위해 코드 블록을 분리하기 위해 중괄호를 사용하기도합니다. 예를 들어, 동일한 메소드에 여러 개의 SqlCommand
을 넣으면 자주 코드 블록을 복사하여 붙이며 이름을 혼합하고 두 번 명령을 실행합니다. 잘못된 위치에 잘못된 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
}
그래서,
있습니까?
괜찮 으면 StyleCop 규칙을 위반하지 않고 가독성을 높이려면 어떻게해야합니까?
이러한 것을 익명 블록이라고합니다. 관련 항목 : http://stackoverflow.com/questions/85282/what-is-the-value-of-an-anonymous-unattached-block-in-c 및 http://stackoverflow.com/questions/500006/what- 익명 -blocks-in-c-style-languages 언어 –