I was reading some code found on the web and fell on these lines (java):
private List<String> values;
[...]
for (final String str : values) {
length += context.strlen(str);
}
What is the advantage of declaring a variable final in a for loop ? I thought the variable specified in the for loop was already read-only (e.g. can’t assign something to ‘str’ in the above example).
Thx
Not much in a small piece of code, but, if it would help to avoid changing the reference while looping.
For instance:
If you don’t use final, the last line
anotherComputationcan potentially use a different value than the one was defined in the iteration and subtle bugs may be introduced, while reading other code the maintainer will try to figure out how come that method is failing with the correct values.For a 5 – 15 lines long for this is easy to spot, but for larger segments of code, believe me, is much harder.
Using
finalwill prevent value change at compile time.This code fails at compile time
variable s might already have been assignedAnother advantage could be to allow the variable to be used inside an anonymous inner class: