Tags

Final declaration

April 1st, 2006

Some weeks ago I heard somewhere that calling non-final methods from ctor is a bad idea because “it leads to problems down the road”

Well yesterday I found that I needed a mere 30′ to get there…

The story in short:

  1. Start with some refactoring and encapsulate some StringBuffer hacking with a Builder.
  2. Clean up the code - it seems natural to initialize the object upon creation.
  3. Derive a special Builder thats extend the standard builder and overrides a method fromt the base-builders ctor
  4. Make the override use a member private final List vars = new ArrayList();
  5. Stare at the code at least as long as it took you to complete steps 1-4.
  6. Take yourself some minutes to explain what happened to a coworker and then decide to blog on it.

So actually - my post-mortem analysis: The call to non-finals is dangerous. It leads to problems that are beyond the reach of many programmers. Here the vars was null and this is not detected by the compiler…
Well you need this behavior sometimes - but it gets sometimes ridiculously hard to achieve this, just for the price of having an object being constructed invariably right from the beginning.

It is most of the time much easier to initialize an object explicitly. The downside of this is having this step not being checked by the compiler; a member not being final, that is only set in the init() method. If you have code-reviews in your project or write test-cases and use assertion this is normally no problem - less elegant perhaps but you replaced code with hiddeous features with code with obvious requirements.

Well, if it is not elegant, it is not worth to be done. Sometimes the control whether the “init()” is called at the right place is more difficult to find than a soltuion for the initializers. I’d call it lenient initialization stay tuned.
By the way: The greatest blunder of all was that I extended a non-abstract class, you don’t get nectarines by shaving peaches! Sometimes one is tempted to “save same time” because it is actually “not really difficult”

Leave a Reply