Comments Conventions
Java Comments
Introduction
Comments should be used to provide additional information which is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.
Discussion of nontrivial or not really obvious design decisions is appropriate, but avoid duplicating information that is present in the code. In general, avoid any comments that are likely to get out of date as the code evolves.
Java programs can have two kinds of comments: implementation comments and documentation comments.
- Implementation comments are those found in C++, which are delimited by /* ... */ and //.
- Documentation comments are meant to describe the specification of the code, from an implementation-free perspective to be read by developers who might not necessarily have the source code at hand. Documentation comments are Java-only, and are delimited by /** ... */. These comments can be extracted to HTML files using the JavaDoc tool.
Implementation Comments
Implementation comments are means for commenting out code or for comments about the particular implementation.
Comments should not be enclosed in decorative large boxes drawn with asterisks or other characters. Also avoid special characters such as tabs and new lines.
 | Note
The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer. |
Beginning comments
All source files should begin with a comment that lists the copyright notice. See rule JAD_002: Provide A Correct File Comment For A File (High)
.
/*
* Copyright notice
*
*/
Documentation Comments
What Is JavaDoc?
The JavaDoc tool parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing the public and protected classes, nested classes, interfaces, constructors, methods, and fields. You can use it to generate the API documentation or the implementation documentation for a set of source files.
You can run the JavaDoc tool on entire packages, individual source files, or both.
Format Of A Document Comment
A doc comment is written in HTML and must precede a class, field, constructor or method declaration. It is made up of two parts: a description followed by block tags. In this example, the block tags are @param, @return and @see.
For example:
/**
* Returns an Image object that can then be painted on the screen.
* The URL argument must specify an absolute {@link URL}. The name
* argument is a specifier that is relative to the url argument.
* <p>
* This method always returns immediately, whether or not the
* image exists. When this applet attempts to draw the image on
* the screen, the data will be loaded. The graphics primitives
* that draw the image will incrementally paint on the screen.
* <p>
*
* @param url an absolute URL giving the base location of the image
* @param name the location of the image, relative to the url argument
* @return the image at the specified URL
* @see Image
*/
public Image getImage(URL url, String name) {
}
- The first line starts with the document-comment delimiter /**.
- Starting with Javadoc 1.4, the leading asterisks are optional.
- Each line above is indented to align with the code below the comment.
- Write the first sentence as a short summary of the method, as JavaDoc automatically places it in the method summary table and index.
- If you have more than one paragraph in the doc comment, separate the paragraphs with a <p> paragraph tag, as shown.
- Insert a blank comment line between the description and the list of tags, as shown above. There is only one description block per comment; you cannot continue the description following block tags.
- The last line contains the end-comment delimiter */. The end document comment contains only a single asterisk.
- Lines won't wrap, limit any document comment line to 80 characters. See rule JAC_004: Do Not Make A Line Longer Than 120 Characters (Normal)
.
 | Tip
You can always use Jalopy, an open source code formatter for the Sun Java programming language. It layouts any valid Java source code according to configurable rules. You can download an IDE plug-in from http://jalopy.sourceforge.net/index.html . |
Tag Comments
The rule JAD_003: Provide A JavaDoc Comment For A Class (Enforced)
checks whether JavaDoc comments are provided for classes, interfaces, methods and attributes. In the list below you'll find the required and optional JavaDoc tags.
@author (Required)
Adds an Author entry with the specified name-text to the generated JavaDocs.
You can provide one or multiple @author tags. For example:
/**
* ...
*
* @author firstName lastName - companyName
*/
 | Note
You need to use the JavaDoc option -author to get the author information in the generated JavaDocs. |
@version (Required)
This JavaDoc tag adds a Version subheading with the specified version-text-date to the generated docs
This tag is intended to hold the current version number of the software that this code is part of and the date from the last source check-in.
The version-text-date has no special internal structure but is dependent on the used versioning system. Below you can find an example for CVS:
/**
* ...
*
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
 | Note
You need to use the JavaDoc option -version to add the version information in the generated JavaDocs. |
@param (Required)
Adds a parameter to the Parameters section. The description may be continued on the next line. This tag is valid only in a doc comment for a method or constructor.
The @param tag is followed by the name (not data type) of the parameter, followed by a description of the parameter. By convention, the first noun in the description is the data type of the parameter. (Articles like a, an and the can precede the noun.) An exception is made for the primitive int where the data type is usually omitted.
Additional spaces can be inserted between the name and description so that the descriptions line up in a block. Dashes or other punctuation should not be inserted before the description, as the Javadoc tool inserts one dash.
Parameter names are lowercase by convention. The data type starts with a lowercase letter to indicate an object rather than a class. The description begins with a lowercase letter if it is a phrase (contains no verb), or an uppercase letter if it is a sentence. End the phrase with a period only if another phrase or sentence follows it.
For example:
/**
* ...
*
* @param c the character to be tested
* @param observer the image observer to be notified
*/
Do not bracket the name of the parameter after the @param tag with <code>...</code> since Javadoc 1.2 and later automatically do this. (Beginning with 1.4, the name cannot contain any HTML, as Javadoc compares the @param name to the name that appears in the signature and emits a warning if there is any difference.)
@return (Required)
Adds a Returns section with the description text. This text should describe the return type and permissible range of values. This tag is valid only in a doc comment for a method.
Having an explicit @return tag makes it easier for someone to find the return value quickly. Whenever possible, supply return values for special cases (such as specifying the value returned when an out-of-bounds argument is supplied).
@throws (Required)
A @throws tag should be included for any checked exceptions (declared in the throws clause), as illustrated below, and also for any unchecked exceptions that the caller needs to be aware of (for example java.lang.IllegalArgumentException).
/**
* ...
*
* @throws IOException If an input or output exception occurred
*/
public void bar() throws IOException {
}
/**
* ...
*
* @throws IllegalArgumentException If <code>name</code> is <code>null</code>
*/
public void setName(String name) {
if (name == null) {
throw new IllegalArgumentException("name can not be null");
}
}
 | Tip
Multiple @throws tags should be listed alphabetically by the exception names. |
 | Tip
Add multiple @throws tags for the same exception if it can be thrown under different circumstances intead of describing all circumstances in a single @throws tag. |
@see (Optional)
Adds a See Also heading with a link or text entry that points to reference. A doc comment may contain any number of @see tags, which are all grouped under the same heading.
In the example below an @see tag refers to the equals method in the String class. The tag includes both arguments: the name String#equals(Object) and the label equals.
/**
* ...
*
* @see String#equals(Object) equals
*/
The standard Doclet produces HTML something like this:
<dl>
<dt><b>See Also:</b>
<dd><a href="../../java/lang/String#equals(java.lang.Object)">
<code>equals<code></a>
</dl>
@deprecated (Optional)
Adds a comment indicating that this API should no longer be used (even though it may continue to work). The Javadoc tool moves the deprecated-text ahead of the main description, placing it in italics and preceding it with a bold warning: Deprecated. This tag is valid in all doc comments: overview, package, class, interface, constructor, method and field.
The @deprecated description in the first sentence should at least tell the user when the API was deprecated and what to use as a replacement. Only the first sentence will appear in the summary section and index. Subsequent sentences can also explain why it has been deprecated.
/**
* ...
*
* @deprecated As of JDK 1.1, replaced by #setBounds(int,int,int,int)}
*/
A JavaDoc Comments Example
/**
* Graphics is the abstract base class for all graphics contexts
* which allow an application to draw onto components realized on
* various devices or onto off-screen images.
* A Graphics object encapsulates the state information needed
* for the various rendering operations that Java supports. This
* state information includes:
* <ul>
* <li>The Component to draw on
* <li>A translation origin for rendering and clipping coordinates
* <li>The current clip
* <li>The current color
* <li>The current font
* <li>The current logical pixel operation function (XOR or Paint)
* <li>The current XOR alternation color
* (see <a href="#setXORMode">setXORMode</a>)
* </ul>
* <p>
* Coordinates are infinitely thin and lie between the pixels of the
* output device.
* Operations which draw the outline of a figure operate by traversing
* along the infinitely thin path with a pixel-sized pen that hangs
* down and to the right of the anchor point on the path.
* Operations which fill a figure operate by filling the interior
* of the infinitely thin path.
* Operations which render horizontal text render the ascending
* portion of the characters entirely above the baseline coordinate.
* <p>
* Some important points to consider are that drawing a figure that
* covers a given rectangle will occupy one extra row of pixels on
* the right and bottom edges compared to filling a figure that is
* bounded by that same rectangle.
* Also, drawing a horizontal line along the same y coordinate as
* the baseline of a line of text will draw the line entirely below
* the text except for any descenders.
* Both of these properties are due to the pen hanging down and to
* the right from the path that it traverses.
* <p>
* All coordinates which appear as arguments to the methods of this
* Graphics object are considered relative to the translation origin
* of this Graphics object prior to the invocation of the method.
* All rendering operations modify only pixels which lie within the
* area bounded by both the current clip of the graphics context
* and the extents of the Component used to create the Graphics object.
* <p>
*
* @author Sami Shaio - SunMicrosystems
* @author Arthur van Hoff - SunMicrosystems
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public abstract class Graphics {
/**
* Draws as much of the specified image as is currently available
* with its northwest corner at the specified coordinate (x, y).
* This method will return immediately in all cases, even if the
* entire image has not yet been scaled, dithered and converted
* for the current output device.
* <p>
* If the current output representation is not yet complete then
* the method will return false and the indicated {@link ImageObserver}
* object will be notified as the conversion process progresses.
*
* @param img the image to be drawn
* @param x the x-coordinate of the northwest corner of the
* destination rectangle in pixels
* @param y the y-coordinate of the northwest corner of the
* destination rectangle in pixels
* @param observer the image observer to be notified as more of the
* image is converted. May be <code>null</code>
* @return <code>true</code> if the image is completely
* loaded and was painted successfully;
* <code>false</code> otherwise.
* @see Image
* @see ImageObserver
*/
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer);
/**
* Dispose of the system resources used by this graphics context.
* The Graphics context cannot be used after being disposed of.
* While the finalization process of the garbage collector will
* also dispose of the same system resources, due to the number
* of Graphics objects that can be created in short time frames
* it is preferable to manually free the associated resources
* using this method rather than to rely on a finalization
* process which may not happen for a long period of time.
* <p>
* Graphics objects which are provided as arguments to the paint
* and update methods of Components are automatically disposed
* by the system when those methods return. Programmers should,
* for efficiency, call the dispose method when finished using
* a Graphics object only if it was created directly from a
* Component or another Graphics object.
*
* @see #create(int, int, int, int)
* @see #finalize()
* @see Component#getGraphics()
* @see Component#paint(Graphics)
* @see Component#update(Graphics)
*/
public abstract void dispose();
/**
* Disposes of this graphics context once it is no longer referenced.
*
* @see #dispose()
*/
public void finalize() {
}
}
Documentation Checking Tool
Sun has developed a tool for checking JavaDoc comments, called the Sun Doc Check Doclet, or DocCheck. You run it on your source code and it generates a report describing what style and JavaDoc errors the comments have, and recommends changes.
You can download a free copy of the DocCheck tool from [http://java.sun.com/j2se/javadoc/doccheck/index.html}.
The DocCheck report
The DocCheck report contains the following parts:
- The executive summary shows the number of missing comments and the percentage for package groups (e.g. java.awt.*). Also shows the number of minor errors for packages that have no major comment errors.
- The package summary shows the number of missing comments and the number of minor errors, along with percentages by package.
- The package statistics shows the kinds of errors found in each package, the number and kind of items that were inspected (classes, methods, etc.), and provides a statistical breakdown of the errors.