Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't all function arguments be declared final?

Tags:

java

oop

pmd

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

like image 900
Vlad Ilie Avatar asked Apr 25 '14 16:04

Vlad Ilie


People also ask

Should all variables be final?

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.

Why should method parameters be final?

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.

Do all functions need an argument?

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.

How many function arguments is too many?

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.


2 Answers

I can think of only 2 reasons not to make a parameter final:

  1. 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.

  2. 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.

like image 96
Joffrey Avatar answered Nov 20 '22 13:11

Joffrey


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.

like image 25
Denis Kulagin Avatar answered Nov 20 '22 11:11

Denis Kulagin