The same unary operator is applied twice to one operand
ID |
objectivec.maintainability.no_double_operators |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundant Operation |
Language |
Objective-C |
Description
Reports an operand carrying the same unary prefix operator twice in a row - !!flag, ~~mask, or an arithmetic negation written - -offset. The two applications may be separated by spaces. A negation wrapped in parentheses (!(!flag)), a comparison against a negation (a != !b), the decrement operator --count, a subtraction of a negated operand (a - -b), and occurrences inside a comment or a string literal are not reported. A chain of two different unary operators is reported by the multiple-unary-operator rule instead.
Rationale
~~mask and - -offset cancel out exactly, so they are equivalent to the operand alone and compute nothing - they are the visible residue of an edit, such as a negation added to an expression that was already negated, or a sign left behind by a search-and-replace. !!flag does not cancel: it is the established idiom for narrowing an arbitrary scalar to YES or NO, so it is worth keeping where that is the intent. Where it is not, it reads as if the author were unsure what the operand held, and the ambiguity is exactly what a reader has to stop and resolve.
The following code illustrates the pattern detected by this rule:
@implementation Session
- (BOOL)isActive:(NSInteger)handle {
// FLAGGED: The same unary operator is applied twice to one operand
BOOL active = !!handle;
return active;
}
@end
Remediation
For ~~ and - -, delete both operators and use the operand directly. For !!, keep it only where narrowing to YES/NO is genuinely the point - assigning to a BOOL field that is later compared with ==, for instance - and otherwise reduce it to a single ! or to the operand itself. Where narrowing is intended, flag ? YES : NO states it without relying on the reader knowing the idiom.