This might be a simple question: How can I massively refactor my Java code to make most of the method argument as "final"? This is to follow one of our "checkstyle" rule. We have thousands of Java files, so manually edit all of them seems not an acceptable solution to us.
I didn't find any such refactor option in IntelliJ. Anybody knows any tool that can help? Or any smart approach to achieve that?
The final keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all.
The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override). The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The final keyword is called a "modifier".
Final Methods When a method is declared with final keyword, it is called a final method. A final method cannot be overridden.
The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment.
You can use IntelliJ's inspections mechanism for this:
final
modifier in all the missing places.Once you've done this, you may want to enable this inspection in your IDE so it warns you about making further mistakes:
In IntelliJ you can check the "Make generated local variables final" and "Make generated parameters final" options enabled.
In IntelliJ 2017.3 it's in Preferences -> Editor -> Code Style -> Java -> Code Generation tab.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With