avoid_equals_and_hash_code_on_mutable_classes 규칙: @immutable이 아닌 클래스에서 ==와 hashCode 오버로딩 피하기

avoid_equals_and_hash_code_on_mutable_classes 규칙: @immutable이 아닌 클래스에서 ==와 hashCode 오버로딩 피하기

avoid_equals_and_hash_code_on_mutable_classes@immutable로 표시되지 않은 클래스에서 operator ==hashCode를 오버로딩하지 말라고 알려주는 린트(lint) 규칙이에요. 변경 가능한(mutable) 클래스에서 이 둘을 오버로딩하면 컬렉션에서 예측할 수 없는 바람직하지 않은 동작이 생길 수 있어요.

출처: avoid_equals_and_hash_code_on_mutable_classes

본문

설명

Effective Dart에서 가져온 규칙이에요.

AVOID: @immutable로 표시되지 않은 클래스에서 operator ==hashCode를 오버로딩하지 마세요.

클래스가 불변(immutable)이 아니라면, operator ==hashCode를 오버로딩했을 때 컬렉션에서 사용될 때 예측할 수 없고 바람직하지 않은 동작이 생길 수 있어요.

BAD:

class B {
  String key;
  const B(this.key);
  @override
  operator ==(other) => other is B && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

GOOD:

@immutable
class A {
  final String key;
  const A(this.key);
  @override
  operator ==(other) => other is A && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

NOTE: 이 린트는 @immutable 애너테이션의 사용을 검사해요. 그래서 클래스가 실제로는 변경 가능하지 않아도 경고가 발생할 수 있어요. 그래서 이런 코드도 경고 대상이 돼요.

BAD:

class C {
  final String key;
  const C(this.key);
  @override
  operator ==(other) => other is C && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

활성화

avoid_equals_and_hash_code_on_mutable_classes 규칙을 활성화하려면 analysis_options.yaml 파일의 linter > rulesavoid_equals_and_hash_code_on_mutable_classes를 추가해요.

linter:
  rules:
    - avoid_equals_and_hash_code_on_mutable_classes

YAML map 문법으로 린터 규칙을 설정한다면 linter > rulesavoid_equals_and_hash_code_on_mutable_classes: true를 추가해요.

linter:
  rules:
    avoid_equals_and_hash_code_on_mutable_classes: true

더 알아보기