Using final for ctor and setter arguments

Tor Norbye has a nice discussion on the use of final for constructor and setter arguments here. I couldn’t agree more with Tor on this. I’ve been coding like this for more than a year now. I actually use final in many places now that never occurred to me before:

  • On local variables that shouldn’t change.
  • On method parameters (almost always).
  • On variables representing constants (or course!).

I’ve lost count of the number of times this trick has saved me. It reminds me of my old C/C++ days when people were always getting caught by code like this:

if (myVar = 0)

This, of course, is not only always false but also destroys the current value of myVar. I realized that my if statements frequently contained a literal value and trained myself to code the above like this:

if (0 = myVar)

which, of course, caused a compile error making me catch my mistake of using = rather than == before my code got to the test stage (or later).

Of course Java protects us from foolishness like the above but, as Tor points out, it is still possible to step on your own foot.

I first stumbled on how useful (and efficient) final could be reading Hardcore Java by Robert Simmons, Jr. I would recommend this book to you based on the discussion of final alone.

Anyway, nice job Tor, if you’d only learn how to line up your curly braces we’d be totally on the same page. šŸ™‚


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: