null
or undefined
check should be consistent for all accesses of a variable
- INSUFFICIENT_NULL_CHECK
- Error
- Medium
- No tags
This rule applies when a variable is checked for null
(or undefined
) value at one point but is accessed without null
check at another point.
If the variable has indeed null
value, a TypeError
exception occurs when trying to access its property or call it as a function.
Therefore, a programmer needs to check the following:
- Access a variable consistently after checking it is not
null
. - Remove all
null
checks of a variable consistently if it cannot benull
.
Noncompliant Code Example
View with compliant examples side by sidefunction example1(x) {
x.p = 42;
if (x != null) { // INSUFFICIENT_NULL_CHECK alarm
doSomething(x);
}
}
function example2(x) {
if (x != null) { // INSUFFICIENT_NULL_CHECK alarm
doSomething(x);
}
y = x.p;
}
function example3(cb) {
cb();
if (cb != null) { // INSUFFICIENT_NULL_CHECK alarm
doSomething(cb);
}
}
Compliant Code Example
View with noncompliant examples side by sidefunction example1(x) {
if (x != null) {
x.p = 42;
doSomething(x);
}
}
function example2(x) {
if (x != null) {
doSomething(x);
}
y = x != null ? x.p : '';
}
function example3(cb) {
// If 'cb' must not be null
cb();
doSomething(cb);
}
Version
This rule was introduced in DeepScan 1.0.0-alpha.