Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can excessive use of final hurt more than do good?

Why are people so emphatic about making every variable within a class "final"? I don't believe that there is any true benefit to adding final to private local variables, or really to use final for anything other than constants and passing variables into anonymous inner classes.

I'm not looking to start any sort of flame war, I just honestly want to know why this is so important to some people. Am I missing something?

like image 626
Tim Michalski Avatar asked Feb 10 '10 05:02

Tim Michalski


1 Answers

  1. Intent. Other people modifying your code won't change values they aren't supposed to change.

  2. Compiler optimizations can be made if the compiler knows a field's value will never change.

Also, if EVERY variable in a class is final (as you refer to in your post), then you have an immutable class (as long as you don't expose references to mutable properties) which is an excellent way to achieve thread-safety.

like image 161
danben Avatar answered Oct 13 '22 02:10

danben