dart-lang / linter

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

proposal: `abstract_private_class_member` #4984

Open nate-thegrate opened 1 month ago

nate-thegrate commented 1 month ago

Description

Don't define an abstract private member within a public class.

Can be fixed by making the value public or adding a sealed or final modifier to the class.

Details

Kind: AVOID

Currently, the following produces zero static analysis warnings:

abstract base class A {
  void _foo();

  A() {
    _foo(); // always throws an error
  }
}

Marking a field as abstract signifies that "subclasses should implement this", so making it private entirely defeats the purpose.

Examples

abstract class A {
  // BAD
  int get _value;

  // BAD
  void _foo();

  // BAD
  abstract final bool _value;
}

// GOOD: class is private instead
abstract class _A {
  void foo();
}

// GOOD: class is marked as `sealed`
abstract sealed class A {
  void _foo();
}

Discussion

If an abstract private field is added to a non-sealed public class, there are 3 possibilities:

  1. The unused_element rule is triggered
  2. It's referenced in a public scope (see #4983)
  3. It's referenced only within other private scope(s) in the same library

Even though possibility number 3 would never result in an error, I still think it'd be good for this rule to apply: a lack of sealed or final indicates that the class can be built upon outside the declaring library, so if the private field provides utility within the library, IMO it should either be refactored or exposed as a public field.

Probably low-priority

If this proposal is motivated by real-world examples, please provide as many details as you can. Demonstrating potential impact is especially valuable.

I've never seen a class with an abstract private field.