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