Wednesday, February 9, 2005

Inheriting javadoc comments

WARNING: This blog entry was imported from my old blog on (which used different blogging software), so formatting and links may not be correct.

I just learned something new - which I thought I would share.

I always avoid having javadoc comments on methods which implement an interface method. I add a full comment in the interface, explaining the method, its parameters and its return value. However, in the implementation class, I leave out the javadoc completely. That ensures that javadoc will copy the description from the interface instead, which in turn ensures that the comment is accurate since I only have to maintain it in one place. (Had I copied it in when I first implemented the method, and then later changed the description, the implementation copy would go stale. And yes, I've made that mistake in the past...)

This scheme works fairly well, but there are times when I want to add additional comments to the implementing method. For example, adding additional notes useful to clients calling this specific implementation of the interface. When I've done this, I've only included the specific documentation for this method, and then I refer to the interface method itself for the full method description. This is clearly not a good solution either, because when you view the documentation in an IDE javadoc popup, for example, it doesn't include the basic comment which is often more important than the supplemental information.

Well, it turns out there's a way to get javadoc to include the parent documentation, and you can surround it with your own specific comments! Just use "{@inheritDoc} " inside the documentation somewhere, and it will include the super documentation:

* {@inheritDoc}
* <p>
* For this specific implementation of the interface, you're better off
* calling the more efficient {@link foo} method, provided you have the
* additional arguments!
* </p>

More information on this can be

found here

@inheritDoc is available as of JDK1.4. In JDK 5 there's another cool tag to use as well
(thanks to Peter von der Ahé, Mr. Javac,
who's sitting next to me here in the Prague office, for pointing this one out to me.)
Use the @code tag to include code samples inline in the javadoc. No more needing to
escape all < and > characters in the javadoc comment as &lt; and &gt; !
And there was much rejoicing...

1 comment:

  1. Many thanks, I've got a lot of interfaces and implementations thereof, it would be very nice indeed not to have to keep things manually sync'ed.