Search code examples
javafinal

Final variables as method arguments


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


Solution

  • The immutability of string is completely irrelevant to whether it's declared final or not. You could have a final StringBuilder parameter, and it would prevent exactly the same thing: reassignment of the variable within the method. You'd still be able to append to the StringBuilder. final in Java isn't the same as const in 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 final modifier, simply because it adds cruft in the code. If final were the default and you had to explicitly use a mutable modifier, 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 final modifier.

    Of course, if your colleague wrote the code, you don't have to guess - just ask!