跳到主內容

避免_實現_值_型別

穩定

不要實現覆蓋 == 的類。

詳情

#

不要 實現覆蓋 == 的類。

== 運算子在契約上要求是一個等價關係;也就是說,對於所有物件 o1o2o1 == o2o2 == o1 必須要麼都為 true,要麼都為 false。

注意:Dart 沒有真正的值型別,因此我們將實現 == 的類視為標識值型別的代理

使用 implements 時,你不會繼承 == 的方法體,這使得遵循 == 的契約幾乎不可能。覆蓋 == 的類通常可以直接在測試中使用,而無需建立 mock 或 fake。例如,對於給定的類 Size

dart
class Size {
  final int inBytes;
  const Size(this.inBytes);

  @override
  bool operator ==(Object other) => other is Size && other.inBytes == inBytes;

  @override
  int get hashCode => inBytes.hashCode;
}

dart
class CustomSize implements Size {
  final int inBytes;
  const CustomSize(this.inBytes);

  int get inKilobytes => inBytes ~/ 1000;
}

dart
import 'package:test/test.dart';
import 'size.dart';

class FakeSize implements Size {
  int inBytes = 0;
}

void main() {
  test('should not throw on a size >1Kb', () {
    expect(() => someFunction(FakeSize()..inBytes = 1001), returnsNormally);
  });
}

dart
class ExtendedSize extends Size {
  ExtendedSize(int inBytes) : super(inBytes);

  int get inKilobytes => inBytes ~/ 1000;
}

dart
import 'package:test/test.dart';
import 'size.dart';

void main() {
  test('should not throw on a size >1Kb', () {
    expect(() => someFunction(Size(1001)), returnsNormally);
  });
}

啟用

#

要啟用 avoid_implementing_value_types 規則,請在你的 analysis_options.yaml 檔案中的 linter > rules 下新增 avoid_implementing_value_types

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_implementing_value_types

如果你使用的是 YAML map 語法來配置 linter 規則,請在 linter > rules 下新增 avoid_implementing_value_types: true

analysis_options.yaml
yaml
linter:
  rules:
    avoid_implementing_value_types: true