目錄

invariant_booleans

條件不應無條件評估為 truefalse

此規則已在最新的 Dart 版本中移除。

詳細資訊

#

注意:此規則已在 Dart 3.0.0 中移除;它已不再起作用。

不要測試可在編譯時推斷的條件,或測試相同的條件兩次。

使用永遠只能是 false 的條件的條件陳述式,會導致程式碼區塊無法運作。如果條件永遠只能評估為 true,則條件陳述式是完全多餘的,且會降低程式碼的可讀性。很可能程式碼與程式設計者的意圖不符。應該移除條件,或應更新條件,使其不會始終評估為 truefalse,且不會執行多餘的測試。此規則會提示測試與 linted 的測試衝突。

錯誤

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