Hi, Thanks for your explanation.
Max Berger wrote: >>> [1] >>> http://pmd.sourceforge.net/rules/optimizations.html#MethodArgumentCouldBeFinal > >> +1 >> I must say, I’ve never really grasped the benefit of doing this. I’d be >> happy to be enlightened, though. > > Sure: > > Declaring a parameter / variable as final makes it immutable in the > method where it is used. This is: > > - required if the variable is used in an anonymous inner class (as a way > of passing "parameters" into one) Agreed on this one. I’ve used that once already. (More precisely, Eclipse told me that it would refuse to compile my file as long as I wouldn’t declare my parameters final, and I wasn’t in the mood for fight back then.) > - good coding practice on all methods: If a parameter is re-assigned, > the value may not be what the programmer actually intended it to be. Hmmm. But this safeguard becomes helpful only when the method starts to get really long, so long that you can lose track of the places where you re-assign the local variables. So long that it should actually be split into several sub-methods, whose small sizes make this precaution superfluous again. That’s why I’m not convinced by the utility of this rule. FWIW, I do re-assign local variables sometimes (rarely). When the new value serves the same purpose, and creating a new variable with another name would actually look more confusing. Do I have to slash my hand for that? > Example: > > void someMethod(List l) > { > if (l==null) l = new LinkedList(); > l.add("test"); > } > > or even worse, this attempt to fix it: > > List someMethod(List l) > { > if (l==null) l = new LinkedList(); > l.add("test"); > return l; > } > > Here we have a very subtle code bug, which is triggered only in a few cases: > > List l1; > List l2; > ... > l1 = someMethod(l1); // does not trigger > l1 = someMethod(l2); // does trigger Ahem, err, what’s the bug? :-\ In both cases l1 receives a new list containing the string “test”. In both, l1 ends up being != the parameter of someMethod. > This rule is listed under "optimizations", because final can also be > used as a hint for hotspot, and many people use it mostly for > optimization (although the performance advantage is debatable). Moreover, the time where our last resort to further improve performance is to declare final all the arguments of all the methods of the codebase is no near to be reached IMO ;-) Vincent -- Vincent Hennebert Anyware Technologies http://people.apache.org/~vhennebert http://www.anyware-tech.com Apache FOP Committer FOP Development/Consulting