Comparison wrapped in a logical negation
ID |
apex.maintainability.inverted_boolean_check |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Readability |
Language |
Apex |
Description
Reports a comparison that is negated as a whole - !(a == b), !(a > b) and the other four relational forms - where the opposite operator says the same thing directly.
Rationale
The reader has to evaluate the comparison and then flip the result, and the ! is one character wide: it disappears next to a parenthesis, which is how a negation gets dropped or added by accident during an edit. Writing the opposite operator removes both problems and makes the condition readable in one pass.
The following code illustrates the pattern detected by this rule:
public class InvertedChecks {
public void run(Integer a, Integer b, String name) {
// FLAGGED: Comparison wrapped in a logical negation
if (!(a == b)) {
System.debug('different');
}
// FLAGGED: Comparison wrapped in a logical negation
if (!(a > b)) {
System.debug('not greater');
}
// FLAGGED: Comparison wrapped in a logical negation
Boolean differs = !(name == 'x');
System.debug(differs);
if (a != b) {
System.debug('different');
}
if (!name.contains('x')) {
System.debug('no x');
}
if (!(a == b && name == 'x')) {
System.debug('compound');
}
}
}