use final inside a for each loop

final, java

Solution

Usually developers leave the defaults and only add code when they need to. i.e. what ever is the shortest code to write is easier. Think of a lecture theatre and they ask you to raise your hands if you do something and then they ask you to raise your hands if you don't, about half the room won't vote at all.

IMHO The default should have been final and you would have a keyword `var` for values which can change. This way much more fields would be final.

In this particular case, I don't make local variables final on the basis that methods should be short enough that you can reason whether the variable is changed or not. If you can't easily work this out, your loop/method is too complicated.

For fields however, I do recommend making these final whenever possible, esp if they are not private, as it is not so easy to read all the code where it might be used.

Problem

I have a small conflict with effective java. On one hand it strongly encourages to use final modifier. It also encourages to use foreach loop. However I did not see any piece of code anywhere, which codes like this: ``` for (final element e : list) { // do whatever. } ``` If element is not expected to change then using final appears to be good. Why is it not so common?

Original source