sdk
sdk copied to clipboard
Analyzer false positive on "unused private member"
Example:
abstract class PartialFoo {
int get _foo => 42; // Warning here.
}
abstract class Foo<T> {
int get _foo;
T _id(T value);
}
class ConcreteFoo<T> extends PartialFoo implements Foo<T> {
@override
T _id(T value) => value;
}
void main() {
Foo<int> f = ConcreteFoo<int>();
print(f._id(f._foo));
}
This shows the warning
line 2 • The declaration '_foo' isn't referenced.[ (view docs)](https://dart.dev/diagnostics/unused_element)
Try removing the declaration of '_foo'.
The _foo member is used. Its value is printed.
Aw rats. Good catch. It can be even simpler:
abstract class PartialFoo {
int get _foo => 42; // Warning here.
}
abstract class Foo {
int get _foo;
}
class ConcreteFoo extends PartialFoo implements Foo {}
void main() {
Foo f = ConcreteFoo();
print(f._foo);
}
We don't catch it because Foo and PartialFoo are not directly related.
And, of course, there's no reason why Foo and PartialFoo would need to be defined in the same library. Which means that we can't avoid the false positive without either (a) doing whole world analysis, which we can't do, (b) never reporting private members in public types as being unused, or (c) converting this warning to be opt-out by default.
The question is, is it worth the risk of a false positive in order to catch true positives, and that depends in part on how often a false positive like this occurs in practice.
If they're not defined in the same library, the private names won't be the same. I believe we only give this kind of warning for private names?
Yes, thank you. I didn't think it through far enough.
We still can't assume that the common subtype is in the same library, but we could suppress the warning if the same name is defined in multiple types. False negatives are generally less harmful than false positives for this kind of warning, so I think it makes sense to suppress them.