Default method implementations aren't so bad!
Goal for this year: Stop coming up with complicated solutions to simple problems :-)
I guess I should have dwelt on the problem further before blogging about it (though some feedback has helped!) Certainly for the problem described, having a default method implementation is not so bad, and perhaps I was too quick to suggest a complicated solution.
However, given that it is very easy in Java to miss the fact that a method had not been declared as final, I strongly believe you should at least comment such methods indicating that you expect subclasses to over-ride them and possibly even pointing out the consequences of doing so (See Joshua Bloch's item 15: "Design and document for inheritance or else prohibit it").
I guess I should have dwelt on the problem further before blogging about it (though some feedback has helped!) Certainly for the problem described, having a default method implementation is not so bad, and perhaps I was too quick to suggest a complicated solution.
However, given that it is very easy in Java to miss the fact that a method had not been declared as final, I strongly believe you should at least comment such methods indicating that you expect subclasses to over-ride them and possibly even pointing out the consequences of doing so (See Joshua Bloch's item 15: "Design and document for inheritance or else prohibit it").
4 Comments:
You might investigate if annotations can help out in this situation. I'm exploring them, and keep thinking of new and surprising ways having build-time and run-time metadata can help. For example, you can write an annotation processor and build your classes with JDK 5's apt. You could then issue a warning for classes which fail to override the default implementation when the user adds the switch to the command-line for the extra checking.
This comment has been removed by a blog administrator.
I like the idea of using annotations, but I would instead use them to warn of non-final methods that are not annotated with something like "@nonfinal". I wonder if check-style (http://checkstyle.sourceforge.net/) can complain of non-final methods that have no Javadoc?
This is why in C# (and other .NET languages), you have to tell explicitly that methods are "virtual" (the CAN be overriden) and them in subclasses you have to say that a method with the same signature as the virtual superclass method have to is either an "override" or a "new" implementation. The default is to be "new", but warns are issued by the compiler, so that you can figure your real intention.
The Metadata idea, from another comment, can be taylored to give such behaviour with Java 5 and up...
Post a Comment
<< Home