How to Write |
Javadoc
Home Page |
This document describes the formatting and content conventions we use in documentation comments for Java programs written at Java Software, Sun Microsystems. It concentrates on conventions and does not rehash reference material covered elsewhere in the Javadoc reference pages.
At Java Software, we have several guidelines that might make our documentation comments different than those of third party developers. Our documentation comments define the offical Java Platform API Specification. To this end, our target audience is those who write Java compatibility tests or re-implement the Java Platform, in addition to developers. We spend time and effort focused on specifying boundary conditions, argument ranges and corner cases rather than defining common programming terms, writing conceptual overviews, and including examples for developers.Thus, there are commonly two different ways to write doc comments -- as API specifications, or as programming guide documentation. These two targets are described in the following sections. A staff with generous resources can afford to blend both into the same documentation (properly "chunked"); however, our priorities dictate that we give prime focus to writing API specifications in doc comments. This is why developers often need to turn to other documents, such as the JDK Documentation, Java Tutorial or the Java Class Libraries (in hardback only) for programming guides.
Writing API Specifications
Ideally, the Java API Specification comprises all assertions required to do a clean-room implementation of the Java Platform for "write once, run anywhere" -- such that any Java applet or application will run the same on any implementation. This may include assertions in the doc comments plus those in any architectural and functional specifications (usually written in FrameMaker) or in any other document. This definition is a lofty goal and there is some practical limitation to how fully we can specify the API. The following are guiding principles we try to follow:
- The Java Platform API Specification is defined by the documentation comments in the source code and any documents reachable from those comments.
Notice that the specification does not need to be entirely contained in doc comments. In particular, specifications that are lengthy are sometimes best formatted in a separate file and linked to from a doc comment.- The Java Platform API Specification is a contract between callers and implementions.
The Specification describes all aspects of the behavior of each method on which a caller can rely. It does not describe implementation details, such as whether the method is native or synchronized. The specification should describe (textually) the thread-safety guarantees provided by a given object. In the absence of explicit indication to the contrary, all objects are assumed to be "thread-safe" (i.e., it is permissible for multiple threads to access them concurrently). It is recognized that current specifications don't always live up to this ideal.- Unless otherwise noted, the Java API Specification assertions need to be implementation-independent. Exceptions must be set apart and prominently marked as such.
We have guidelines for how to prominently document implementation differences- The Java API Specification should contain assertions sufficient to enable Software Quality Assurance to write complete Java Compatibility Kit (JCK) tests.
This means that the doc comments must satisfy the needs of the conformance testing by SQA. The comments should not document bugs or how an implementation that is currently out of spec happens to work.Writing Programming Guide Documentation
What separates API specifications from a programming guide are examples, definitions of common programming terms, certain conceptual overviews (such as metaphors), and descriptions of implementation bugs and workarounds. There is no dispute that these contribute to a developer's understanding and help a developer write reliable applications more quickly. However, because these do not contain API "assertions", they are not necessary in an API specification. You can include any or all of this information in documentation comments (and can include custom tags, handled by a custom doclet, to facilitate it). At Java Software, we consciously do not include this level of documentation in doc comments, and instead include either links to this information (links to the Java Tutorial and list of changes) or include this information in the same documentation download bundle as the API spec -- the JDK documentation bundle includes the API specs as well as demos, examples, and programming guides.It's useful to go into further detail about how to document bugs and workarounds. There is sometimes a discrepancy between how code should work and how it actually works. This can take two different forms: API spec bugs and code bugs. It's useful to decide up front whether you want to document these in the doc comments. At Java Software we have decided to document both of these outside of doc comments, though we do make exceptions.
API spec bugs are bugs are present in the method signature or in the doc comment. An example is a method that was specified to throw a NullPointerException when null is passed in, when null is really a useful parameter that should be accepted (and was even implemented that way). If a decision is made to correct the API specification, it would be useful to state that either in the API specification itself, or in a list of changes to the spec, or both. Documenting an API difference like this in a doc comment, along with its workaround, alerts a developer to the change where they are most likely to see it. Note that an API specification with this correction would still maintain its implementation-independence. The @deprecated tag is a formal way of alerting developers to API spec bugs by removing API from the specification but not from the implementation.
Code bugs are bugs in the implementation, rather than in the API specification. Code bugs and their workarounds are often likewise distributed separately in a bug report. However, if Javadoc is being used to generate documentation for a particular implementation, it would be quite useful to include this information in the doc comments, suitably separated as a note or by a custom tag (say @bug).
Who "Owns" the Doc Comments - Writers or Programmers
Here at Java Software, the doc comments are not owned exclusively by writers or programmers, but their ownership is shared between them. It is a basic premise that writers and programmers honor each other's capabilities and both contribute to the best doc comments possible. Often it is a matter of negotiation to determine who writes which parts of the documentation, based on knowledge, time, resources, interest, API complexity, and on the state of the implementation itself.Ideally, the person designing the API would write the API specification in skeleton source files, with only signatures and doc comments, filling in the implementation only to satisfy the written API contract. The purpose of an API writer is to relieve the designer from some of this work. In this case, the API designer might write the initial doc comments, using sparse language, and for the writer to review the comments, refine the content, and add tags.
If the doc comments are an API specification for re-implementors, and not simply a guide for developers, they should be written either by the programmer who designed and implemented the API, or by a API writer who is or has become a subject matter expert. If the implementation is written to spec but the doc comments are unfinished, a writer can complete the doc comments by inspecting the source code or writing programs that test the API. A writer might inspect or test for exceptions thrown, parameter boundary conditions, and for acceptance of null arguments. However, a much more difficult situation arises if the implementation is not written to spec. Then a writer can proceed to write an API specification only if they either know the intent of the designer (either through design meetings or through a separately-written design specification) or have ready access to the designer with their questions. Thus, it may be more difficult for a writer to write the documentation for interfaces and abstract classes that have no implementors.
With that in mind, these guidelines are intended to describe the finished documentation comments. They are intended as suggestions rather than requirements to be slavishly followed if they seem overly burdensome, or if creative alternatives can be found. When a complex system such as Java (which contains about 60 packages) is being developed, often a group of engineers contributing to a particular set of packages, such as javax.swing may develop guidelines that are different from other groups. This may be due to the differing requirements of those packages, or because of resource constraints.
- API documentation (API docs) or API specifications (API specs)
- On-line or hardcopy descriptions of the API, intended primarily for programmers writing in Java. These can be generated using the javadoc tool or created some other way. Examples would be the on-line JDK API docs and the Chan/Lee Java Class Libraries book.
- Documentation comments (doc comments)
- The special comments in the Java source code that are delimited by the /** ... */ delimiters. These comments are processed by the Javadoc tool to generate the API docs.
- javadoc
- The JDK tool that generates API documentation from documentation comments.
A doc comment is made up of two parts -- a description followed by zero or more tags, with a blank line (containing a single asterisk "*") between these two sections:/** * This is the description part of a doc comment * * @tag Comment for the tag */Break any doc-comment lines exceeding 80 characters in length, if possible. If you have more than one paragraph in the doc comment, separate the paragraphs with a <p> paragraph tag. Also see Troubleshooting Curly Quotes (Microsoft Word) at the end of this document.
- The first line is indented to line up with the code below the comment, and starts with the begin-comment symbol (/**) followed by a return.
- Subsequent lines start with an asterisk *. They are indented an additional space so the asterisks line up. A space separates the asterisk from the descriptive text or tag that follows it.
- Insert a blank comment line between the description and the list of tags, as shown.
- Insert additional blank lines to create "blocks" of related tags (discussed in greater detail below).
- The last line begins with the end-comment symbol (*/) indented so the asterisks line up and followed by a return. Note that the end-comment symbol contains only a single asterisk (*).
First Sentence
The first sentence of each doc comment should be a summary sentence, containing a concise but complete description of the API. This sentence ends at the first period that is followed by a blank, tab, or line terminator, or at the first tag (as defined below). For example, this first sentence ends at "Prof.":/** * This is a simulation of Prof. Knuth's MIX computer. */However, you can work around this by typing an HTML meta-character such as "&" or "<" immediately after the period, such as:/** * This is a simulation of Prof. Knuth's MIX computer. */or/** * This is a simulation of Prof.<!-- --> Knuth's MIX computer. */Javadoc copies this first sentence to the member summary at the top of the web page, so it is important to write crisp and informative initial sentences. In particular, write summary sentences that distinguish overloaded methods from each other. For example:/** * Class constructor. */ foo() { ... /** * Class constructor specifying number of objects to create. */ foo(int n) { ...Implementation-Independence
Write the description to be implementation-independent, but specifying such dependencies where necessary. This helps engineers write code to be "write once, run anywhere."
- As much as possible, write doc comments as an implementation-independent API specification.
- Define clearly what is required and what is allowed to vary across platforms/implementations.
- Ideally, make it complete enough for licensees to re-implement. Realistically, include enough description so that someone reading the source code can write a substantial suite of conformance tests. Basically, the spec should be complete, including boundary conditions, parameter ranges and corner cases.
- Where appropriate, mention what the specification leaves unspecified or allows to vary among implementations.
- If you must document implementation-specific behavior, please document it in a separate paragraph with a lead-in phrase that makes it clear it is implementation-specific. If the implementation varies according to platform, then specify "On <platform>" at the start of the paragraph. In other cases that might vary with implementations on a platform you might use the lead-in phrase "Implementation-Specific:". Here is an example of an implementation-dependent part of the specification for java.lang.Runtime
On Win32 systems, the path search behavior of the loadLibrary method is identical to that of the Win32 API's LoadLibrary procedure.The use of "On Win32" at the beginning of the sentence makes it clear up front that this is an implementation note.
The following are useful tips and conventions for writing descriptions in doc comments.
The add(int, Object) method adds an item at a specified position in this arraylist. |
The add method enables you to insert items. | (preferred) |
The add() method enables you to insert items. | (avoid when you mean "all forms" of the add method) |
Gets the label. | (preferred) |
Get the label. | (avoid) |
Gets the label of this button. | (preferred) |
This method gets the label of this button. | (avoid) |
A button label. | (preferred) |
This field is a button label. | (avoid) |
Gets the toolkit for this component. | (preferred) |
Gets the toolkit for the component. | (avoid) |
Avoid - The description below says nothing beyond what you know from reading the method name. The words "set", "tool", "tip", and "text" are simply repeated in a sentence./** * Sets the tool tip text. * * @param text The text of the tool tip. */ public void setToolTipText(String text) {Preferred - This description more completely defines what a tool tip is, in the larger context of registering and being displayed in response to the cursor./** * Registers the text to display in a tool tip. The text * displays when the cursor lingers over the component. * * @param text The string to display. If the text is null, * the tool tip is turned off for this component. */ public void setToolTipText(String text) {
Most of the following tags are specified in the Java Language Specification. Also see the javadoc reference page.Order of Tags
Include tags in the following order:Tag Blocks* @author (classes and interfaces only, required) * @version (classes and interfaces only, required) (see footnote 1) * * @param (methods and constructors only) * @return (methods only) * @exception (@throws is a synonym added in Javadoc 1.2) * @see * @since * @deprecated (see How and When To Deprecate APIs)
For readability, divide the tags into blocks of related tags. The blocks shown above are an example.Ordering Multiple Tags
We employ the following conventions when a tag appears more than once in a documentation comment. If desired, groups of tags, such as multiple @see tags, can be separated from the other tags by a blank line with a single asterisk.Multiple @author tags should be listed in chronological order. The creator of the class should be listed at the top.
Multiple @param tags should be listed in argument-declaration order. This makes it easier to match the list to the signature with your eyes.
Multiple @exception tags (also known as @throws) should be listed alphabetically by the exception names.
Multiple @see tags should be ordered as follows, which is roughly the same order as their arguments are searched for by javadoc, basically from nearest to farthest access, from least-qualified to fully-qualified, The following list shows this progression. Notice the methods and constructors are in "telescoping" order, which means the "no arg" form first, then the "1 arg" form, then the "2 arg" form, and so forth. Where a second sorting key is needed, they could be listed either alphabetically or grouped logically.
@see #field @see #Constructor(Type, Type...) @see #Constructor(Type id, Type id...) @see #method(Type, Type,...) @see #method(Type id, Type, id...) @see Class @see Class#field @see Class#Constructor(Type, Type...) @see Class#Constructor(Type id, Type id) @see Class#method(Type, Type,...) @see Class#method(Type id, Type id,...) @see package.Class @see package.Class#field @see package.Class#Constructor(Type, Type...) @see package.Class#Constructor(Type id, Type id) @see package.Class#method(Type, Type,...) @see package.Class#method(Type id, Type, id) @see packageRequired Tags
An @param tag is required for every parameter, even when the description is obvious. The @return tag is required for every method that returns something other than void, even if it is redundant with the method description. (Whenever possible, find something non-redundant (ideally, more specific) to use for the tag comment.)These principles expedite automated searches and automated processing. Frequently, too, the effort to avoid redundancy pays off in extra clarity.
Tag Comments
As a reminder, the fundamental use of these tags is described on the Javadoc Reference page. Java Software generally uses the following additional guidelines to create comments for each tag:
- @author (reference page)
- If the author is unknown, use "unascribed" as the argument to @author.
- @version (reference page)
- The Java Software convention for the argument to the @version tag is the SCCS string "%I%, %G%", which converts to something like "1.39, 02/28/97" when the file is checked out of SCCS.
- @param (reference page)
- The @param tag is followed by the name (not type) of the parameter, followed by a description of the parameter. The first non-trivial word in the description is the data type of the parameter. (Trivial words are articles like "a", "an", and "the".) Additional spaces can be inserted between the name and description so that comments line up in a block. Dashes or other punctuation should not be inserted before the description, as Javadoc inserts one dash.
The name and data type always start with a lowercase letter. The description is most usually a phrase, starting with a lowercase letter and ending without a period, unless it contains a complete sentence.Example:
* @param ch the character to be tested * @param observer the object to be notifiedDo not bracket the name of the parameter after the @param tag with <code>...</code> since Javadoc 1.2 automatically does this. (Javadoc will do the right thing and suppress inserting code tags around the parameter name if they are already present.)When writing the comments themselves:
- Prefer a phrase to a sentence.
- Giving a phrase, do not capitalize, do not end with a period.
@param x a phrase goes here- Giving a sentence, capitalize it and end it with a period.
@param x This is a sentence.- When giving multiple sentences, follow all sentence rules.
@param x This is sentence #1. This is sentence #2.- Giving multiple phrases, separate with a semi-colon and a space.
@param x phrase #1 here; phrase #2 here- Giving a phrase followed by a sentence, do not capitalize the phrase. However, end it with a period to distinguish the start of the next sentence.
@param x a phrase goes here. This is a sentence.- @return (reference page)
- Omit @return for methods that return void and for constructors; include it for all other methods, even if its content is entirely redundant with the method description. 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).
- @deprecated (reference page)
- 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. When generating the description for a deprecated API, Javadoc moves the @deprecated text ahead of the description, placing it in italics and preceding it with a bold warning: "Deprecated". An @see tag (for Javadoc 1.1) or {@link} tag (for Javadoc 1.2 or later) should be included that points to the replacement method:
- For Javadoc 1.1, the standard format is to create a pair of @deprecated and @see tags. For example:
/** * @deprecated As of JDK 1.1, replaced by setBounds * @see #setBounds(int,int,int,int) */For Javadoc 1.2, the standard format is to use @deprecated tag and the in-line {@link} tag. This creates the link in-line, where you want it. For example: /** * @deprecated As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)} */If the member has no replacement, the argument to @deprecated should be "No replacement".Do not add @deprecated tags without first checking with the appropriate engineer. Substantive modifications should likewise be checked first.
@since (reference page) Specify the product version when the name was added to the API. For example, if a member or class was added in JDK 1.2, use: /** * @since JDK1.2 */If a member changes from protected to public in a later release, the @since tag would not change, even though it is now usable by any caller, not just subclassers.@exception (@throws is a synonym added in Javadoc 1.2) (reference page) An @exception 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 might reasonably want to catch, with the exception of NullPointerException. Errors should not be documented as they are unpredictable. For more details, please see Documenting Exceptions with the @throws Tag. /** * @exception IOException If an input or output exception occurred */ public void f() throws IOException { // body }See the Exception chapter of the Java Language Specification for more on exceptions.@serial @serialField @serialData (All added in Javadoc 1.2) (reference page) For information about how to use these tags, along with an example, see "Documenting Serializable Fields and Data for a Class," Section 1.6 of the Java Object Serialization Specification.
{@link} (Added in Javadoc 1.2) (reference page) For conventions, see Use In-Line Links Economically.
This section covers images used in the doc comments, not images directly used by the source code.NOTE: The bullet and heading images required with Javadoc version 1.0 and 1.1 are located in the images directory of the JDK download bundle: jdk1.1/docs/api/images/
Prior to Javadoc 1.2, Javadoc would not copy images to the destination directory -- you had to do it in a separate operation, either manually or with a separate script. Javadoc 1.2 looks for and copies to the destination directory a directory named "doc-files" in the source tree (one for each package). Thus, you can put into this directory any images (GIF, JPEG, etc) or other files not otherwise processed by Javadoc.
The following are the Java Software proposals for conventions for including images in doc comments. The master images would be located in the source tree; when javadoc is run with the standard doclet, it would copy those files to the destination HTML directory.
Images in Source Tree
- Naming of doc images in source tree - Name GIF images "<class>-1.gif", incrementing the integer for subsequent images in the same class. Example: Button-1.gif
- Location of doc images in source tree - Put doc images in a directory called "doc-files". This directory should reside in the same package directory where the source files reside. (The name "doc-files" distinguishes it as documentation separate from images used by the source code itself, such as bitmaps displayed in the GUI.) Example: A screen shot of a button, Button-1.gif, might be included in the class comment for the Button class. The Button source file and the image would be located at:
java/awt/Button.java (source file) java/awt/doc-files/Button-1.gif (image file)
Images in HTML Destination
- Naming of doc images in HTML destination - Images would have the same name as they have in the source tree. Example: Button-1.gif
- Location of doc images in HTML destination -
- With hierarchical file output, such as Javadoc 1.2, directories would be located in the package directory named "doc-files". For example:
api/java/awt/doc-files/Button-1.gifWith flat file output, such as Javadoc 1.1, directories would be located in the package directory and named "images-<package>". For example:api/images-java.awt/ api/images-java.awt.swing/
/** * 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. * * @author Sami Shaio * @author Arthur van Hoff * @version %I%, %G% * @since JDK1.0 */ public abstract class Graphics { /** * Draws as much of the specified image as is currently available 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. * If the current output representation is not yet complete then * the method will return false and the indicated ImageObserver * object will be notified as the conversion process progresses. * * @param img the image to be drawn * @param x the x coordinate * @param y the y coordinate * @param observer the object to be notified as more of the image is * converted * @return <code>true</code> if the image is completely * loaded and was painted successfully; * <code>false</code> otherwise. * @see Image * @see ImageObserver * @since JDK1.0 */ 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 * @see #finalize * @see Component#getGraphics * @see Component#paint * @see Component#update * @since JDK1.0 */ public abstract void dispose(); /** * Disposes of this graphics context once it is no longer referenced. * @see #dispose * @since JDK1.0 */ public void finalize() { dispose(); } }
Problem - A problem occurs if you are working in an editor that defaults to curly (rather than straight) single and double quotes, such as Microsoft Word on a PC -- the quotes disappear when displayed in some browers (such as Unix Netscape). So a phrase like "the display's characteristics" becomes "the displays characteristics."The illegal characters are the following:
What should be used instead is:
- 146 - right single quote
- 147 - left double quote
- 148 - right double quote
Preventive Solution - The reason the "illegal" quotes occurred was that a default Word option is "Change 'Straight Quotes' to 'Smart Quotes'". If you turn this off, you get the appropriate straight quotes when you type.
- 39 - straight single quote
- 34 - straight quote
Fixing the Curly Quotes - Microsoft Word has several save options -- use "Save As Text Only" to change the quotes back to straight quotes. Be sure to use the correct option:
- "Save As Text Only With Line Breaks" - inserts a space at the end of each line, and keeps curly quotes.
- "Save As Text Only" - does not insert a space at the end of each lines, and changes curly quotes to straight quotes.
Footnotes
[1] At Java Software, we use @version for the SCCS version. See "man sccs-get" for details. The concensus seems to be:
Some developers omit the date %G% (and have been doing so) if they find
it too confusing (3/4/96 is ambiguous to Europeans), and include the time
%U% if they want more resolution (due to multiple check-ins in a day).
The real solution would be to have the date formatted as text (10 Oct
1996 or Oct 10 1996), but that enhancement would need to come from SCCS.
[Author's comment: Include more
comments from step 5 of: ~dkramer/javadocdir/moving-frame-into-src.html#revisproc
%I% gets incremented each time you edit and delget a file
When you create a file, %I% is set to 1.1. When you edit and delget it,
it increments to 1.2.
%G% is the date mm/dd/yy
"Manual edit the HTML files
produced by WebWorks"]
This page is hosted by the Chair for Applied Software Engineering of the Technische Universität München.
Imprint (Impressum)