omit_local_variable_types: 지역 변수의 타입 표기를 생략하세요

omit_local_variable_types: 지역 변수의 타입 표기를 생략하세요

작은 함수 중심으로 짜여진 현대적인 코드에서는 지역 변수의 유효 범위(scope)가 아주 짧아요. 그런데 매번 타입을 붙여 쓰면 오히려 더 중요한 변수 이름과 초기화 값이 눈에 덜 들어와요. omit_local_variable_types는 초기화된 지역 변수에 중복되는 타입 표기를 붙이지 말라고 알려주는 린트(lint) 규칙이에요.

출처: omit_local_variable_types

본문

상세 설명

초기화된 지역 변수에 중복되는 타입 표기를 붙이지 마세요. 지역 변수는 특히 함수가 작은 현대 코드에서 유효 범위가 아주 짧아요. 타입을 생략하면 독자의 시선이 더 중요한 변수 이름과 초기화 값에 머물게 돼요.

BAD:

List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
  List<List<Ingredient>> desserts = <List<Ingredient>>[];
  for (final List<Ingredient> recipe in cookbook) {
    if (pantry.containsAll(recipe)) {
      desserts.add(recipe);
    }
  }

  return desserts;
}

GOOD:

List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
  var desserts = <List<Ingredient>>[];
  for (final recipe in cookbook) {
    if (pantry.containsAll(recipe)) {
      desserts.add(recipe);
    }
  }

  return desserts;
}

다만 추론된 타입이 변수에 원하던 타입이 아닐 때도 있어요. 예를 들어 나중에 다른 타입의 값을 할당할 생각이라면, 그때는 원하는 타입을 명시해 주면 돼요.

GOOD:

Widget build(BuildContext context) {
  Widget result = Text('You won!');
  if (applyPadding) {
    result = Padding(padding: EdgeInsets.all(8.0), child: result);
  }
  return result;
}

호환되지 않는 규칙

omit_local_variable_types 린트는 다음 규칙과 호환되지 않아요:

  • always_specify_types
  • specify_nonobvious_local_variable_types

활성화하기

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

linter:
  rules:
    - omit_local_variable_types

대신 YAML map 문법으로 린터 규칙을 설정한다면, linter > rules 아래에 omit_local_variable_types: true를 추가해요.

linter:
  rules:
    omit_local_variable_types: true

참고로 이 규칙에는 자동 수정(fix)이 제공돼요.

더 알아보기