[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: bindings and assignments (was: Re: continuations)



Shriram Krishnamurthi wrote:
> Two related, necessarily somewhat vague, questions:
>
> 1. What do the main Java texts/books say about this?  Do they (a)
> emphasize its existence, (b) provide useful guidelines on its use and,
> (c) most importantly, use it frequently in their own sample code so
> programmers will imbibe this discipline?

To start with, I'll point you to here:
http://www.javapractices.com/Topic23.cjp

As an in-the-trench Java programmer, I would say that most programmers know 
of the existance of this idiom. But many find it too verbose, and would not 
normally use 'final' for local variables nor parameters.

More common is the use of final for member variables of classes. This usage 
forces that member to be initialized once-and-only-once; the compiler 
complains if you forget to initialize a final member in a constructor. 
(Non-final members are initialized to null, false, 0 or 0.0 by default.)

> 2. Do practicing programmers use it much?  If, for instance, you were
> to search through your own code base, or libraries from Sun, or code
> on Alphaworks, would this appear often?  (I could search this myself,
> except that I want only this use of final, not the one for classes,
> and I don't have a Java parser handy to mock this up.)

I have worked in organisations whose coding standard mandated the use of 
final for any local-variable/parameter that was only assigned to once. 
Searching through my own code, I always make members final if they can be, 
and *some* of my code uses final for locals/parameters. I suppose I might 
be in the "final is too verbose" camp, but I don't really have any good 
reasons.

The checkstyle project (http://checkstyle.sourceforge.net/) is an example 
of a codebase that uses final in these ways:
http://cvs.sourceforge.net/cgi- 
bin/viewcvs.cgi/checkstyle/checkstyle/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java


Marking parameters as final prevents this:

class A {
   private int i;
   public foo(int i) {
      int normalized = Math.abs(i);
      i = normalized; // oops, assignment to param not member
   }
   public bar(final int i) {
      int normalized = Math.abs(i);
      i = normalized; // sytnax error, assignment to final variable
      this.i = normalized; // what we really want
   }
}


=Matt