Java Style
These guidelines are consistent with
Sun's Code Conventions
and Google's coding standards for Java.
Above all be consistent and clear.
Programs that check style:
See the on-line version:
Java analyzer.
Checkstyle Checks
Some checks that may not be immediately obvious.
A. Identifiers
- All identifiers should have meaningful names---meaningful to people who do not know about the program.
Occasionally,
single letter loop indices like i for an int
or o for an Object are acceptable. But do not
overlook other possibilities like row or column.
- Class names must begin with a capital letter.
(Hence files names begin with a capital letter.)
The names of all instance methods and fields must not begin with a capital letter.
- Method and local variable names must begin with a lower case letter.
- Constants (static final member fields) must be all upper case letters and digits.
- Package names must be all lower case letters.
- Avoid abbreviations; never omit letters of a word to shorten an identifier.
- Avoid overly long identifiers, say greater than 20 characters or so.
- Although identifiers can differ only by capitalization in Java,
never take advantage of this.
- Choose names for different identifiers that are "psychologically distant"
in order to avoid confusion.
Compare:
disk_1 disk_2 disk_3
smallDisk mediumDisk largeDisk
- Nouns should be used for classes; verb phrases
for methods. For example,
void free ()
int assign ()
float multiply ()
void rescale ()
void printTitles ()
int rollTwo ()
void correctTable ()
Functions that return a boolean value often begin with is
boolean isEmpty ()
boolean isAllZero ()
- Getter and setter methods should look like this:
void setField (int field) { this.field = field; }
int getField () { return field; }
- Interface names often end in "able," especially if they have one method:
calculable,
changeable,
chargeable,
commensurable,
committable,
communicable,
compellable,
computable,
doable,
igniteable,
implementable,
movable,
paintable,
pluggable,
printable,
realizable,
runnable,
serializable,
terminable,
throwable,
tolerable,
traceable,
transferable,
transfusable,
transmittable,
transposable,
transportable,
traversable,
triable,
usable,
variable,
venerable,
etc.
interface Computable {
int compute (String x, float y);
}
Hungarian notation uses leading (or occasionally) trailing tags that identify the type of the object.
"Avoid ``Hungarian''-style naming conventions which encode type
information in variable names. They may be systematic, but they'll
screw you if you ever need to change the type of a variable. If the
variable has a small scope, the type will be visible in the
declaration, so the annotation is useless clutter. If the variable has
a large scope, the code should modular against a change in the
variable's type. In general, I think any deterministic algorithm for
producing variable names will have the same effect." Larson's C Coding Style
(The term Hungarian refers to the nationality of Charles Simonyi, a programmer
at Microsoft who wrote a doctoral thesis in the 1980's called "Program
Identifier Naming Conventions").
I am not a big fan of camelCase
(aka camelBack, sulkingCamelCase).
Compare with BiCapitalization (aka InterCaps),
sTuDLyCaPs, etc., at the article on Wikipedia.
I'd prefer to separate words by underscores (wide case).
It looks better to readers (the underscore is the space-which-is-not-a-space)
and can be enforced syntactically.
Compare [a-z][a-zA-Z]*
with [a-z]+(_[A-Z][a-z]*)*.
Capitalization can then be reserved for distinguishing larger syntactic namespaces.
Also, underscores work better with occasional acronyms, like ICBM_missile.
But that is not the true way in Java.
B. Comments
- Comments should be helpful, clear, concise, and grammatically correct.
- Comments should be formatted appropriately.
/*
This
comment
wastes a lot of vertical space.
*/
- Do not restate the obvious. For example,
i = i + 1; // Add one to i
Answer the question why you are doing it.
i = i + 1; // Prepare for next record in list
- Comments should be indented to the same margin as the code they pertain to.
// Loop comment
for (;;) {
}
Not
// Loop comment
for (;;) {
}
C. White Space
- Newlines should be indicated by either NL, or CR followed by NL.
- Use blank lines to separate logically related parts of the program.
- Use spaces judiciously to help the reader understand a complex line.
For example, compare
while (i<dataCount&&data[i]<target) {
with
while (i<dataCount && data[i]<target) {
- Use spaces judiciously to align similar or related program parts
For example, compare
private boolean hasExcess () { return dataCount>MAXIMUM; }
private boolean hasShortage () { return dataCount<MINIMUM; }
with
private boolean hasExcess () { return dataCount>MAXIMUM; }
private boolean hasShortage () { return dataCount<MINIMUM; }
- Do not use excessive (i) vertical and (ii) horizontal white space.
- A space belongs before a '(' character (most of the time), and never afterward.
A space belongs after a ')' character (most of the time), and never before.
- A space (or new line) belongs after the ',' or ';' characters, and never before.
D. Indentation
- Indentation should be 3 or 4 spaces.
Less than 3 spaces does not leave enough visual contrast and more than 4 spaces
wastes valuable horizontal space.
The Java coding conventions say to use 4 spaces.
- Whatever the number of columns
is chosen, that number should be used consistently whenever indentation is
called for.
- Do not put the tab character in your programs,
because applications interpret it differently.
E. Line Breaks
This convention for formatting control constructs is
known as K&R (for Kernighan and Richie).
- Generally, there should be exactly one statement per line.
(Although dependent on the overall developing environment,
make lines less than 90 characters.)
- The opening bracket '{' should be on same line as the if, else, for, while, do, and switch
keywords. (Sometimes known as Egyptian brackets.)
- Format of the while statement
while (k<=j) {
statements;
}
- Format of the if statement
if (...) {
statements;
} else if (...) {
statements;
} else {
statements;
}
- A
for
statement should have the following form:
for (initialization; condition; update) {
statements;
}
- The rare
for
statement with an empty body should be written:
for (initialization; condition; update) /* DO NOTHING! */ ;
- Format of the try statement:
try {
statements;
} catch (ExceptionOneClass e) {
statements;
} catch (ExceptionTwoClass e) {
statements;
} finally {
statements;
}
- A
switch
statement should have the following form:
switch (condition) {
case ABC:
statements;
/* FALLS THROUGH! */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
- Always use brackets even when the body of a compound construct
is just one statement.
for (int space=0; space<indent; space++) {
System.out.print(" ");
}
Get in the habit of doing this and you will have less trouble modifying
your own code.
Experienced programmers may be forgiven for occasionally
breaking this rule in situations where the entire
construct fits comfortably on one line.
for (int space=0; space<indent; space++) System.out.print(" ");
- When you must break a very long expression across a line,
follow these guidelines:
- Break after a comma.
- Break before an operator.
- Prefer higher-level breaks to lower-level breaks.
As for indenting the next line ... the Java code
conventions say to indent 8 spaces (two indenting units).
In mathematical text always break mathematical formulas before
a binary operator when the formula is displayed. (When the formula is
in the text of the paragraph, then break after the operator.)
Thus spoke Knuth.
F. Visibility
- Restrict the visibility of variables and other identifiers as much as possible.
Move the declaration of local variables to the point of first use.
- Declare the index variables of loops in the for construct.
for (int i=0; i<a.length; i++) {
statements
}
- Avoid methods that depend on instance variables and non-local variables.
G. General
- Initialization of variables:
- Initialize all variables at the point of declaration;
- use meaningful default values;
- if it comes to that, initialize objects to null, even though that is is redundant.
- In no case, initialize a string variable to a string that is never used.
- Use constants instead of variables as much as possible.
In other words, favor final local and instance variables over non-final.
Over 85% of local declarations should be final.
- Don't assign to method parameters; declare them to be final.
- Favor static over non-static methods, fields, and classes.
- Avoid comparing boolean constants or
assigning boolean constant values to variables.
- Order the conditions in a test meaningfully.
Use if(variable == constant) instead of if(constant == variable).
No "Yoda conditions" (see New Programming Jargon).
- The extension of a Java source file name must be .java (no capital letters).
- Array types: use String[] args not String args[].
Its the form the works in most contexts, i.e., in a method's return type.
Though the following is legal, don't use it.
int x, y[]; // Avoid; use two declarations
- Follow the standard order of modifiers:
- Methods: [public|protected|private] -> abstract -> static->final->synchronized->native->strictfp
- Fields: [public|protected|private] -> abstract -> static->final->transient->volatile
H.Assert
Document your code by using the assert statement.
// counter-clockwise is a left turn
private final boolean leftTurn (Point p) {
assert stack.size()>1; // must be at least two points on the stack
return Triangle.isCCW ((Point)stack.get(1), (Point)stack.get(0), p);
}
// No place for file, so create new disk
final Disc d = new Disc (discs.size()+1);
assert (length<=discCapacity); // assume any 1 file can always fit on empty disc
d.add (length,name);
discs.add (d);
I. Design
Write simple and robust code.
- Do not write the essentially same code twice;
use functions and procedures.
- Avoid multiple exits from loops.
- Avoid introducing boolean "flag" variables.
- Try to have exactly one return at the end of functions.
- Do not use System.exit()
- One class per file (inner classes excluded).
- Try to keep classes limited to 50-90 lines.
- Try to keep methods limited to 5-30 lines.
- Use packages to modularize complex programs.
- Use exception handling to handle uncommon cases.
- Don't handle exceptions unless the procedure can fix the problem
or unless the procedure is responsible for reporting errors.
- Don't raise or catch NullPointerException; it is always
evidence of a bug in the program
- Report errors and handle I/O in the main program.
- Avoid OS dependent behavior, e.g., Unix-centric constants "\n", "/", etc.
- Favor immutability. (Item 13, Block, 2001)
- Avoid string concatenation (except when concatenation two or three strings),
use StringBuilder (StringBuffer is synchronized and so is less efficient).
(Item 34, Block, 2001).
- Favor interfaces to reflection.
(Item 35, Block, 2001).
Ryan Stansifer <ryan@cs.fit.edu>
Last modified: Tue Jan 17 15:49:58 EST 2012