Ternary that returns the boolean it tested, or the same value twice
ID |
objectivec.maintainability.redundant_conditional_operator |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundant Code |
Language |
Objective-C |
Description
Reports two pointless shapes of the ? : operator: one that yields YES and NO (or true/false, TRUE/FALSE) in either order, which just restates the condition, and one whose two operands are the same identifier or number, which makes the condition irrelevant. A ternary whose condition is itself a literal constant is left to constant-conditional-operator and is not reported here. Operands that only share a prefix, such as self.name and self.nameSuffix, are not treated as equal.
Rationale
flag ? YES : NO is a longer spelling of flag, and condition ? NO : YES a longer spelling of !condition; both make the reader parse a branch to recover a value that was already in hand. The second shape is more than noise: flag ? x : x evaluates the condition and then discards the answer, which is almost never what the author wrote — it is usually a copy-paste where one of the two operands should have been changed, so the bug is a missing edit rather than a redundant one, and the line looks deliberate until the operands are read side by side.
The following code illustrates the pattern detected by this rule:
@implementation Reporter
- (BOOL)isReady:(BOOL)flag {
// FLAGGED: Ternary that returns the boolean it tested, or the same value twice
return flag ? YES : NO;
}
@end