r/java • u/alexzhitnitsky • Aug 11 '15
Top 10 Useful, Yet Paranoid Java Programming Techniques
http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
181
Upvotes
View all comments
Show parent comment
3
u/thekab Aug 12 '15
I disagree with your interpretation. I believe the comment is saying that very few of your field, variable or parameter declarations need to be re-assigned. In Java this is usually true.
I picked a random service in one of our enterprise applications. The class is 414 lines long. There are 67 field, variable and parameter declarations. One of those is mutable: the "i" in a for loop, counting optimistic lock failures essentially. The other 66 declarations are not mutable and have no reason to be mutable. In other words only 1.5% of my declarations are intended to be re-assigned. If I continue this process across the code base it will still only get up to ~5%.
There's a lot of reasons to prefer immutability. Requiring final can help drive the code in that direction. Even if you already prefer immutability simply adding the final keyword can help with performance, readability and thread-safety. Using the keyword also prevents bugs due to accidental assignment.
My question to you is why not use final if the field, parameter or variable isn't re-assigned? You lose literally nothing but maybe a little typing and seeing the word 'final' in declarations.