Same expression on both sides of a binary operator
ID |
apex.correctness.identical_operands |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
Apex |
Description
Reports a comparison, a logical operator or a subtraction or division whose two operands are the same expression.
Rationale
The result is fixed before the code runs: a == a is always true, a && a is a, a - a is zero. A condition that cannot vary is not a condition, so the branch it guards either always runs or never does - and the test that was supposed to be performed is silently absent. The usual cause is a copy-pasted operand where the second name was never changed, which means the variable that should have been compared is not being checked at all.
The following code illustrates the pattern detected by this rule:
public class IdenticalOperands {
public void run(Account a, Account b, Integer x, Integer y) {
// FLAGGED: Same expression on both sides of a binary operator
if (a.Name == a.Name) {
System.debug('always');
}
// FLAGGED: Same expression on both sides of a binary operator
Boolean both = (x > 0 && x > 0);
// FLAGGED: Same expression on both sides of a binary operator
Integer zero = x - x;
System.debug(both + '' + zero);
if (a.Name == b.Name) {
System.debug('compared');
}
Integer diff = x - y;
System.debug(diff);
}
}