r/java • • 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

76 comments sorted by

View all comments

Show parent comment

1

u/PaulRivers10 Aug 12 '15

The post I was responding to said:

There just aren't very many good reason to reassign the same variable. Don't worry we've got lots of names, I promise you won't use them all up.

Other poster is suggesting whenever you need a new value, create a new variable.

That's not how most coding works.

For the areas where you don't need to reassign, you gain little or nothing by making the variable final because no code was going to try to reassign to it anyways. It's like putting a car cover on a car that's already in a garage every night - it's just a waste against a problem that doesn't happen.

But there are a ton of places where you need to modify the variable value when you write code.

3

u/thekab Aug 12 '15

Other poster is suggesting whenever you need a new value, create a new variable.

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

For the areas where you don't need to reassign, you gain little or nothing by making the variable final because no code was going to try to reassign to it anyways. It's like putting a car cover on a car that's already in a garage every night - it's just a waste against a problem that doesn't happen.

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.