Expression whose two operands are the same identifier
ID |
objectivec.maintainability.redundant_expression |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundant Operation |
Language |
Objective-C |
Description
Reports a comparison or a logical or arithmetic combination whose two operands are the same single identifier - x == x, x != x, x && x, x || x, x - x. Occurrences inside a line comment, a block comment or a string literal are not reported. An operand made of several tokens, such as a property access self.total == self.total, is not reported.
Rationale
The result of such an expression is fixed before the program runs: x == x is always true, x != x always false, x && x and x || x are just x, and x - x is always zero. The expression therefore tests nothing and computes nothing, while looking exactly like a check that does. Almost always one of the two operands is the wrong name - the second element of a copy-pasted comparison that was never renamed - so the guard that was meant to be there is silently absent and the branch it protects is taken unconditionally.
The following code illustrates the pattern detected by this rule:
@implementation Ledger
- (BOOL)isBalanced:(NSInteger)debit credit:(NSInteger)credit {
// FLAGGED: Expression whose two operands are the same identifier
if (debit == debit) {
return YES;
}
// FLAGGED: Expression whose two operands are the same identifier
if (debit != debit) {
return NO;
}
return debit == credit;
}
@end
Remediation
Work out which operand was meant to differ and correct it - usually the second one, against the neighbouring comparison it was copied from. If both operands really are the same value, delete the expression and use the operand directly, or drop the branch it guards.