Constant expression should not be used in the conditional statements
- CONSTANT_CONDITION
- Code Quality
- Medium, Low
- cwe
This rule applies when a condition check has always the same result.
For example, it occurs when constant-valued variables are used or the condition is redundant with previously checked one. This rule also applies when only one case
is executed due to the result of switch
condition check being always the same.
It could be a debugging code, but at worst it is a programmer's mistake that completely misses block of code intended to be executed.
Especially, if a redundant condition makes some code unreachable or conflicts with previously checked one, 'Medium' impact is assigned to the alarm because such code is more likely to have problems.
Note:
- Not applied if the variable name is
debug
ordbg
. - Not applied if the variable is declared with a constant value and never assigned again.
Noncompliant Code Example
View with compliant examples side by side// Example 1
if (y) {
x = 42;
} else {
x = 42;
}
if (x > 0) { // CONSTANT_CONDITION alarm: Condition 'x > 0' is always satisfied at this point.
console.log(x);
}
// Example 2
if (y) {
x = 42;
} else {
x = 42;
}
switch (x) {
case 0: z = 0; break;
case 42: z = 1; break; // CONSTANT_CONDITION alarm: This switch case is always matched.
}
// Example 3
if (x) {
if (x != null) { // CONSTANT_CONDITION alarm: Condition 'x != null' is always satisfied because it is redundant with the above condition 'x'.
console.log(x.p);
}
}
// Example 4
if (x < 0) {
if (x < 42) { // CONSTANT_CONDITION alarm: Condition 'x < 42' is always satisfied at this point because it is redundant with the above condition 'x < 0'.
console.log('x is between 0 and 42');
}
}
// Example 5
function foo(x, y) {
var arr = [];
if (x) arr.push(x);
if (y) arr.push(y);
if (arr) { // CONSTANT_CONDITION alarm: Condition 'arr' is always satisfied at this point because it is an array. Did you mean 'arr.length' instead?
console.log(arr.join(", "));
}
}
Compliant Code Example
View with noncompliant examples side by side// Example 1
if (y) {
x = 42;
} else {
x = 0;
}
if (x > 0) {
console.log(x);
}
// Example 2
if (y) {
x = 42;
} else {
x = 0;
}
switch (x) {
case 0: z = 0; break;
case 42: z = 1; break;
}
// Example 3
if (x) {
console.log(y.p);
}
// Example 4
if (x > 0) {
if (x < 42) {
console.log('x is between 0 and 42');
}
}
// Example 5
function foo(x, y) {
var arr = [];
if (x) arr.push(x);
if (y) arr.push(y);
if (arr.length) {
console.log(arr.join(", "));
}
}
Version
This rule was introduced in DeepScan 1.0.0-alpha.