always_returns_same_constant
Reports a function whose conditions all return the same literal. Give each branch the answer it was meant to give.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- strict
- Fix
- none
What it reports
Section titled “What it reports”A function, a method or a getter made of conditions and returns only, every one of which returns the same literal: if (a) return true; if (b) return true; return true;. The conditions decide nothing.
It is reported when:
- the body holds only
ifstatements, with or withoutelse, and returns, nested in blocks or not; - its last statement returns, and it has at least two returns;
- every return gives the same literal: a boolean, a number, or a string without interpolation.
It does not report:
- a body with any other statement: in
if (cached) return true; compute(); return true;the condition decides whether the work is done; - the literal
null, whichalways_returns_nullreports; - an override;
- one if/else chain whose last two branches are the same code, or one
ifwhose branch is the return after it (if (ready) return true; return true;):no_equal_branchesreports both.
The branches were written to give different answers, and one of them was copied without being changed. A caller that tests the result can never take its other branch.
Example
Section titled “Example”bool canEdit(Document document, User user) { if (document.isLocked) return true; if (user.isGuest) return true; return true;}bool canEdit(Document document, User user) { if (document.isLocked) return false; if (user.isGuest) return false; return true;}Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// Every mode allows it for now; the conditions stay for the next release.// ignore: assay/always_returns_same_constant// ignore_for_file: assay/always_returns_same_constant silences it in a whole file, and // ignore: always_returns_same_constant without the prefix works too. See Suppressions.