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? ...
Dave Johnson
in Java
• 🕒 02:49PM Aug 12, 2003
Tags:
Java
Posted by PaulRivers on August 13, 2003 at 02:49 AM EDT #
Posted by Chris Nokleberg on August 14, 2003 at 04:43 AM EDT #