Previous Page TOC Index Next Page

Chapter 37

Java documentation

The bane of any software developer’s existence is embodied by a seemingly innocuous word: documentation. The old coder’s war cry, “If it was hard to write, it should be hard to read and use,” has no doubt been heard by some readers. Part of this general malaise can be attributed to the sometimes disjointed methods by which software documentation is created—an awkward cycle of creating code, commenting, extracting comments (if any in the first place), formatting in perhaps a word-processing package, preparing, and finally distributing it internally.

However, on some operating systems such as UNIX, editors exist that can be taught to perform such tasks (for example, the ubiquitous Emacs). While useful, such an approach always is parochial. There are no defined standards for commenting C++, C, or even Smalltalk code in a universally understood manner. Code documentation generally remains a weak point of the overall development process, because any code base that requires no maintenance probably is not useful anymore, and any maintenance effort is hampered by poor, incomplete, or missing documentation.

The developers of Java, however, decided to address such issues. It is possible with Java to add code commentary and produce documentation simultaneously and painlessly. Additionally, documentation can be released with Java products, eliminating the time lag between software and its accompanying explanatory text. The Java API documentation is itself generated from the Java class library source code and is copiously hypertext-linked, indexed, and presented attractively. With Java, it might even be possible, in some small way, to actually enjoy this process! We shall explore some of the rationale behind good documentation, the Java tools available for documentation, and metrics that can be used to measure what is finally produced in this chapter.

Documentation: Why Bother?

As mentioned, documentation still is a relatively thorny and unpopular issue. In an attempt to soothe any qualms you might have, we are going to lay out some reasons why you should document your code, and document it well.

Five Reasons to Document

There are more than five reasons to document, but here is a selection of some of the more compelling ones:

Guidelines for Successful Java Documentation

Because you made it this far, we hope that you might also be interested in some guidelines that have proven useful empirically over the course of a number of mostly object-oriented projects. These guidelines, however, are for the most part paradigm- and language-independent. They are offered to augment the basic Java facilities for documentation.

Table 37.1. Sample variable naming scheme for Java.

Variable Prefix Meaning Example
I Integer variable iNumberOfEvents
l Long integer lNumberOfEvents
f Floating-point variable fNumberOfStars
d Double variable dNumberOfNebulae
c Character cSmallCharacter
s String or string buffer sLabel
t Thread tAnimationThread
rReference to variable (all variables in Java) rMemberFunction
x An exception xIoException
b Boolean bMorePages

The javadoc Utility

The thrust of this chapter is to encourage the use of the javadoc utility as a useful aid during software development. This section covers the use of HTML as a help system, navigating the generated documentation such as the Java API documents, the tags used to mark up code, and the command-line usage of javadoc itself.

HTML as a Help System

Although it seems the obvious choice as a supporting help system for a web programming language, HTML actually offers certain advantages as an API help system. Some are obvious, such as general formatting, graphics inclusion, hypertext linking, and the ability to link to remote sites through the general web structure. Other less obvious advantages include portability, symmetry with one of the intentions of Java (architectural neutrality), and the ability to recite the whole document structure without comprising the links therein (in the case of javadoc-generated documentation). The advantage of portability is sort of obvious, but you can see its value when trying to use an RTF or Windows help file under Solaris.

Navigating the javadoc-Generated Documentation

The HTML documentation that composes the Java API was generated using the javadoc utility with a few exceptions edited by hand that will be discussed later. A discussion of the underlying structure of these documents—a separately obtainable part of the Java Development Kit—and their navigation covers both the online documentation and your own documentation in one fell swoop. In the text that follows, <directory> represents the base directory into which you uncompressed the API documentation. After a little while, you may begin to wonder why there is no applet content in the generated pages—as it would not have been difficult to include it.

API User’s Guide Entry Screen

Figure 37.1 shows the first screen that you will see when perusing the Java API User’s Guide.

figure FIGURE 37.1.

The opening screen for the API User's Guide.

Figure 37.1 is the file <directory>/api/API_users_guide.html, the HTML document that is the entryway to the user’s guide. Click the top hypertext link, Java API, to progress to the next page, as shown in Figure 37.2.

Figure FIGURE 37.2.

The package index document, showing the applet packages and others.

This file, located in <directory>/api/Packages.html, has been manually edited post production. Each package as listed corresponds to those present in the java.* and sun.tools.debug packages. Each of these packages is a hypertext link to the classes, interfaces, exceptions, and errors of that package. So, by clicking the java.awt link, you would see Figure 37.3.

Figure FIGURE 37.3.

The java.awt package API document.

Figure 37.3, <directory>/api/Package-java.awt.html), contains a number of interesting navigational features. As you can see, the document is partitioned into a number of indexes, asfollows:

At the top of the document, you will see the following links:

Figure FIGURE 37.4.

Class hierarchy document tree.html.

Figure FIGURE 37.5.

Index document AllNames.html.

Class Document

Each class in a package will have its documentation present in a file called <fully qualified class name>.html, where <fully qualified class name> denotes a full package name specification. Each file has a common structure consisting of the following:

To also aid in navigation, the top of the document has hypertext links that enable you to jump to the following:

All of these document types have been covered in previous sections. Figure 37.6 shows the top of the java.awt.Panel class page.

Figure FIGURE 37.6.

The AWT Panel class help page, java.awt.Panel.html.

javadoc Markup

We have mentioned already that documentation generation is achieved by executing the javadoc utility. However, we have only briefly touched upon the fact that a tag-marking scheme is required for source code files to be suitable candidates for parsing. This section covers all of the details regarding this text markup, and reiterates some of the ways in which you can enhance the basic javadoc scheme.

NOTE
Even though javadoc will generate linked and attractive documentation, it is not a substitute for well-written comments.

The command-line usage of javadoc is covered later.

What Documentation javadoc Will Generate

Documentation can be generated for the following:

Note that only text will be generated for public and protected aspects of objects. This is in accordance with the basic object-oriented principle of encapsulation—a human API browser should not be aware necessarily of the internals of class, for example. Do not take this as a method to avoid documenting implementations, though!

Embedding HTML Sequences

Virtually any of the standard HTML tags can be embedded inside source text for eventual inclusion into the generated documents. Common sense dictates (as does Sun Microsystems) that formatting tags, anchors, lists, horizontal rulers, and other tags might interfere with the documents that are produced by javadoc. It is a reasonably good way of adding some extra information in a visually striking way, though—such things are best determined empirically.

Available Tags

The following table defines each currently available tag, its scope, and associated semantics. Note that they are only significant when enclosed by the special comment-opening characters /** and closing characters */ (like a fancy C comment, really). The semantics are expanded later along with some code examples. (Note: The letters fq in the following table are an acronym for fully qualified.)

Table 37.2. Defined javadoc markup tags.

Tag/string Scope Semantics
@see classname Class See also” hypertext link to the class specified
@see fq-classname Class Hyperlinked “see also” entry
@see fq-classname#method-name Class Hyperlinked “see also” entry to the method in the given class
@version version text Class “Version” entry
@author author Class Creates an “Author” entry
@see classname Variable “See also” hypertext link to the named class
@see fq-classname Variable Hyperlinked “see also” entry to the given class
@see fq-classname#method-name Variable Hyperlinked “see also” entry to the method in the named class
@param parameter-name description Method Parameter specification for the “Parameters” section
@return description Method “Returns” section, specifying the return value
@exception fq-class-name description Method “Throws” entry, which contains the name of the exception that might be thrown by the method

There are some conditions that apply to the use of tags, and they are as follows:

Class Comment Example

A class comment is arguably the most important you can make! Be sure to include a general description of the intent, general behavior, version, authors—perhaps including some of the look ahead tokens for version control, date, and any reference to related classes. Listing 37.1 shows a rather short class comment.

//=================================================================================

/**

 * This class is part of a subsystem to parse a configurable grammar token stream

 * using various recovery schemes, as detailed in the specification, under section

 * 2.3, Finite State Machine recovery. An internally-mounted Web page 

 * <A HREF=http://ow:8080/specifications/parser/fsmrecov2.3>details this</a>. 

 * <br>

 * @see org.parser.fsm for the finite state machine details

 * @see java.io.InputStrean for the protocol our token stream adheres to

 * @author T Beveridge

 * @Author Natasha Brown

 * @version 12/10/95, 1.00 

*/

//=================================================================================

class StackedTokenStream extends org.tokenStream implements Runnable {

Note the placement of comment lines and text. There also are some extra features here, in that we have included our own hypertext reference to a specification document on our internal web server. The use of the <br> tag also inserts an empty line for neatness. Multiple tags have been used to reflect the two authors of the class, and our version details will show as a date followed by our own version number.

Method Comment Example

Remember that only public or protected methods will have documentation created. It is, of course, your decision whether to include comments for private methods, but for all except the most trivial (such as accessors), it is good software engineering practice to include comments.

TIP
javadoc takes the first sentence of a method comment and uses it for the index entry. Therefore, it is a good idea to make this sentence descriptive. For a constructor, rather than having, “Constructor. Taking X arguments…”, use, “Constructor taking X arguments, …”.

Describing parameters is helpful in Java, because there is no syntactic means of ascribing the C++ concept of ascribing state constancy to a parameter; this even though some parameters might never be modified when used by the method. The description of exceptions also is excellent practice because they will either have to be caught by your client’s code, caught and re-thrown, or passed on. Listing 37.2 illustrates a helpful method comment.

//=================================================================================

/**

 * This method determines if the Finite State Machine is in one of the 2  

 * (desirable) states given. The StringBuffer parameter is the only one of the 3  

 * that may change during the execution of this call. Note that this method may 

 * become private, so it may be a good idea to avoid it ! <br>

 * Has not been modified for some considerable time so could be considered stable 

 * (or obsolete).<br> @param rStateOne  An instance of FsmState. The order is 

 * irrelevant @param rStateTwo  An instance of FsmState. The order is irrelevant

 * @param rStrBuffer <b>volatile</b> This wil be updated during this call with the 

 * state actually encountered if this function returns true

 * @return true if one of the two states has been encountered ; false (!) otherwise

 * @exception java.io.IOException Thrown when the Fsm delegator attempts to fetch a

 * token and fails. Unusual

 * @exception org.exceptions.FsmDead Thrown when the Finite State Machine is in a 

 * GC’ablestate.

*/

//=================================================================================

protected boolean duplexState(FsmState rStateOne, FsmState rStateTwo, StringBuffer ÂrStrBuffer) {

          if (bTerminated)

              throw new org.exceptions.FsmDead(“FSM: Dead state entered”);

Again, note the inclusion of <br> tags to introduce blank lines and the use of a boldface “volatile” comment on the rStrBuffer description to indicate its potential value change.

Variable Comment Example

Because only the comments of protected and public variables are candidates for documentation inclusion, you might not see many of these. They seem to appear mainly for FINAL variables, which are really just a Java method for introducing constant values. Remember that variable comments for javadoc can only contain @see directives. Listing 37.3 shows a sample variable comment.

//=================================================================================

/**

 * This boolean variable holds our live/dead status. It is held to be true through

 * out the useful life of the Finite State Machine, being rendered false only when 

 * the associated token stream is in error or throws an exception.

 * @see org.io.streams.StackedTokenStream

*/

//=================================================================================

protected boolean bTerminated;

Generating Documentation

Now we cut to the chase. We will discuss how to generate your documentation, where it can reside, platform differences, and errors that can occur.

javadoc: Command-Line Usage

javadoc is just about the simplest utility in the JDK. The syntax is as follows:

javaDoc [options] {Package Name or File Name}.........

Available options are as follows:

-d <directory>

This instructs javadoc to redirect output to <directory>. The default is the current directory.

-classpath     

This allows the specification of a classpath. It is the same as javac and overrides the CLASSPATH environment variable.

-verbose     

This instructs javadoc to print a list of files loaded during execution. From JDK Beta 2, this might include files loaded from a ZIP file.

Measuring Your Documentation Quality

javadoc certainly is a tremendous help when it comes to automating the sometimes arduous task of creating software documentation. One aspect it does not cover is that of quality. This section attempts to provide some heuristics that can be applied to determine if the documents you are producing are worthy of a readership. Please note that a subset of this information also is included in the book Object Oriented Software Metrics by Mark Lorenz and Jeff Kidd, which is a recommended read for those interested in object-oriented metrics.

The list that follows presents metrics that you might consider adopting:

Currently, there is no way in Java to automate this process of documentation-quality measurement. However, if you avail yourself of the Beta 2 source code and adhere to the source license agreement, it would be possible to modify the javadoc source code to incorporate such abilities. This will at least give you timely statistics on quality automatically if you require them. The javadoc source code itself is in the package java.tools.javadoc.

Summary

This summary presents some possible improvements in javadoc—though not exhaustively—and a final endorsement of its use.

Potential Improvements

As with all tools, there always are improvements that could be made. Some of the more interesting ones include the following:

This chapter has shown that javadoc is a simple and reasonably effective tool for generating API documentation quickly and effectively. Used properly, it can create useful documents to aid the users of packages. It is recommended.


Previous Page TOC Index Next Page