Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

final

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.

like image 493
Landon Kuhn Avatar asked May 21 '12 18:05

Landon Kuhn


People also ask

When should variables be final?

The term effectively final variable was introduced in Java 8. A variable is effectively final if it isn't explicitly declared final but its value is never changed after initialization.

What happen if we declare a variable as final?

Once we declare a variable with the final keyword, we can't change its value again. If we attempt to change the value of the final variable, then we will get a compilation error. Generally, we can consider a final variable as a constant, as the final variable acts like a constant whose values cannot be changed.

Why is it good practice to use local variables whenever possible?

So, by using a local variable you decrease the dependencies between your components, i.e. you decrease the complexity of your code. You should only use global variable when you really need to share data, but each variable should always be visible in the smallest scope possible.


1 Answers

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.

like image 115
Dave Newton Avatar answered Sep 19 '22 20:09

Dave Newton