Originally posted by Olexiy Prokhorenko:
Can anybody give me a clear explanation when it is the best way to use 'final' in method arguments? Really, cannot get it. Primitives are passed by value, objects are passed by reference to method. Even if we will use 'final' with object in method argument, all changes to object inside the method are possible and will affect real object.
So, what for? I feel myself very newbie, but cannot find any answer.
Originally posted by Ken Blair:
Anonymous classes that need to use a parameter as Jeff demonstrated is the most common case for a 'need' that I come across. Other than that I almost never use it. I suppose it might be a good practice to declare anything you don't intend on having altered as final. I don't see any disadvantages to declaring them final but I can see a few advantages.
Originally posted by Jim Yingst:
Regarding using final for variables used in local and anonymous classes, I omitted that simply because in those cases where you need to do it, it's obvious because the compiler will tell you so directly. I was more interested in the less obvious benefits of using final in general. Still, use in anonymous classes did deserve mention, so thanks to Jeff for bringing it up.
[Tony]: Better still, have your build fail if you declare any local (or field) that is "write once"
What's wrong with "write once"? Do you mean, fail for any write-once field which is not declared final? (I'd agree with that.)
Also, I'm curious about the time you found it necessary (or at least useful) to not declare a parameter final - even if it was a contrived case. I'd have thought method params could always be final. Was there perhaps an observable performance difference? Some other reason? Any further details you recall would be appreciated.
Originally posted by Alan Moore:
Everybody has been using primitives in their examples, but object references are a different story. If the object is mutable, declaring it final doesn't stop you from changing its state; it only stops you from assigning the variable to a different object. For example, say you're passing a StringBuffer into a method so you can append some text to it. Declaring the parameter final doesn't stop you from doing that, but it prevents your accidentally reassigning the variable to a different StringBuffer and creating a hard-to-find bug.
I agree that all parameters should be implicitly final. I don't make them final because (1) I'm lazy, (2) lines tend to be too long already, and (3) dammit, I shouldn't have to!
I didn't do it. You can't prove it. Nobody saw me. The sheep are lying! This tiny ad is my witness!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koophttps://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton