« WellformedWeb(TM)... | Main | Testing 123... »

Best practice or final fetish.

I work with a couple of Programming Languages geeks who are, it seems, always Scheme-ing and Smalltalking behind Java's back. One of these guys has a thing about the final key word. He believes that all fields, variables, classes, arguments, etc. should be final be default and that, instead of having a final keyword to declare immutables, Java should have a mutable keyword to declare those that may be mutated.

He argues that, wherever possible, fields, variables, classes, arguments, etc. should be declared final. Since Java does not default to final, you should default to final. Here are some advantages to this:

  • If you declare and initialize a variable final, you never have to worry about it being null later. Nobody can change it, so it will never be null.
  • Extending classes that are not carefully designed for extension, and let's face it most are not, is problematic. By mentally defaulting to final classes, you prevent potential problems.
  • If you need to declare an anonymous class, you don't need to wory about redeclaring your variables as final because you already declared them that way.
  • Other reasons? ...
My coworker is not the only one with the final fetish. Renaud Waldura is a final fan too. Brian Goetz writes that final can simplify your life, but points out that declaring classes or methods final does not make them faster.

Using final doesn't make anything faster. http://www-106.ibm.com/developerworks/java/library/j-jtp04223.html#N4000AD I assume developerworks knows what they are talking about. My humble opinion is that declaring everything is just a waste of time. Do you every really run into problems that you have to fix because someone improperly tried to subclass your class?

Posted by PaulRivers on August 13, 2003 at 02:49 AM EDT #

Making method or classes final also prevents subclassing even in cases where it is guaranteed to not cause any harm. For example, Hibernate uses CGLIB to generate lazy-loading proxies for any class (not just interfaces), which is achieved through the use of dynamically created subclasses.

Posted by Chris Nokleberg on August 14, 2003 at 04:43 AM EDT #

Post a Comment:
  • HTML Syntax: NOT allowed

« WellformedWeb(TM)... | Main | Testing 123... »


This is just one entry in the weblog Blogging Roller. You may want to visit the main page of the weblog

Related entries

Below are the most recent entries in the category Java, some may be related to this entry.