avoid-unnecessary-if

Group
Style
Path
lint/style/avoid-unnecessary-if
Default
Off, opt in
Origin
Falcon
Rule
165 of 512

Flags an if branch that only returns the same expression as the following return.

The if must have no else and its body must be a single value-return statement. Expressions are compared by token spelling, preserving literal contents. Check whether the branch should return something different; when removing it, retain any side effects in the condition. Bare returns belong to avoid-unnecessary-return. If-case patterns are excluded because their bindings can shadow return values.

Invalid

example.dartdart
int literal(bool ready) {
  if (ready) { return 1; }
  return 1;
}
String text(bool ready) {
  if (ready) return 'same';
  return 'same';
}
int variable(bool ready, int value) {
  if (ready) { return value; }
  return value;
}
int grouped(bool ready) {
  if (ready) { return (2); }
  return 2;
}
class Example {
  int method(bool ready) {
    if (ready) return 3;
    return 3;
  }
}
This branch returns the same value as the following return; check or remove the redundant branch.
1int literal(bool ready) {
2 if (ready) { return 1; }
This branch returns the same value as the following return; check or remove the redundant branch.
5String text(bool ready) {
6 if (ready) return 'same';
This branch returns the same value as the following return; check or remove the redundant branch.
9int variable(bool ready, int value) {
10 if (ready) { return value; }
This branch returns the same value as the following return; check or remove the redundant branch.
13int grouped(bool ready) {
14 if (ready) { return (2); }
This branch returns the same value as the following return; check or remove the redundant branch.
18 int method(bool ready) {
19 if (ready) return 3;

Valid

example.dartdart
int different(bool ready) {
  if (ready) return 1;
  return 2;
}
String whitespace(bool ready) {
  if (ready) return 'a b';
  return 'ab';
}
int work(bool ready) {
  if (ready) { print('work'); return 1; }
  return 1;
}
int otherwise(bool ready) {
  if (ready) return 1; else return 2;
}
int intervening(bool ready) {
  if (ready) return 1;
  print('work');
  return 1;
}
void bare(bool ready) {
  if (ready) return;
  print('work');
}
void barePair(bool ready) {
  if (ready) return;
  return;
}
String binding(Object value, String name) {
  if (value case String name) return name;
  return name;
}

Configure avoid-unnecessary-if

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "avoid-unnecessary-if": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/style/avoid-unnecessary-if: <reason>