invariant_booleans
条件不应无条件评估为 true
或 false
。
详情
#注意:此规则已在 Dart 3.0.0 中移除;它不再起作用。
不要测试在编译时可以推断出的条件,也不要测试同一条件两次。
使用条件始终为 false
的条件语句,会导致代码块无法运行。如果条件始终评估为 true
,则条件语句完全多余,并降低代码的可读性。很可能代码与程序员的意图不符。应移除条件,或者应更新条件,使其不总是评估为 true
或 false
,并且不执行冗余测试。此规则将提示与当前 lint 规则冲突的测试。
不好
dart
// foo can't be both equal and not equal to bar in the same expression
if(foo == bar && something && foo != bar) {...}
不好
dart
void compute(int foo) {
if (foo == 4) {
doSomething();
// we know foo is equal to 4 at this point, so the next condition is always false
if (foo > 4) {...}
...
}
...
}
不好
dart
void compute(bool foo) {
if (foo) {
return;
}
doSomething();
// foo is always false here
if (foo){...}
...
}
好
dart
void nestedOK() {
if (foo == bar) {
foo = baz;
if (foo != bar) {...}
}
}
好
dart
void nestedOk2() {
if (foo == bar) {
return;
}
foo = baz;
if (foo == bar) {...} // OK
}
好
dart
void nestedOk5() {
if (foo != null) {
if (bar != null) {
return;
}
}
if (bar != null) {...} // OK
}
启用
#要启用 invariant_booleans
规则,请在你的 analysis_options.yaml
文件中,在 linter > rules 下添加 invariant_booleans
analysis_options.yaml
yaml
linter:
rules:
- invariant_booleans
如果你改用 YAML map 语法来配置 linter 规则,请在 linter > rules 下添加 invariant_booleans: true
analysis_options.yaml
yaml
linter:
rules:
invariant_booleans: true