모든 흐름 제어 구조에는 중괄호를 사용해 주세요

모든 흐름 제어 구조에는 중괄호를 사용해 주세요

if, for, while 같은 흐름 제어 구조는 가능하면 항상 중괄호로 감싸 주는 게 좋아요. 중괄호가 없으면 "dangling else" 같은 혼동스러운 문제가 생길 수 있거든요. 딱 한 가지 예외만 있어요.

출처: DO use curly braces for all flow control structures

본문

모든 흐름 제어 구조에는 중괄호를 사용해 주세요.

이렇게 하면 dangling else 문제를 피할 수 있어요.

BAD:

if (overflowChars != other.overflowChars)
  return overflowChars < other.overflowChars;

GOOD:

if (isWeekDay) {
  print('Bike to work!');
} else {
  print('Go dancing or read a book!');
}

이 규칙에는 예외가 하나 있어요. 조건과 본문을 포함한 if 문 전체가 한 줄에 들어가는, else 절이 없는 if 문이라면 중괄호를 생략해도 괜찮아요.

GOOD:

if (arg == null) return defaultValue;

하지만 본문이 다음 줄로 넘어가게 된다면 중괄호를 사용해야 해요.

GOOD:

if (overflowChars != other.overflowChars) {
  return overflowChars < other.overflowChars;
}

활성화 방법

curly_braces_in_flow_control_structures 규칙을 활성화하려면 analysis_options.yaml 파일의 linter > rules 아래에 curly_braces_in_flow_control_structures를 추가하면 돼요.

linter:
  rules:
    - curly_braces_in_flow_control_structures

대신 YAML map 문법으로 린트 규칙을 설정한다면 linter > rules 아래에 curly_braces_in_flow_control_structures: true를 추가하면 돼요.

linter:
  rules:
    curly_braces_in_flow_control_structures: true

더 알아보기