Ok, so I understand why we should declare an argument to be final from this question, but I don't understand why we shouldn't...
Since Java always uses pass by value, this means that we can't return a new value through the given argument, we can only overwrite it, and make the argument useless therefore, because we don't use the passed value...
Is the only benefit of non-final method arguments in Java the fact that you don't have to make a local variable of the arguments' type?
P.S. This question was triggered by PMD
's rule of MethodArgumentCouldBeFinal
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.
Having final on methods parameters helps you understand the outgoings of the method at first glance, and draws some attention to those non-final parameters.
You can define a function that doesn't take any arguments, but the parentheses are still required. Both a function definition and a function call must always include parentheses, even if they're empty.
Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.
I can think of only 2 reasons not to make a parameter final
:
to save the use of a local variable if you need to overwrite the parameter's value in some edge cases (for instance to put a default if the param is null etc.). However, I wouldn't consider that a good practice in general.
to save 6 characters per parameter, which improves readability.
Reason 2 is what leads me not to write it most of the time. If you assume that people follow the practice of never assigning a new value to a parameter, you can consider all parameters as implicitly final
. Of course, the compiler won't prevent you from assigning a parameter, but I can live with that, given the gain in readability.
It prevents you from making unintentional error in your code. Rule of thumb here is to make each field and each function argument you know you shouldn't change (I mean reference, you still can change value) in your code as final.
So basically its a mean to prevent programmer from shooting their foot. Nothing more.
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