Search code examples
javasonarqubefinalruleslocal-variables

SonarQube - Java - Force local variables to be effectively final


I am using SonarQube and i can't find any rule for Java that would report reassignment of local variables (optionally also method parameters or class fields, but not in setters of course), or, in other words, force every local variable to be effectively final.

Non compilant example

public Car createRedCar() {
  Car car = new Car();
  car.setColor(Color.RED);

  car = makeCool(car); // <- error, car variable was reassigned
  // do other irrelevant stuff with car, eg log, dispatch event or whatever
  return car;
}

Compilant example

public Car createRedCar() {
  Car car = new Car();
  car.setColor(Color.RED);

  Car coolCar = makeCool(car); // <- it's ok, because all local variables are effectively final
  // do other irrelevant stuff with car, eg log, dispatch event or whatever
  return coolCar;
}

Another compilant example

public Car createRedCar() {
  final Car car = new Car();
  car.setColor(Color.RED);

  final Car coolCar = makeCool(car); // <- it's also ok, but i don't want to force every variable to be final
  // do other irrelevant stuff with car, eg log, dispatch event or whatever
  return coolCar;
}

I don't want to force every variable to have final keyword, just for them to be effectively final OR final.

If no default rule for this is present i'm okay with using custom rules and / or plugins, or finally even write one, but someone probably already did this and this is why i'm posting here.

I am using sonarqube-7.4, and i am willing to update if it comes with the rule i want.


Solution

  • If anyone is interested, i've developed a rule that does what i was asking for in the question. For now, it was tested only on sonarqube-8.3.1.

    link to the repo.