Skip to content

no_leading_underscores_for_local_identifiers shouldn’t fire if the variable is defined in an object pattern field with an implied name #59121

Closed
dart-archive/linter
#4296
@stereotype441

Description

@stereotype441

Describe the issue
When a variable name is declared implicitly using ObjectPattern(:var name) syntax, the user doesn't have free choice in the variable name; the name must match the field of the object they are destructuring.

The lint no_leading_underscores_for_local_identifiers shouldn't fire in this case, because it can't be fixed by a simple rename.

To Reproduce
Given this Dart 3.0 code:

class Foo {
  var _bar;
}
test(Object o) {
  switch (o) {
    case Foo(:var _bar): // (1)
      print(_bar);
  }
}

The lint no_leading_underscores_for_local_identifiers is firing at (1). However the suggested quick fix ('Remove leading underscore') produces this:

  switch (o) {
    case Foo(:var bar): // (1)
      print(bar);
  }

(the omitted lines are unchanged). This is a compile-time error because there is no field bar in the class Foo.

It's tempting to suggest also renaming Foo._bar, but that would be bad because it would expose private details of the class Foo to consumers of the library.

In principle, one could avoid the lint by rewriting the object pattern using an explicit name, i.e.:

  switch (o) {
    case Foo(_bar: var bar): // (1)
      print(bar);
  }

But I would argue that this is worse than the original because of the repetition of bar. I think it would be better to simply make an exception so that the lint rule doesn't fire in cases like these.

Expected behavior
The lint shouldn't fire if the variable is defined by a variable pattern, and that variable pattern is either:

  • An immediate subpattern of an object pattern, where the corresponding field name is omitted,
  • or an immediate subpattern of a null-assert or null-check pattern, where the null-assert or null-check pattern is an immediate subpattern of an object pattern, where the corresponding field name is omitted.

Reproduced in Dart SDK 742612d, which includes linter version 2212d95.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions