no_self_assignments 린트: 변수를 자기 자신에게 할당하지 말기

no_self_assignments 린트: 변수를 자기 자신에게 할당하지 말기

변수를 자기 자신에게 할당하는 실수를 잡아주는 린트(lint) 규칙이에요. 이런 할당은 보통 오타나 실수로 생긴 경우가 많아서, 제거하거나 올바른 대상을 가리키도록 고쳐 주라는 규칙이랍니다.

출처: no_self_assignments

본문

설명

변수를 자기 자신에게 할당하지 마세요. 보통 이것은 실수인 경우가 많아요.

BAD:

class C {
  int x;

  C(int x) {
    x = x;
  }
}

GOOD (생성자 초기화 목록 사용):

class C {
  int x;

  C(int x) : x = x;
}

GOOD (this.x 사용):

class C {
  int x;

  C(int x) {
    this.x = x;
  }
}

BAD (setter 안에서 자기 자신 할당):

class C {
  int _x = 5;

  int get x => _x;

  set x(int x) {
    _x = x;
    _customUpdateLogic();
  }

  void _customUpdateLogic() {
    print('updated');
  }

  void example() {
    x = x;
  }
}

GOOD:

class C {
  int _x = 5;

  int get x => _x;

  set x(int x) {
    _x = x;
    _customUpdateLogic();
  }

  void _customUpdateLogic() {
    print('updated');
  }

  void example() {
    _customUpdateLogic();
  }
}

BAD (다른 객체의 값을 쓰려다 자기 자신을 쓴 경우):

class C {
  int x = 5;

  void update(C other) {
    this.x = this.x;
  }
}

GOOD:

class C {
  int x = 5;

  void update(C other) {
    this.x = other.x;
  }
}

this.x = this.x처럼 다른 객체 other의 값을 써야 하는데 실수로 자기 자신을 가리킨 경우도 잡아줘요. 셋터(setter)의 부수 효과를 일으키려는 게 아니라면, 그냥 필요한 로직을 직접 호출하는 게 더 명확해요.

활성화 방법

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

analysis_options.yaml:

linter:
  rules:
    - no_self_assignments

대신 YAML 맵 문법으로 린트 규칙을 설정한다면, linter > rules 아래에 no_self_assignments: true라고 적어요.

analysis_options.yaml:

linter:
  rules:
    no_self_assignments: true

더 알아보기