I have enabled Checkstyle for my project. It is showing yellow mark on method parameters and requesting to set it as final
. Why? What is the purpose? If not specified what will be the problem?
Method parameters and local variables should not be declared final unless it improves readability or documents an actual design decision. Fields should be declared final unless there is a compelling reason to make them mutable.
The main reasoning behind making a method final is to prevent it from being overridden by subclasses. By making a method final, you not only indicate but also ensures that your tried and tested method is not overridden.
If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it.
The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in. Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked.
In case there is a rule in Checkstyle, normally the answer is there as well: http://checkstyle.sourceforge.net/config_misc.html
In this case:
Changing the value of parameters during the execution of the method's algorithm can be confusing and should be avoided. A great way to let the Java compiler prevent this coding style is to declare parameters final.
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