避免_实现_值_类型
不要实现覆盖 ==
的类。
详情
#不要 实现覆盖 ==
的类。
==
运算符在契约上要求是一个等价关系;也就是说,对于所有对象 o1
和 o2
,o1 == o2
和 o2 == 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