Tuesday, June 14, 2005

How often do you use final?

I ran across a Source Code Scanner called PMD in the last Dr Dobbs issue. There are two rules that seem to generate a lot of warnings. They are LocalVariableCouldBeFinal and MethodArgumentCouldBeFinal (http://pmd.sourceforge.net/rules/optimizations.html)

In the terms of Method Arguments and local varaibles, I found that the final modifyer means that the variable will not be reassigned.

I find that pretty much all my MethodArguments should be final and a majority of my Local Variables should be final. Unfortunately, defining everything as final takes extra work (all that typing) and also causes some code clutter.

Any comments on how strictly I should use the final modifier?

98 comments:

Anonymous said...

It would be cool for IDEs to have an automatic refactoring that added final everywhere it could.

Anonymous said...

I use the inspect code in intellij IDEA. It can refactor all variables/methods to final ones.

Anonymous said...

Tools like checkstyle forces you to use it when it's required...

Anonymous said...

This seems pretty useless. The only use of this information is to the person writing the method implementation. In particular, having the method arguments declared final conveys no information whatsoever to the client of the method.

Now, if you can't figure out if a specific local variable is or isn't supposed to be modified, then by all means, use final, but what it really means is that your method is just too long!

I think if I saw code that has final all over the place (so far I never had in practice), I'd feel that it was noisy...

I think a much more valuable check would be to verify a method should or should not be declared as final. A well-designed library should have most methods declared as final, but it very rarely happens... But a source code scanner would not be intelligent enough beyond stating that a method is not being overridden in the library code itself.

Then again, I haven't used lint tools in my work, I imagine I'd find them annoying :)

Anonymous said...

Lots of insight around the final keyword can be found in The Final Word On the final Keyword and especially the section on final variables.

For a small project, we are trying to put final keyword everywhere PMD recommends it. It makes the code bulky at first but you're quickly used to it, and see the benefits.

Anonymous said...

I have no idea how much benefit is actually gained. I always follow the recommendation. It seems that as clever as the JIT/Hotspot JRE's are, they probably figure out what variables can be considered "effectively final" and optimize anyway. My personal feeling is that it never hurts to give the JRE/compiler a little extra help.

Anonymous said...

I think that specifying method params as final can be informative to clients, but not nearly as informative as some good javadoc.

I don't see the benefit of making local variables final, especially with modern compilers. Of course, there are some special circumstances where this makes sense, but as a rule, I think it would be a waste of time.

Anonymous said...

I am using final wherever I could. Not for performance (as often expected) but for safety. Overwriting variables is very error-prone, since it leads to code that is hard to understand. As a result, re-writing variables often ends up in overwriting the wrong ones. With almost every variable final, "variable reuse" is prevented, and in turn you are forced to use new variables (with new and unambiguous names!). As a result, the potential bugs per line are reduced by far. We found out that in the past five years of Java coding in our company, this reduced our costs for bugs by around 50% (together with some other nice side effects e. g. final forces to correctly initialize).

Anonymous said...

I didn't feel at ease while reading the first comments on this topic because I was missing the ascpect that finally came up in the statement of markus karg. From my point of view the main reason for using final on local variables / parameters is avoiding errors. It think that every programmers should ALWAYS think twice when "reusing" a variable. It's all about program structure on "developer level" - don't spend time on trying to help the compiler or the JVM, other people take care of those.

Anonymous said...

Using final for parameters is very, very useful. It directly tells you if you miss the "this" prefix when using the same name for a parameter and an instance variable.
/B

Anonymous said...

Great article! Thanks.

Anonymous said...

Thanks for interesting article.

Anonymous said...

Nice! Nice site! Good resources here. I will bookmark!

Anonymous said...

I see first time your site guys. I like you :)

Anonymous said...

Excellent website. Good work. Very useful. I will bookmark!

Anonymous said...

4ERZOO You have a talant! Write more!

Anonymous said...

ART8Lh actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

L1TB0p The best blog you have!

Anonymous said...

1mbQTG Thanks to author.

Anonymous said...

Good job!

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

Please write anything else!

Anonymous said...

Magnific!

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

Good job!

Anonymous said...

Please write anything else!

Anonymous said...

Thanks to author.

Anonymous said...

oaoePU write more, thanks.

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

Please write anything else!

Anonymous said...

Good job!

Anonymous said...

Magnific!

Anonymous said...

Thanks to author.

Anonymous said...

Please write anything else!

Anonymous said...

Please write anything else!

Anonymous said...

Magnific!

Anonymous said...

Magnific!

Anonymous said...

Hello all!

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

Friends help you move. Real friends help you move bodies

Anonymous said...

Friends help you move. Real friends help you move bodies.

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

Beam me aboard, Scotty..... Sure. Will a 2x10 do?

Anonymous said...

Suicidal twin kills sister by mistake!

Anonymous said...

Lottery: A tax on people who are bad at math.

Anonymous said...

Lottery: A tax on people who are bad at math.

Anonymous said...

Energizer Bunny Arrested! Charged with battery.

Anonymous said...

Friends help you move. Real friends help you move bodies.

Anonymous said...

Lottery: A tax on people who are bad at math.

Anonymous said...

Suicidal twin kills sister by mistake!

Anonymous said...

Beam me aboard, Scotty..... Sure. Will a 2x10 do?

Anonymous said...

Hello all!

Anonymous said...

All generalizations are false, including this one.

Anonymous said...

A lot of people mistake a short memory for a clear conscience.

Anonymous said...

I don't suffer from insanity. I enjoy every minute of it.

Anonymous said...

If ignorance is bliss, you must be orgasmic.

Anonymous said...

Save the whales, collect the whole set

Anonymous said...

Suicidal twin kills sister by mistake!

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

C++ should have been called B

Anonymous said...

C++ should have been called B

Anonymous said...

Suicidal twin kills sister by mistake!

Anonymous said...

Clap on! , Clap off! clap@#&$NO CARRIER

Anonymous said...

Nice Article.

Anonymous said...

Hello all!

Anonymous said...

Magnific!

Anonymous said...

640K ought to be enough for anybody. - Bill Gates 81

Anonymous said...

Nice Article.

Anonymous said...

The gene pool could use a little chlorine.

Anonymous said...

Save the whales, collect the whole set

Anonymous said...

I don't suffer from insanity. I enjoy every minute of it.

Anonymous said...

If ignorance is bliss, you must be orgasmic.

Anonymous said...

What is a free gift ? Aren't all gifts free?

Anonymous said...

Ever notice how fast Windows runs? Neither did I.

Anonymous said...

Good job!

Anonymous said...

Suicidal twin kills sister by mistake!

Anonymous said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

Anonymous said...

Nice Article.

Anonymous said...

What is a free gift ? Aren't all gifts free?

Anonymous said...

Lottery: A tax on people who are bad at math.

Anonymous said...

Hello all!

Anonymous said...

All generalizations are false, including this one.

Anonymous said...

Nice Article.

Anonymous said...

Give me ambiguity or give me something else.

Anonymous said...

Oops. My brain just hit a bad sector.

Anonymous said...

I don't suffer from insanity. I enjoy every minute of it.

Anonymous said...

The gene pool could use a little chlorine.

Anonymous said...

640K ought to be enough for anybody. - Bill Gates 81

Anonymous said...

Calvin, we will not have an anatomically correct snowman!

Anonymous said...

640K ought to be enough for anybody. - Bill Gates 81

Anonymous said...

Wonderful blog.

Anonymous said...

Clap on! , Clap off! clap@#&$NO CARRIER

Anonymous said...

black mold exposure,
black mold symptoms of exposure,

wrought iron garden gates,
your nest iron garden gates, here,

hair styles for fine thin hair,
search hair styles for fine thin hair,

night vision binoculars,
buy, night vision binoculars,

lipitor reactions,
lipitor reactions,


luxury beach resort in the philippines,
beach resort in the philippines,

homeopathy for baby eczema.,
homeopathy for baby eczema.,

save big with great mineral makeup bargains,
companies marketing mineral makeups,

prodam iphone praha,
Apple prodam iphone praha,

Anonymous said...

buy viagra now 2007 viagra hmo viagra pills uk viagra sales viagra australia viagra for sale without a prescription viagra soft tabs viagra australia viagra attorneys how does viagra work videos viagra viagra faq women taking viagra viagra generic soft tab

Anonymous said...

[url=http://rastimores.net/][img]http://rastimores.net/img-add/euro2.jpg[/img][/url]
[b]place to buy dreamweaver, [url=http://rastimores.net/]Standart Edition Mac Retail[/url]
[url=http://akreoplastoes.net/][/url] discount on software for discount software com
adobe acrobat distiller 9 closes [url=http://akreoplastoes.net/]cheap oem software[/url] store integration software
[url=http://akreoplastoes.net/]software volume discount[/url] nero 9 special
[url=http://rastimores.net/]microsoft software service[/url] cheap software with
2009 software purchase [url=http://akreoplastoes.net/]ms office 2003 key[/url][/b]

Anonymous said...

[url=http://sapresodas.net/][img]http://vioperdosas.net/img-add/euro2.jpg[/img][/url]
[b]to buy microsoft software in, [url=http://vioperdosas.net/]free adobe photoshop cs3 trial download[/url]
[url=http://sapresodas.net/]kaspersky internet security 2009 wrong application na[/url] software at discounted cheapest software for
software biz reseller [url=http://sapresodas.net/]teacher discount software[/url] buy photoshop from
[url=http://vioperdosas.net/]buy retail software[/url] install eye toy for windows vista
[url=http://vioperdosas.net/]medical office billing software[/url] Suite X4 Retail Price
adobe photo editor software [url=http://sapresodas.net/]crack coreldraw 12 trial[/url][/b]

Anonymous said...

Yesterday i bought viagra in [url=http://shoppharm.com]Online drugstore[/url].
On my surprise it works excellent! All the matter is that the price low, because I do not pay for the trade mark. That's all!
You can see explanations about it.
A generic drug (generic drugs, short: generics) is a drug which is produced and distributed without patent protection. According to the U.S. Food and Drug Administration, generic drugs are identical bioequivalent range to the brand name counterpart with respect to pharmacokinetic and pharmacodynamic properties. By extension, therefore, generics are considered identical in dose, strength, route of administration, safety, efficacy, and intended use. In most cases, generic products are available once the patent protections afforded to the original developer have expired. When generic products become available, the market competition often leads to substantially lower prices for both the original brand name product and the generic forms. You can read more at http://shoppharm.com