Reversed Compound Operator
ID |
java.reversed_compound_operator |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
operators, reliability |
Description
Reports an assignment written as target =- num, target =+ num or flag =! other: the = sits glued to the following unary operator, with the operand set off by a space. Java has no =-, =+ or =! operator — the statement is a plain assignment of a negated, signed, or inverted value — but the spacing makes it read as the compound assignment -= / +=, or the comparison !=.
Rationale
The mismatch is silent: the code compiles and runs, just not as the layout advertises. total =- count assigns -count, not total minus count; flag =! other overwrites flag with the negation of other, rather than comparing the two. Either could be exactly what the author wanted, or it could be a typo for the compound operator that nobody will notice until the numbers come out wrong.
int total = -5;
int count = 3;
total =- count; // total becomes -3, not total - count
Remediation
Use the compound operator if that was the intention, or add a space after = to make the unary operator unambiguous.
int total = -5;
int count = 3;
total -= count; // total becomes -8
// or, if the negation was intended:
total = -count; // total becomes -3