dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
627 stars 172 forks source link

proposal: `unnecessary_late` #4365

Open goderbauer opened 1 year ago

goderbauer commented 1 year ago

unnecessary_late

Description

If a variable is assigned in all code branches before use, the late keyword is unnecessary.

Details

The analyzer can determine statically whether a final local variable is assigned in all code paths before it is accessed. For that reason, it is not necessary to mark the variable as late.

Kind

Guard against errors: if during a refactoring you accidentally forget to assign foo in one of the branches, the analyzer will tell you instead of crashing at runtime.

Bad Examples

void bar(int value) {
  late final String foo;
  if (value == 1) {
    foo = "one";
  } else {
    foo = "not one";
  }
  print(foo);
}

Good Examples

void bar(int value) {
 final String foo;
  if (value == 1) {
    foo = "one";
  } else {
    foo = "not one";
  }
  print(foo);
}

Discussion

n/a

Discussion checklist

goderbauer commented 1 year ago

This lint likly needs a different name, since a lint by the very same name already exists: https://dart-lang.github.io/linter/lints/unnecessary_late.html. It catches different cases of unnecessary lates, though.

srawlins commented 1 year ago

I like the guard as an improvement over an exception thrown at runtime.

goderbauer commented 9 months ago

The lint should probably also fire in the most trivial case:

int foo() {
  late int bar = 0; // unnecessary late
  // ...
  return bar;
}