New Rule: Variable should not be reassigned

  • 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
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) {

Hi @Ygrek,

Thank you for the suggestion!

After analyzing your suggestion for a new rule, I found some additional topics I would like you to consider.

Java is a language where we have mutable variables by design. If you want non-mutable variables, you can use the final keyword, but that means you will have more code.

I also noticed that the link you provided with best practices addresses the case where reassignment of the method parameters is not recommended. Your code example does not match that use case since you are reassigning a newly created variable, barName.

If you need this rule in your project, you can create your own custom rule.
Here is the link with the process explained.

I hope this helps.

All the best,