Assignment written as =+, =- or =!
ID |
apex.correctness.non_existent_operators |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Suspicious Construct |
Language |
Apex |
Description
Reports =+, =- or =! written as a single token and followed by a space, where +=, -= or != was almost certainly meant. Only that spacing is reported, because = +x and = -x are legitimate unary expressions.
Rationale
Apex has no =+, =- or =! operator, so the compiler reads the line as a plain assignment of a unary expression and accepts it. total =+ delta therefore replaces the running total with the last delta instead of adding to it, and remaining =- 1 sets the value to minus one rather than decrementing it. Nothing fails: the arithmetic simply produces a different number, which in an accumulator over a trigger batch means the record is saved with the last row’s contribution and no error anywhere. stale =! isFresh is the same trap written as a comparison that never happens.
The following code illustrates the pattern detected by this rule:
public class StockLedger {
public static Integer applyDelta(Integer total, Integer delta) {
// FLAGGED: Assignment written as =+, =- or =!
total =+ delta;
return total;
}
public static Integer consume(Integer remaining) {
// FLAGGED: Assignment written as =+, =- or =!
remaining =- 1;
return remaining;
}
public static Boolean invalidate(Boolean isFresh) {
Boolean stale;
// FLAGGED: Assignment written as =+, =- or =!
stale =! isFresh;
return stale;
}
public static Integer applyDeltaFixed(Integer total, Integer delta) {
total += delta;
return total;
}
public static Integer consumeFixed(Integer remaining) {
remaining -= 1;
return remaining;
}
public static Integer negate(Integer delta) {
Integer signed = -delta;
return signed;
}
public static Integer explicitSign(Integer delta) {
Integer signed = +delta;
return signed;
}
public static Boolean invalidateFixed(Boolean isFresh, Boolean wasFresh) {
Boolean changed = isFresh != wasFresh;
return changed;
}
public static Boolean atLeast(Integer count, Integer floorValue) {
return count >= floorValue;
}
}