Programing

Why would one mark local variables and method parameters as “final” in Java?

lottogame 2020. 12. 24. 23:19
반응형

Why would one mark local variables and method parameters as “final” in Java?


In Java, you can qualify local variables and method parameters with the final keyword.

public static void foo(final int x) {
  final String qwerty = "bar"; 
}

Doing so results in not being able to reassign x and qwerty in the body of the method.

This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?


You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.


My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.

I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.

But, of course, it's all personal preference ;-)


Making a parameter final guarantees that the value used at any location in the method refers to the value passed. Otherwise you have to parse mentally all the code above a given location to know what value the parameter has at that point.

Hence, not using final makes your code less readable, and maintainable, all by itself :)

Final local variables depend on intent, and is less important in my point of view. Depends on what goes on.


In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be.

In the case of magic numbers, I would put them as a constant private field anyway rather than in the code.

I only use final in situations where it is necessary (e.g., passing values to anonymous classes).


Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.

Finalizing local var's seems somewhat overkill IMO.


Yes do it.

It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.

A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.


final has three good reasons:

  • instance variables set by constructor only become immutable
  • methods not to be overridden become final, use this with real reasons, not by default
  • local variables or parameters to be used in anonimous classes inside a method need to be final

Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.


Although it creates a little clutter, it is worth putting final. Ides e.g eclipse can automatically put the final if you configure it to do so.


Making local variables and method parameters final is essential if you want to pass those parameters into anonymous classes - like you instantiate an anonymous Thread and want to access those params in the body of the run() method.

Apart from that I am not sure of the performance benefits w.r.t better performance through compiler optimization. It is up to the specific compiler implementation whether it wants to optimize it at all...

It will be good to know of any performance stats from using final ...


Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.

The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.

Edit

In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.


I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.


We do it here for the local variables if we think they will not be reassigned or should not be reassigned.

The parameters are not final since we have a Checkstyle-Check which checks for reassigning parameters. Of course nobody would ever want to reassign a parameter variable.

ReferenceURL : https://stackoverflow.com/questions/316352/why-would-one-mark-local-variables-and-method-parameters-as-final-in-java

반응형