Oct 1, 2007

How to write javadoc

My personal opinion how to write good javadocs (with examples from jdk)

Overview of method/class

Goal of method/class ? What is goal of class. Example:
* The <code>String</code> class represents character strings. All
* string literals in Java programs, such as <code>"abc"</code>, are
* implemented as instances of this class.

Responsibility of method/class ?What method/class is doing. Example in code above.

Action of method ?What statements we can make about how goal is achieved ? Example in StringBuffer class.
/**
* Ensures that the capacity of the buffer is at least equal to the
* specified minimum.
* If the current capacity of this string buffer is less than the
* argument, then a new internal buffer is allocated with greater
* capacity. The new capacity is the larger of:
* <ul>
* <li>The <code>minimumCapacity</code> argument.
* <li>Twice the old capacity, plus <code>2</code>.
* </ul>
* If the <code>minimumCapacity</code> argument is nonpositive, this
* method takes no action and simply returns.
*
* @param minimumCapacity the minimum desired capacity.
*/
public synchronized void ensureCapacity(int minimumCapacity) {

And, of course, describe boundary situations carefully.

Preconditions of method:

Some special agreement then it's legal to apply method/class, example:
* @param s a <code>String</code> containing the <code>int</code>
* representation to be parsed

It's not necessary must be placed in params, but it's good to have such statement. ;)

Postconditions of method:

What it must return if everything is ok.
* @return the integer value represented by the argument in decimal.

Exceptions documentation:

Please don't provide javadoc like "throws Exception if something goes wrong", it has no information in it.
Good Example is:
* @exception NumberFormatException if the string does not contain a
* parsable integer.

CRC description of class

Class javadoc is good then it contains Overview of class, it's responsibilities, classes it coolaborates with, and brief description of working logic and purpose. Example from Timer class.
/**
* A facility for threads to schedule tasks for future execution in a
* background thread. Tasks may be scheduled for one-time execution, or for
* repeated execution at regular intervals.

Examples of use helps a lot sometimes.

Links:

java.sun.com/j2se/javadoc/writingdoccomments/

alistair.cockburn.us/index.php/Structuring_use_cases_with_goals

en.wikipedia.org/wiki/Design_by_contract