Java Coding Standard: Revision: March 15, 2002
Java Coding Standard: Revision: March 15, 2002
Contributors
Assaf Arkin[arkin@intalio.com]
Table of Contents
Note to the reader.................................................................................................................................... 4
2.1 Packages.................................................................................................................................... 7
4 Recommendations..........................................................................................................19
4.1 Classes......................................................................................................................................19
5.1 Example.java.........................................................................................................................31
2
Java Coding Standard, 3/26/02
3 / 39
Java Coding Standard, 3/26/02
Whenever possible, use the conventions from this document; do not reinvent
them. Keep in mind that projects (whether it is a software project or not) are not
developed in a vacuum and organizations do not work in a vacuum either.
A standard is never perfect and can not fit all situations: it is be possible that one
day you find yourself in a situation where none of these conventions could be
applied. Thus, you might want to break the conventions to fit your particular
situation; if you do so, document it.
If you go against a standard, you must document why you broke it and the
potential implications of breaking it.
The bottom line is that you need to understand each standard and understand
fully when to apply it (and also when not to apply it).
4
Java Coding Standard, 3/26/02
1.1 Introduction
Code conventions are important to programmers for a number of reasons:
• Hardly any software is maintained for its whole life by the original author.
• If you ship your source code as a product, you need to make sure it is as well packaged
and clean as any other product you create.
1.2 Contents
Structure and Documentation
Standard ways to write and document constructions.
Naming conventions
Standard ways to name identifiers (class names, method names, variable names, etc).
Recommendations
Some rules of thumb that tend to avoid common errors and development obstacles.
You can use these guidelines to make your own design and coding checklists to be
used in retrospective code clean-up or when classes need to be used in new contexts or
placed in reusable libraries.
Code Examples
‘Example.java’ uses the code conventions of this document. ‘Package.html’ outlines
the purpose of a package.
5 / 39
Java Coding Standard, 3/26/02
Related Documents
References to other style guidelines etc.
6
Java Coding Standard, 3/26/02
2.1 Packages
Create a new java package for each self-contained project or group of related functionality.
Create and use directories in accord with java package conventions.
Consider writing a package.html file in each directory briefly outlining the purpose and
structure of the package.
7 / 39
Java Coding Standard, 3/26/02
Example:
/**
*/
package demo;
import java.util.NoSuchElementException;
Preface each class with a /** ... */ comment describing the purpose of the class,
guaranteed invariants, usage instructions, and/or usage examples. Also include any
reminders or disclaimers about required or desired improvements. Use HTML format, with
added tags:
8
Java Coding Standard, 3/26/02
Example:
/**
* For example:
* <pre>
* win.show();
* </pre>
* @see awt.BaseWindow
* @see awt.Button
*/
...
Declaration order:
• member variables
• class constructors
• public methods
9 / 39
Java Coding Standard, 3/26/02
Use javadoc conventions to describe nature, purpose, constraints, and usage of instances
variables and static variables. Use HTML format, with added tags:
• @see string
• @see URL
• @see classname#methodname
Example:
/**
*/
2.5 Methods
Use javadoc conventions to describe nature, purpose, preconditions, effects, algorithmic notes,
usage instructions, reminders, etc. Use HTML format, with added tags:
10
Java Coding Standard, 3/26/02
Do not forget to document why something is being done, not just what. With some time every
one can figure out what your code is doing but can hardly say why you choose to do that.
Example:
/*
* Strategy:
* 2. Clone it
*/
Use running // comments to clarify non-obvious code. But don't bother adding such
comments to obvious code; instead try to make code obvious!
Example:
int index = -1; // -1 serves as flag meaning the index isn't valid
11 / 39
Java Coding Standard, 3/26/02
2.7 Layout
• Indentation
Avoid the ‘Tab’ key; four spaces should be used as the unit of indentation.
• Line Length
Lines up to 70 characters are easier to read and print.
Note: this is only a recommendation, lines can be longer, just don't abuse it.
Right-brace (‘}’) starts a line by itself intended to match its corresponding opening
statement, except when it is a null statement the ‘}’ should appear immediately after
the ‘{‘.
12
Java Coding Standard, 3/26/02
• Put the ‘extend’ line under the ‘naming’ line if the ‘extend line is too long.
Examples:
class Example1
extends Class1,Class2,Class3,Class4,Class5
if (condition) {
...
} else {
...
} //--Example1
...
if (condition) {
...
} else {
...
} //--Example2
• Declare all method variables at the top of the method (except for loop initializers or
local loop variables)
13 / 39
Java Coding Standard, 3/26/02
Example:
while (true) {
...
Note: a blank space should not be used between a method name and its opening
parenthesis. This helps to distinguish keywords from method calls.
Example:
...
} //--foo
14
Java Coding Standard, 3/26/02
• All binary operators except ‘.’ 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.
Examples:
a += c + d;
a = (a + b) / (c * d);
while (condition) {
n++;
Examples:
myMethod((int)aInt, (Object)x);
• Concerning the blank space in the naming line of a method, do as you want:
Examples:
public foo(int i, byte b){
15 / 39
Java Coding Standard, 3/26/02
• Align the new line with the beginning of the expression at the same level on the
previous line.
Examples:
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.
+ 4 * longname6; // PREFER
16
Java Coding Standard, 3/26/02
3 Naming Conventions
packages
lowercase
Consider using the recommended domain-based conventions described in the Java
Language Specification, page 107 as prefixes.
files
The java compiler enforces the convention that file names have the same base name
as the public class they define.
classes
CapitalizedWithInternalWordsAlsoCapitalized
ClassNameEndsWithImpl OR ClassNameEndsWithObject
exception class
ClassNameEndsWithException.
constants (finals)
UPPERCASE_WITH_UNDERSCORE_IF_MORE_THAN_ONE_WORD
private or protected
_firstWordLowerCaseWithUnderscoreAndInternalWordsCapitalized
17 / 39
Java Coding Standard, 3/26/02
local variables
firstWordLowerCaseButInternalWordsCapitalized
methods
firstWordLowerCaseButInternalWordsCapitalized()
newX OR createX
toX
X getX()
18
Java Coding Standard, 3/26/02
4 Recommendations
4.1 Classes
• When sensible, consider writing a main for the principal class in each program file. The
main should provide a simple unit test or demo.
• For self-standing application programs, the class with main should be separate from
those containing normal classes.
• Consider writing source code templates for the most common kinds of class files you
create: Applets, library classes, application classes.
Rationale: Interfaces are more flexible than abstract classes. They support multiple
inheritances and can be used as `mixins' in otherwise unrelated classes.
Rationale: These are ``magic'' interfaces in Java, that automatically add possibly-
needed functionality only if so requested.
Rationale: Making a class final means that no one ever has a chance to reimplement
functionality. Defining it instead to be a subclass of a base that is not final means that
someone at least gets a chance to subclass the base with an alternate implementation.
Which will essentially always happen in the long run.
19 / 39
Java Coding Standard, 3/26/02
• Always handle the catch block when handling exception, by at least logging a
message or the stack trace.
Rationale: It is far from being enough to just document the catch block with
sentences like:
“never here.”
You can never be 100% confident about the execution of a code. For instance, you don’t
know on which platform it will be run and with which JVM implementation. You can’t
predict the behavior of your code in all the cases. Thus to prevent tedious debugging or
unexpected behavior, always log a message in the catch block and this is a minimum
effort.
try {
_service.connect();
_logger.log(ce.printStackTrace());
20
Java Coding Standard, 3/26/02
• Don’t use generic exceptions , always try to as precise as possible when catching an
exception
Rationale: Being precise will help you to master your code and to know exactly what
you are doing. For instance, the following exception handling code reflects the work of
a developer that is not very confident (or worst that is lazy J)
try{
if (_file.exists()) {
db.store(_file);
printReport();
} catch(Exception e) {
e.printStackTrace();
if (_file.exists()) {
db.store(_file);
printReport();
} catch(IOException ie) {
_logger.log(re.getMessage());
21 / 39
Java Coding Standard, 3/26/02
• A constructor or method must explicitly declare all unchecked (i.e. runtime) exceptions
it expects to throw. The caller can use this documentation to provide the proper
arguments.
• Do not use unchecked exceptions instead of code that checks for an exceptional
condition.
Rationale: Comparing an index with the length of an array is faster to execute and
better documented than catching ArrayOutOfBoundsException.
22
Java Coding Standard, 3/26/02
4.3 Variables
• Never declare instance variables as public(that does not include constant variables
(final static)).
Rationale: The standard OO reasons. Making variables public gives up control over
internal class structure. Also, methods cannot assume that variables have valid values.
• Minimize reliance on implicit initializers for instance variables (such as the fact that
reference variables are initialized to null).
Rationale: Static variables act like globals in non-OO languages. They make methods
more context-dependent, hide possible side-effects, sometimes present synchronized
access problems. and are the source of fragile, non-extensible constructions. Also,
neither static variables nor methods are overridable in any useful sense in subclasses.
• Generally prefer double to float and use int for compatibility with standard Java
constructs and classes (for the major example, array indexing, and all of the things this
implies, for example about maximum sizes of arrays, etc).
Rationale: fewer precision problems occur with doubles than floats. On the other
hand, because of limitations in Java atomicity guarantees, use of
double(respectively int) must be synchronized in cases where use of
floats(long) sometimes would not be.
• Use final and/or comment conventions to indicate whether instance variables that
never have their values changed after construction are intended to be constant
(immutable) for the lifetime of the object (versus those that just so happen not to get
assigned in a class, but could in a subclass).
Rationale: Access to immutable instance variables generally does not require any
synchronization control, but others generally do.
23 / 39
Java Coding Standard, 3/26/02
• Avoid unnecessary instance variable access and update methods. Write get/set-style
methods only when they are intrinsic aspects of functionality. Always write these
methods when coding an interface.
Rationale: Most instance variables in most classes must maintain values that are
dependent on those of other instance variables. Allowing them to be read or written in
isolation makes it harder to ensure that consistent sets of values are always used.
• Minimize direct internal access to instance variables inside methods. Use protected
access and update methods instead (or sometimes public ones if they exist anyway).
Rationale: While inconvenient and sometimes overkill, this allows you to vary
synchronization and notification policies associated with variable access and change
in the class and/or its subclasses, which is otherwise a serious impediment to
extensibility in concurrent OO programming. (Note: The naming conventions for
instance variables serve as an annoying reminder of such issues.)
• Declare a very local variable (such as loop variable or array index) only at that point in
the code where you know what its initial value should be.
• Declare and initialize a new local variable rather than reusing (reassigning) an existing
one whose value happens to no longer be used at that program point.
• Assign null to any reference variable that is no longer being used. (This includes,
especially, elements of arrays.)
24
Java Coding Standard, 3/26/02
4.4 Methods
• Avoid cascading method calls
Example
bind(object)
bindInt(int)
bindString(string)
Rationale: Java method resolution is static; based on the listed types, not the actual
types of argument. This is compounded in the case of non-Object types with coercion
charts. In both cases, most programmers have not committed the matching rules to
memory. The results can be counterintuitive; thus the source of subtle errors. For
example, try to predict the output of this. Then compile and run.
class Classifier{
} //--class Classifier
class Relay {
25 / 39
Java Coding Standard, 3/26/02
} //--class Relay
System.out.println(relayer.relay(i));
} //--class App
Rationale: Better encapsulation; less prone to subclassing snags; can be more efficient.
Rationale: Clients may need to take special actions to avoid nested monitor calls.
• Prefer abstract methods in base classes to those with default no-op implementations.
(Also, if there is a common default implementation, consider instead writing it as a
protected method so that subclass authors can just write a one-line implementation
to call the default.)
Rationale: The Java compiler will force subclass authors to implement abstract
methods, avoiding problems occurring when they forget to do so but should have.
26
Java Coding Standard, 3/26/02
Rationale: Essentially all containers and other utilities that group or compare objects
in ways depending on equality rely on hashcodes to indicate possible equality.
• Override readObject and writeObject if a Serializable class relies on any state that
could differ across processes, including, in particular, hashCodes and transient fields.
• If you think that clone() may be called in a class you write, then explicitly define it
(and declare the class as implements Cloneable).
Rationale: The default shallow-copy version of clone might not do what you want.
Rationale: If someone defined an equals method to compare objects, then they want
you to use it. Otherwise, the default implementation of Object.equals is just to use
==.
• Always embed wait statements in while loops that re-wait if the condition being
waited for does not hold.
Rationale: When a wait wakes up, it does not know if the condition it is waiting for is
true or not.
• Use notifyAll instead of notify or resume when you do not know exactly the number
of threads which are waiting for something.
Rationale: Classes that use only notify can normally only support at most one kind of
wait condition across all methods in the class and all possible subclasses. And
unguarded suspends/resumes are even more fragile.
27 / 39
Java Coding Standard, 3/26/02
if (x instanceof C) cx = (C) x;
else evasiveAction();
Rationale: This forces you to consider what to do if the object is not an instance of the
intended class rather than just generating a ClassCastException.
• When throwing an exception, do not refer to the name of the method which has
thrown it but specify instead some explanatory text
Rationale: the name of the method could be given by the stack trace and good
exception messages are always useful.
Rationale: See Jonathan Hardwick's Java Optimization pages (see Chapter 6).
Rationale: There are almost always typos. The java compiler catches cases where (“=”)
should have been (“==”) except when the variable is a boolean.
Rationale: These are typically errors. If it is by intention, make the intent clear. A
simple way to do this is:
int unused = obj.methodReturningInt(args);
• Minimize * forms of import. Be precise about what you are importing. Check that all
declared imports are actually used.
Rationale: Otherwise readers of your code will have a hard time understanding its
context and dependencies.
28
Java Coding Standard, 3/26/02
• Ensure that non-private static variables have sensible values even if no instances are
ever created. (Similarly ensure that static methods can be executed sensibly.) Use
static intitializers (static { ... } ) if necessary.
Rationale: You cannot assume that non-private statics will be accessed only after
29 / 39
Java Coding Standard, 3/26/02
• Do not require 100% conformance to rules of thumb such as the ones listed here!
Rationale: Java allows you program in ways that do not conform to these rules for
good reason. Sometimes they provide the only reasonable ways to implement things.
And some of these rules make programs less efficient than they might otherwise be, so
are meant to be conscientiously broken when performance is an issue.
30
Java Coding Standard, 3/26/02
5 Code Examples
5.1 Example.java
/**
* File: Example.java
*/
package com.intalio.n3.xml;
import java.io.Serializable;
import java.net.URL;
import java.net.MalformedURLException;
/**
*@version $Revision$
*@see URNNamespace
*/
31 / 39
Java Coding Standard, 3/26/02
/**
*/
/**
*/
/**
*@see URNNamespace
*/
/**
*/
_identifier = url;
/**
32
Java Coding Standard, 3/26/02
*/
return _identifier;
/**
*/
...
while (condition) {
...
do {
...
} while (condition);
} //equals
...
switch (condition) {
case ABC:
if (condition) {
33 / 39
Java Coding Standard, 3/26/02
...
} else {
...
break;
case DEF:
statements;
break;
case XYZ:
...
break;
default:
statements;
break;
} //switch
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}//hashCode
34
Java Coding Standard, 3/26/02
}//-- Example
35 / 39
Java Coding Standard, 3/26/02
5.2 package.html
<html>
<body>
<dd><ahref="mailto:arkin@exoffice.com">Assaf
Arkin</a></dd>
</dl>
36
Java Coding Standard, 3/26/02
<pre>
JDO jdo;
Database db;
Query oql;
QueryResults results;
db = jdo.getDatabase();
db.begin();
results = oql.execute();
while ( results.hasMore() ) {
<font color="red">// A 25% mark down for each product and mark as
sale</font>
37 / 39
Java Coding Standard, 3/26/02
38
Java Coding Standard, 3/26/02
6 Related Documents
For some others standards and style guides, see:
http://java.sun.com/products/jdk/javadoc/writingdoccomments/index.html
• Javasoft Coding Standard (the present document uses some sections of it)
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
• joodcs standards, with links to a Coding Standards Repository for various languages.
http://www.meurrens.org/ip-Links/java/joodcs/
http://gee.cs.oswego.edu/dl/html/javaCodingStd.html
http://www.ambysoft.com/javaCodingStandards.pdfJonathan
http://www.cs.cmu.edu/~jch/java/optimization.html
http://www.java-zone.com/free/articles/top10/
39 / 39