From SUN (Oracle) http://www.oracle.com/technetwork/java/index-135089.html
Code Conventions for the Java TM ProgrammingLanguage
Revised April 20, 1999
This Code Conventions for the Java Programming Language documentcontains the standard conventions that we at Sun follow and recommend thatothers follow. It covers filenames, file organization, indentation, comments,declarations, statements, white space, naming conventions, programmingpractices and includes a code example.
The Code Conventions for the Java Programming Language document wasrevised and updated on April 20, 1999.
Code conventions are important toprogrammers for a number of reasons:
For theconventions to work, every person writing software must conform to the codeconventions. Everyone.
This document reflects the Java languagecoding standards presented in the Java LanguageSpecification, from Sun Microsystems, Inc. Major contributions are fromPeter King, Patrick Naughton, Mike DeMoney, Jonni Kanerva, Kathy Walrath, andScott Hommel.
This document is maintained by ScottHommel. Comments should be sent to [email protected]
This section lists commonly used filesuffixes and names.
Java Software uses the following filesuffixes:
File Type |
Suffix |
Frequently used file names include:
File Name |
Use |
The preferred name for makefiles. We use |
|
The preferred name for the file that summarizes the contents of a particular directory. |
A file consists of sections that should beseparated by blank lines and an optional comment identifying each section.
Files longer than 2000 lines arecumbersome and should be avoided.
For an example of a Java program properlyformatted, see "Java Source File Example".
Each Java source file contains a singlepublic class or interface. When private classes and interfaces are associatedwith a public class, you can put them in the same source file as the publicclass. The public class should be the first class or interface in the file.
Java source files have the followingordering:
All source files should begin with ac-style comment that lists the class name, version information, date, andcopyright notice:
/* * Classname * * Version information * * Date * * Copyright notice */
The first non-comment line of most Javasource files is a package
statement. After that, import
statements can follow. For example:
package java.awt; import java.awt.peer.CanvasPeer;
Note: The first component of a uniquepackage name is always written in all-lowercase ASCII letters and should be oneof the top-level domain names, currently com, edu, gov, mil, net, org, or oneof the English two-letter codes identifying countries as specified in ISOStandard 3166, 1981.
The following table describes the parts ofa class or interface declaration, in the order that they should appear. See "Java Source File Example" for anexample that includes comments.
|
Part of Class/Interface Declaration |
Notes |
See "Documentation Comments" on page 9 for information on what should be in this comment. |
||
Class/interface implementation comment ( |
This comment should contain any class-wide or interface-wide information that wasn't appropriate for the class/interface documentation comment. |
|
First the |
||
First |
||
These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier. |
Four spaces should be used as the unit ofindentation. The exact construction of the indentation (spaces vs. tabs) isunspecified. Tabs must be set exactly every 8 spaces (not 4).
Avoid lines longer than 80 characters,since they're not handled well by many terminals and tools.
Note:Examples for use in documentation should have a shorter line length-generallyno more than 70 characters.
When an expression will not fit on a singleline, break it according to these general principles:
Here are some examples of breaking methodcalls:
someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3));
Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID
Following are two examples of indentingmethod declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.
//CONVENTIONAL INDENTATION someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS private static synchronized horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... }
Line wrapping for if
statements should generally use the 8-space rule, since conventional (4 space)indentation makes seeing the body difficult. For example:
//DON'T USE THIS INDENTATION if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS } //USE THIS INDENTATION INSTEAD if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } //OR USE THIS if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); }
Here are three acceptableways to format ternary expressions:
alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma;
Java programs can have two kinds ofcomments: implementation comments and documentation comments. Implementationcomments are those found in C++, which are delimited by /*...*/, and //.Documentation comments (known as "doc comments") are Java-only, andare delimited by /**...*/. Doc comments can be extracted to HTML files usingthe javadoc tool.
Implementation comments are mean forcommenting out code or for comments about the particular implementation. Doccomments are meant to describe the specification of the code, from animplementation-free perspective. to be read by developers who might notnecessarily have the source code at hand.
Comments should be used to give overviewsof code and provide additional information that is not readily available in thecode itself. Comments should contain only information that is relevant toreading and understanding the program. For example, information about how thecorresponding package is built or in what directory it resides should not beincluded as a comment.
Discussion of nontrivial or nonobviousdesign decisions is appropriate, but avoid duplicating information that ispresent in (and clear from) the code. It is too easy for redundant comments toget out of date. In general, avoid any comments that are likely to get out ofdate as the code evolves.
Note:Thefrequency of comments sometimes reflects poor quality of code. When you feelcompelled to add a comment, consider rewriting the code to make it clearer.
Comments should not be enclosed in largeboxes drawn with asterisks or other characters.
Comments should never include special characters such as form-feed andbackspace.
Programs can have four styles ofimplementation comments: block, single-line, trailing, and end-of-line.
Block comments are used to providedescriptions of files, methods, data structures and algorithms. Block commentsmay be used at the beginning of each file and before each method. They can alsobe used in other places, such as within methods. Block comments inside afunction or method should be indented to the same level as the code theydescribe.
A block comment should be preceded by ablank line to set it apart from the rest of the code.
/* * Here is a block comment. */
Block comments can startwith /*-
, which is recognized by indent(1) asthe beginning of a block comment that should not be reformatted. Example:
/*- * Here is a block comment with some very special * formatting that I want indent(1) to ignore. * * one * two * three */
Note: If youdon't use indent(1), you don't have touse /*-
in your code or make any other concessions to the possibility thatsomeone else might run indent(1) onyour code.
See also "DocumentationComments".
Short comments can appear on a single lineindented to the level of the code that follows. If a comment can't be writtenin a single line, it should follow the block comment format (see section 5.1.1). A single-line commentshould be preceded by a blank line. Here's an example of a single-line commentin Java code (also see "Documentation Comments"):
if (condition) { /* Handle the condition. */ ... }
Very short comments can appear on the sameline as the code they describe, but should be shifted far enough to separatethem from the statements. If more than one short comment appears in a chunk ofcode, they should all be indented to the same tab setting.
Here's an example of a trailing comment in Java code:
if (a == 2) { return TRUE; /* special case */ } else { return isPrime(a); /* works only for odd a */ }
The //
comment delimiter 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 inconsecutive 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; //}
Note: See "Java Source File Example" for examples of thecomment formats described here.
For further details, see "How toWrite Doc Comments for Javadoc" which includes information on the doc commenttags (@return, @param, @see):
http://java.sun.com/products/jdk/javadoc/writingdoccomments.html
For further details about doc commentsand javadoc, see the javadoc home page at:
http://java.sun.com/products/jdk/javadoc/
Doc comments describe Java classes,interfaces, constructors, methods, and fields. Each doc comment is set insidethe comment delimiters /**...*/
, with one comment per class,interface, or member. This comment should appear just before the declaration:
/** * The Example class provides ... */ public class Example { ...
Notice that top-level classes andinterfaces are not indented, while their members are. The first line of doccomment (/**) for classes and interfaces is not indented; subsequent doccomment lines each have 1 space of indentation (to vertically align the asterisks).Members, including constructors, have 4 spaces for the first doc comment lineand 5 spaces thereafter.
If you need to give information about aclass, interface, variable, or method that isn't appropriate for documentation,use an implementation block comment (see section 5.1.1) orsingle-line (see section 5.1.2)comment immediately afterthe declaration. For example, details about the implementation of a classshould go in in such an implementation block comment following the classstatement, not in the class doc comment.
Doc comments should not be positioned insidea method or constructor definition block, because Java associates documentationcomments with the firstdeclaration afterthe comment.
One declaration per line is recommendedsince it encourages commenting. In other words,
int level; // indentation level int size; // size of table
int level, size;
Do not put different types on the sameline. Example:
int foo, fooarray[]; //WRONG!
Note: Theexamples above use one space between the type and the identifier. Anotheracceptable alternative is to use tabs, e.g.:
int level; // indentation level int size; // size of table Object currentEntry; // currently selected table entry
Try to initialize local variables wherethey're declared. The only reason not to initialize a variable where it'sdeclared is if the initial value depends on some computation occurring first.
Put declarations only at the beginning ofblocks. (A block is any code surrounded by curly braces "{" and"}".) Don't wait to declare variables until their first use; it canconfuse the unwary programmer and hamper code portability within the scope.
void myMethod() { int int1 = 0; // beginning of method block if (condition) { int int2 = 0; // beginning of "if" block ... } }
The one exception to the rule is indexes offor
loops, which in Java can be declared in the for
statement:
for (int i = 0; i < maxLoops; i++) { ... }
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variablename in an inner block:
int count; ... myMethod() { if (condition) { int count = 0; // AVOID! ... } ... }
When coding Java classes and interfaces,the following formatting rules should be followed:
class Sample extends Object { int ivar1; int ivar2; Sample(int i, int j) { ivar1 = i; ivar2 = j; } int emptyMethod() {} ... }
Each line should contain at most onestatement. Example:
argv++; // Correct argc--; // Correct argv++; argc--; // AVOID!
Compound statements are statements thatcontain lists of statements enclosed in braces "{ statements }
".See the following sections for examples.
if-else
or for
statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces. A return
statement with avalue should not use parentheses unless they make the return value more obviousin some way. Example:
return; return myDisk.size(); return (size ? size : defaultSize);
The if-else
class ofstatements should have the following form:
if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition) { statements; } else if (condition) { statements; } else { statements; }
Note: if
statements always use braces {}. Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES {}! statement;
A for
statement should havethe following form:
for (initialization; condition; update) { statements; }
An empty for
statement (one inwhich all the work is done in the initialization, condition, and updateclauses) should have the following form:
for (initialization; condition; update);
When using the comma operator in theinitialization or update clause of a for
statement, avoid thecomplexity of using more than three variables. If needed, use separatestatements before the for
loop (for the initialization clause) orat the end of the loop (for the update clause).
A while
statement should havethe following form:
while (condition) { statements; }
An empty while
statementshould have the following form:
while (condition);
A do-while
statement shouldhave the following form:
do { statements; } while (condition);
A switch
statement should havethe following form:
switch (condition) { case ABC: statements; /* falls through */ case DEF: statements; break; case XYZ: statements; break; default: statements; break; }
Every time a case falls through (doesn'tinclude a break
statement), add a comment where the break
statement would normally be. This is shown in the preceding code example withthe /* falls through */
comment.
Every switch
statement shouldinclude a default case. The break
in the default case isredundant, but it prevents a fall-through error if later another case
is added.
A try-catch
statement shouldhave the following format:
try { statements; } catch (ExceptionClass e) { statements; }
A try-catch
statement mayalso be followed by finally
, which executes regardless of whetheror not the try
block has completed successfully.
try { statements; } catch (ExceptionClass e) { statements; } finally { statements; }
Blank lines improve readability by settingoff sections of code that are logically related.
Two blank lines should always be used inthe following circumstances:
One blank line should always be used in thefollowing circumstances:
Blank spaces should be used in thefollowing circumstances:
while (true) { ... }
Note that a blank space shouldnot be used between a method name and its opening parenthesis. This helps todistinguish keywords from method calls.
.
should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands. Example: a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } printSize("size is " + foo + "\n");
for (expr1; expr2; expr3)
myMethod((byte) aNum, (Object) x); myMethod((int) (cp + 5), ((int) (i + 3)) + 1);
Naming conventions make programs moreunderstandable by making them easier to read. They can also give informationabout the function of the identifier-for example, whether it's a constant,package, or class-which can be helpful in understanding the code.
Don't make any instance or class variablepublic without good reason. Often, instance variables don't need to beexplicitly set or gotten-often that happens as a side effect of method calls.
One example of appropriate public instancevariables is the case where the class is essentially a data structure, with nobehavior. In other words, if you would have used a struct
insteadof a class (if Java supported struct)
, then it's appropriate tomake the class's instance variables public.
Avoid using an object to access a class(static) variable or method. Use a class name instead. For example:
classMethod(); //OK AClass.classMethod(); //OK anObject.classMethod(); //AVOID!
Numerical constants (literals) should notbe coded directly, except for -1, 0, and 1, which can appear in a for
loop as counter values.
Avoid assigning several variables to thesame value in a single statement. It is hard to read. Example:
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!
Do not use the assignment operator in aplace where it can be easily confused with the equality operator. Example:
if (c++ = d++) { // AVOID! (Java disallows) ... }
if ((c++ = d++) != 0) { ... }
Do not use embedded assignments in anattempt to improve run-time performance. This is the job of the compiler.Example:
d = (a = b + c) + r; // AVOID!
a = b + c; d = a + r;
It is generally a good idea to useparentheses liberally in expressions involving mixed operators to avoidoperator precedence problems. Even if the operator precedence seems clear toyou, it might not be to others-you shouldn't assume that other programmers knowprecedence as well as you do.
if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // RIGHT
Try to make the structure of your programmatch the intent. Example:
if (booleanExpression) { return true; } else { return false; }
return booleanExpression;
if (condition) { return x; } return y;
return (condition ? x : y);
If an expression containing a binaryoperator appears before the ?
in the ternary ?:
operator,it should be parenthesized. Example:
(x >= 0) ? x : -x;
Use XXX
in a comment to flagsomething that is bogus but works. Use FIXME
to flag somethingthat is bogus and broken.
The following example shows how to format aJava source file containing a single public class. Interfaces are formattedsimilarly. For more information, see "Class andInterface Declarations" and "DocumentationComments"
/* * @(#)Blah.java 1.82 99/03/18 * * Copyright (c) 1994-1999 Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. */ package java.blah; import java.blah.blahdy.BlahBlah; /** * Class description goes here. * * @version 1.82 18 Mar 1999 * @author Firstname Lastname */ public class Blah extends SomeClass { /* A class implementation comment can go here. */ /** classVar1 documentation comment */ public static int classVar1; /** * classVar2 documentation comment that happens to be * more than one line long */ private static Object classVar2; /** instanceVar1 documentation comment */ public Object instanceVar1; /** instanceVar2 documentation comment */ protected int instanceVar2; /** instanceVar3 documentation comment */ private Object[] instanceVar3; /** * ...constructor Blah documentation comment... */ public Blah() { // ...implementation goes here... } /** * ...method doSomething documentation comment... */ public void doSomething() { // ...implementation goes here... } /** * ...method doSomethingElse documentation comment... * @param someParam description */ public void doSomethingElse(Object someParam) { // ...implementation goes here... } }