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
What is the advantage of declaring a variable final in a for loop ?
Not much in a small piece of code, but, if it would help to avoid changing the reference while looping.
For instance:
for( String s : values ) {
computeSomething( s );
... a dozen of lines here...
s = s.trim();// or worst s = getOtherString();
... another dozen of line
otherComputation( s );
}
If you don't use final, the last line anotherComputation
can 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 final
will prevent value change at compile time.
...
for( final String s : values ) {
s = new StringBuilder( s ).reverse().toString();
}
This code fails at compile time variable s might already have been assigned
Another advantage could be to allow the variable to be used inside an anonymous inner class:
for( final String s : value ) {
doSomething( new InnerClass() {
void something() {
s.length();// accesing s from within the inner class
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With