Assign Already Assigned Value
ID |
java.assign_already_assigned_value |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Java |
Tags |
CWE:1164, code-style |
Description
Reports an assignment that re-assigns to the same target the exact value the immediately preceding statement already assigned, e.g. a = 1; a = 1;. The second assignment is redundant: it performs no additional work and almost always hides a copy-paste slip.
Rationale
When two consecutive statements assign the same value to the same variable, the second one was usually meant to target a different variable or assign a different value, and the edit was forgotten after copy-pasting the first line. The check only pairs strictly consecutive simple assignments and skips values containing method calls, allocations or increments, whose re-execution is observable and therefore not redundant.
// Bad - the second line repeats the first; one of them is a mistake
status = State.READY;
status = State.READY;
// Bad - same field, same value, twice in a row
config.timeout = DEFAULT_TIMEOUT;
config.timeout = DEFAULT_TIMEOUT;
Remediation
Delete the duplicated assignment, or fix it to assign the value or target that was actually intended.
// Good - the second statement targets the intended variable
status = State.READY;
retries = 0;
// Good - re-running a call is observable, not redundant (not reported)
value = next();
value = next();