boolean expression that reduces to a shorter equivalent
ID |
rust.maintainability.nonminimal_bool |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundancy |
Language |
Rust |
Description
Reports boolean expressions with a shorter equivalent - comparison against true/false, double negation, a negated comparison operator, and operands combined with their own negation.
Rationale
Each of these forms makes the reader compute the value instead of reading it: x == true adds a comparison that returns the operand it was given, !(a ⇐ b) has to be mentally rewritten as a > b, and a || !a is a constant dressed up as a decision. The redundant halves also invite mistakes during edits - negating an already negated expression, or changing one side of x == false and inverting the meaning of the whole condition.
The following code illustrates the pattern detected by this rule:
fn render(enabled: bool, verbose: bool, count: usize, limit: usize) -> u8 {
// FLAGGED: boolean expression that reduces to a shorter equivalent
if enabled == true {
return 1;
}
// FLAGGED: boolean expression that reduces to a shorter equivalent
if verbose != false {
return 2;
}
// FLAGGED: boolean expression that reduces to a shorter equivalent
let forced = !!enabled;
// FLAGGED: boolean expression that reduces to a shorter equivalent
let always = enabled || !enabled;
// FLAGGED: boolean expression that reduces to a shorter equivalent
let never = verbose && !verbose;
// FLAGGED: boolean expression that reduces to a shorter equivalent
if !(count == limit) {
return 3;
}
// FLAGGED: boolean expression that reduces to a shorter equivalent
if !(count <= limit) {
return 4;
}
if forced && always && !never {
return 5;
}
0
}