Is it a good practice to declare variables "final" wherever possible?

18,167

Solution 1

The "Java way" is inherently, intrinsically cluttery.

I say it's a good practice, but not one I follow.

Tests generally ensure I'm doing what I intend, and it's too cluttery for my aesthetics.

Solution 2

I routinely apply final to local variables in my code and additionally find reading code much easier after first having marked all effictively final variables with the final keyword. I regard this as a bona fide enhancement to the code, and commit it right thereafter.

As for the concern of code clutter, when applied to local variables I don't find it damaging—in fact it makes me spot all declarations more easily due to syntax coloring.

I must admit, though, that I do find it unbearably cluttery when final is used on parameters, catch blocks, enhanced-for loops and all other places except local variables in the narrow sense. This is quite unfortunate because a reassignment in these cases is even more confusing and they should really have been final by default.

Solution 3

I consider it good practice, more for maintenance programmers (including me!) than for the compiler. It's easier to think about a method if I don't need to worry about which variables might be changing inside it.

Solution 4

Yes, it's a very good idea, because it clearly shows what fields must be provided at object construction.

I strongly disagree that it creates "code clutter"; it's a good and powerful aspect of the language.

As a design principle, you should make your classes immutable (all final fields) if you can, because they may be safely published (ie freely passed around without fear they will be corrupted). Although note that the fields themselves need to be immutable objects too.

Solution 5

It definitely gives you a better code, easy to see which all variables are going to be changed.

It also informs the compiler that it is not going to change which can result to better optimization.

Along side it allows your IDE to give you compile time notification if you tend to do any mistake.

Share:
18,167
Landon Kuhn
Author by

Landon Kuhn

Updated on June 02, 2022

Comments

  • Landon Kuhn
    Landon Kuhn about 2 years

    Possible Duplicate:
    When should one use final?

    I tend to declare all variables final unless necessary. I consider this to be a good practice because it allows the compiler to check that the identifier is used as I expect (e.g. it is not mutated). On the other hand it clutters up the code, and perhaps this is not "the Java way".

    I am wondering if there is a generally accepted best practice regarding the non-required use of final variables, and if there are other tradeoffs or aspects to this discussion that should be made aware of.