duplicate_pattern_alternative
Reports an operand of a logical pattern that repeats an earlier operand of the same chain. Delete it, or write the value you meant.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- delete the repeated operand
What it reports
Section titled “What it reports”An operand that repeats an earlier one in the same chain: case 1 || 2 || 1, case int() && int(). The violation is on the repeated operand, and each further repetition is a violation of its own.
- A chain is a run of
||patterns, or of&&patterns. - A pattern in parentheses is one operand and is not taken apart. An
||chain inside an&&chain is a chain of its own. - Two operands are the same when they hold the same tokens in the same order and every name means the same declaration, as
no_equal_branchescompares branches. Whitespace and comments do not count.
It does not report:
- an operand that declares a variable,
[int x] || [int x]: both sides of||must declare the same variables anyway; - two cases of a
switchwith the same pattern, which the analyzer reports as unreachable; - operands that match the same values in other words,
1 || 2against2 || 1.
A repeated operand of || never matches where the earlier one did not, and a repeated operand of && tests again what was already tested. In a list of alternatives, the repetition usually stands where another value was meant. That value is then missing from the case and falls through to the next one, or to the default.
The rule is advisory because the code still does what the other operands say.
Example
Section titled “Example”String size(int count) => switch (count) { 1 || 2 || 1 => 'small', _ => 'large',};String size(int count) => switch (count) { 1 || 2 || 3 => 'small', _ => 'large',};The fix deletes the repeated operand and the operator before it: 1 || 2 || 1 becomes 1 || 2. The pattern matches the same values as before. If you meant another value, write it in place of the repetition instead.
Rule parameters
Section titled “Rule parameters”The rule has only the two common 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. |
assay: rules: duplicate_pattern_alternative: exclude: ["lib/generated/**"]Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression, which goes above the line of the repeated operand:
switch (code) { // The list mirrors the table of the specification, repetitions and all. // ignore: duplicate_pattern_alternative case 200 || 204 || 200: accept();}// ignore_for_file: assay/duplicate_pattern_alternative silences it in a whole file, and // ignore: assay/duplicate_pattern_alternative with the prefix works too. See Suppressions.