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: `private_field_outside_class` #4983

Open nate-thegrate opened 1 month ago

nate-thegrate commented 1 month ago

Description

Avoid referring to a private field of a class outside the class declaration.

Can be fixed by making the field public, making the class private, making the enclosing reference private, adding the base/sealed/final modifier, or moving the reference into the class declaration.

Kind: AVOID

Currently, the following produces zero static analysis warnings:

interface class A {
  final int _value = 0;
}

int getValue(A a) => a._value; // always throws an error

And when combined with an abstract_private_class_member violation, it doesn't matter whether the class is extended or implemented:

abstract class A {
  int get _value;
}

int getValue(A a) => a._value; // always throws an error

Examples

class A {
  final int _value = 0;
}

// BAD
int getValue(A a) => a._value;

class B {
  // BAD
  factory B.fromA(A a) => B(a._value);
}

// GOOD, class is private
class _A {
  final int _value = 0;
}

// GOOD, enclosing function is private
int _getValue(A a) => a._value;

// GOOD, field is public
class A {
  final int value = 0;
}

// GOOD, class has the "base" modifier
base class A {
  final int _value = 0;
}

// GOOD, private field is accessed within the class
class A {
  final int _value = 0;
  int get value => _value;
}

Discussion

There probably wouldn't be a "quick-fix" for the rule, since there are many solutions (some of which may cause a name overlap).

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 real-world situation where this rule has been broken.