CONTENTS | PREV | NEXT | Java Code Conventions |
Programs can have four styles of implementation comments: block, single-line, trailing and end-of-line.
Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments should be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe.A block comment should be preceded by a blank line to set it apart from the rest of the code. Block comments have an asterisk "*" at the beginning of each line except the first.
/*
* Here is a block comment.
*/
Block comments can start with /*-, which is recognized by indent(1) as the beginning of a block comment that should not reformatted. Example:
/*
* Here is a block comment with some very special
* formatting that I want indent(1) to ignore.
*
* one
* two
* three
*/
Note - If you don't use indent(1), you don't have to use /*- in your code or make any other concessions to the possibility that someone else might run indent(1) on your code.
See also "Comments in Java Code" on page 14.
Short comments can appear on a single line indented to the level of the code that follows. If a comment can't be written in a single line, it should follow the block comment format (see section 3.1.1). A single-line comment should be preceded by a blank line. Here's an example of a single-line comment in Java code (also see "Comments in Java Code" on page 14):
if (condition) {
/* Handle the condition. */
...
}
Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. Avoid the assembly language style of commenting every line of executable code with a trailing comment.Here's an example of a trailing comment in Java code (also see "Comments in Java Code" on page 14):
if (a == 2) {
return TRUE; /* special case */
} else {
return isprime(a); /* works only for odd a */
}
The // comment delimiter begins a comment that continues to the newline. It can comment out a complete line or only a partial line. It shouldn't be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow:
if (foo > 1) {
// Do a double-flip.
...
}
else
return false; // Explain why here.
//if (bar > 1) {
//
// // Do a triple-flip.
// ...
//}
//else
// return false;