跳到主要內容

invariant_booleans

已移除

條件不應無條件評估為 truefalse

詳細資訊

#

注意:此規則已在 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

如果您改為使用 YAML map 語法來設定 linter 規則,請在 linter > rules 下新增 invariant_booleans: true

analysis_options.yaml
yaml
linter:
  rules:
    invariant_booleans: true