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

112,982

Solution 1

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.

Solution 2

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 ;-)

Solution 3

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.

Solution 4

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

Solution 5

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.

Share:
112,982
Julien Chastang
Author by

Julien Chastang

Professional software developer living in beautiful Boulder, Colorado USA

Updated on November 21, 2020

Comments

  • Julien Chastang
    Julien Chastang over 3 years

    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?