-
Reassigning existing variable to new value introduces additional complexity to the code and violates the immutability paradigm. New variable should be created instead of mutating of existing one.
This should have an exception for the for loops and do/while loops as those (unfortunately) rely on the reassignment. -
snippet of Noncompliant Code
found at GitHub - kamilbeben/variable-reassignment-check
void foo(Bar bar) {
String barName = bar.getName();
if (barName == null) {
barName = "defaultName"; // Noncompliant
}
}
- snippet of Compilant Code (fixing the above noncompliant code)
found at GitHub - kamilbeben/variable-reassignment-check
void foo(Bar bar) {
String barName = Optional.ofNullable(bar.getName()).orElse("defaultName");
}
- exceptions to the Noncompliant Code, i.e. conditions in which the noncompliant code should not raise an issue so that we reduce the number of False Positives.
int i = 0;
while (i < 10) {
i++;
}
-
external references and/or language specifications
- Documentation/Blog post explaining the issue and what should be done instead.
Best Practices | PMD Source Code Analyzer
- Documentation/Blog post explaining the issue and what should be done instead.
-
type: Code Smell