Why this matters
If a type parameter itself is nullable, using `!` for null checking can cause runtime exceptions. Use explicit checks instead.
Do not use `!` to check nullable type parameters, as this can lead to runtime exceptions if the type itself is nullable.
If a type parameter itself is nullable, using `!` for null checking can cause runtime exceptions. Use explicit checks instead.
Side-by-side examples engineers can pattern-match during review.
void main() {
getOrDefaultIf<int?>(() => 42, false);
}
T getOrDefaultIf<T>(T retriever(), bool condition) {
T? result;
final retrieveIfCondition = () {
if (condition) {
result = retriever();
}
};
retrieveIfCondition();
return result!; // Noncompliant
}void main() {
getOrDefaultIf<int?>(() => 42, false);
}
T getOrDefaultIf<T>(T retriever(), bool condition) {
T? result;
final retrieveIfCondition = () {
if (condition) {
result = retriever();
}
};
retrieveIfCondition();
return result as T;
}void main() {
getOrDefaultIf<int?>(() => 42, false);
}
T getOrDefaultIf<T>(T retriever(), bool condition) {
T? result;
final retrieveIfCondition = () {
if (condition) {
result = retriever();
}
};
retrieveIfCondition();
return result!; // Noncompliant
}void main() {
getOrDefaultIf<int?>(() => 42, false);
}
T getOrDefaultIf<T>(T retriever(), bool condition) {
T? result;
final retrieveIfCondition = () {
if (condition) {
result = retriever();
}
};
retrieveIfCondition();
return result as T;
}From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.