[New rule] avoid-useless-type-checks #477
Description
Please describe what the rule should do:
The rule should disallow useless type checks with is
operator. During code review I started to see useless type checks and see that people even try to perform null checks using is
operator.
Performing null checks using is
operator is quite bad practice in my opinion because the analyzer will not warn even if LHS is non nullable. For example,
String? value;
// Intention to check value for null
if (value is String) {
... some code
}
But analyzer will also not warn on such code:
const value = '';
// Might be intention to null check sometimes
if (value is String) {
... some code
}
Intention to null check is just one case for this rule, the goal is also to avoid using is
type check when it can be omitted. Maybe, we should split this rule into two: one to disallow useless type checks, the second to disallow null checking using is
operator.
Not sure if some rule like this already exists in the analyzer/linter.
If your rule is inspired by other please provide link to it:
None
What category of rule is this? (place an "X" next to just one item)
[x] Warns about a potential error (problem)
[ ] Suggests an alternate way of doing something (suggestion)
[ ] Other (please specify:)
Provide 2-3 code examples that this rule will warn about (it will be better if you can provide both good and bad examples):
BAD:
const value = '';
if (value is String) { // useless type check
}
String? value;
if (value is String) { // trying to check for null, it's is better to replace with "if (value != null)"
}
GOOD:
Shape value = Circle();
...
if (value is Circle) {
...
} else if (value is Rect) {
...
}
Are you willing to submit a pull request to implement this rule?
Maybe.