unnecessary_this: shadowing을 피할 때가 아니라면 this로 접근하지 마세요

unnecessary_this: shadowing을 피할 때가 아니라면 this로 접근하지 마세요

unnecessary_this는 그림자(shadowing)를 피할 필요가 없을 때 this로 멤버에 접근하지 말라고 알려주는 린트(lint) 규칙이에요. Effective Dart 스타일 가이드와 같은 방향으로 코드를 정리해 줘요.

출처: Don't access members with this unless avoiding shadowing.

본문

상세 설명

Effective Dart의 권장에 따라, shadowing을 피할 필요가 없을 때는 this를 쓰지 마세요.

BAD:

class Box {
  int value;
  void update(int newValue) {
    this.value = newValue;
  }
}

GOOD:

class Box {
  int value;
  void update(int newValue) {
    value = newValue;
  }
}

GOOD:

class Box {
  int value;
  void update(int value) {
    this.value = value;
  }
}

마지막 예시처럼 매개변수 이름이 멤버 이름과 겹쳐서 shadowing이 일어나는 경우에는, this를 써서 멤버를 가리키는 게 맞아요.

활성화하기

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

linter:
  rules:
    - unnecessary_this

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

linter:
  rules:
    unnecessary_this: true

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

더 알아보기