I was looking at some code from a colleague and saw the following method:
public void someMethod(final String str) {
...
}
which I found odd, as Strings are immutable, anyway. I think it is safe to delete the final keyword, there.
I also found the following
public void reportProblems(final Collection<IProblem> problems) {
...
}
There aren’t any inner classes around, so.. is there a point in using the final keyword there? It looks to me that having the final there is absolutely the same as not having. Am I right?
Thanks
The immutability of string is completely irrelevant to whether it’s declared
finalor not. You could have a finalStringBuilderparameter, and it would prevent exactly the same thing: reassignment of the variable within the method. You’d still be able to append to theStringBuilder.finalin Java isn’t the same asconstin C++.Some people like to make everything final when they can – if you know that the value of a variable doesn’t change, it can be easier to reason about it. I have a lot of sympathy with that view, and often take the same approach myself – except that I don’t actually force the issue with the
finalmodifier, simply because it adds cruft in the code. Iffinalwere the default and you had to explicitly use amutablemodifier, I suspect that most developers wouldn’t start making every local variable mutable… they’d just use the default most of the time, as they do now.So, to come back to the original question: I suspect the developer just wants to be explicit about their style. It’s not how I do it, but I can understand the motivation. Another possibility is that at one point there was an inner class, but that’s gone now and the developer forgot to remove the
finalmodifier.Of course, if your colleague wrote the code, you don’t have to guess – just ask!