Repeated Unary Prefix Operator
ID |
java.unary_prefix_operators_repeated |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code_smell, readability |
Description
Reports the same unary prefix operator applied twice or more in a row: - - -i, !!flag,
+ +i. A single layer of parentheses between the repeated operators still counts — !(!flag) is reported the same as !!flag, because the parentheses change nothing about the
value.
Doubled bitwise complement (~~x) is exempt: it is a known idiom for truncating a value to a
narrower integer width, so it is frequently deliberate. A third or later repetition (~x) goes
past that idiom and is reported like any other.
Rationale
For !, - and + the repetition is almost always a typo, and it silently changes the value:
- - -i evaluates to -i, not i, and !!flag evaluates to flag again, not a stronger
negation. Whoever wrote it likely meant the single operator, or meant to negate a different
sub-expression and picked the wrong one to wrap.
A repeated prefix `/`--` (` i`) is *not* reported, and cannot be: the operand of ` and
-- has to be an assignable variable, and i` is a value, so ` ++i is not valid Java in the
first place and never reaches this rule.
Different operators mixed together are not a repetition and are never reported — - +i negates a value that is itself explicitly marked positive, which is not the same defect.
int total = - - -amount; // Bad -- reads as -amount * 3, evaluates to -amount
boolean armed = !!flag; // Bad -- evaluates to flag, not a stronger negation
boolean safe = !(!flag); // Bad -- the same, written through parentheses
int scaled = + +amount; // Bad -- two unary pluses in a row
int total = -amount; // Good -- a single, unambiguous negation
boolean armed = flag; // Good -- the double negation removed entirely
int narrowed = ~~rawOffset; // Good -- the truncation idiom, exempt
Remediation
Collapse the repeated operator to what it actually evaluates to: drop both ! when they cancel
out, and keep a single - or drop it entirely depending on the parity of the count. Where the
repetition was not a typo but a deliberate width truncation, keep it at exactly two ~ so the
idiom stays exempt and recognisable.