
marc.meurrens@acm.org
(
http://homepages.ulb.ac.be/~meurrens)
http://gee.cs.oswego.edu/dl/html/javaCodingStd.html
Doug Lea
(
dl@cs.oswego.edu)
http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/index.html
[back]
Draft Java Coding Standard
http://gee.cs.oswego.edu/dl/html/javaCodingStd.html
by
Doug Lea
(
dl@cs.oswego.edu)
This document includes a section
Structure and Documentation
(Standard ways to write and document constructions) and a section
Naming conventions (Standard ways to name identifiers: class names,
method names, variable names, etc).
recommendations (with rationale!):
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.
(updated August 2, 1997)
links to other style guidelines etc.
The form of these guidelines is based on example coding standards and
checklists in Watts
Humphrey's book
A Discipline for Software Engineering,
Addison-Wesley, 1995, along with author's experience.
Doug Lea
(
dl@cs.oswego.edu)
The form of these guidelines is based on example coding standards and
checklists in Watts
Humphrey's book
A Discipline for Software Engineering,
Addison-Wesley, 1995, along with feedback from people using previous
versions of this document.
package for each self-contained
project or group of related functionality. Create and use
directories in accord with java package conventions.
Consider writing an index.html file in each directory
briefly outlining the purpose and structure of the package.
Begin each file with a comment including:
package, briefly describe the rationale for
constructing the package.
Immediately follow each file header with:
package name
import list.
Example:
/* File: Example.java Date Author Changes Sep 1 95 Doug Lea Created Sep 13 95 Doug Lea Added new doc conventions */ package demo; import java.util.NoSuchElementException;
/** ... **/ comments using javadoc
conventions. (Even though not required by javadoc, end each
/** comment with **/ to make it easier to
read and check.)
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:
@author author-name
@version version number of class
@see string
@see URL
@see classname#methodname
Example:
/**
* A class representing a window on the screen.
* For example:
* <pre>
* Window win = new Window(parent);
* win.show();
* </pre>
*
* @see awt.BaseWindow
* @see awt.Button
* @version 1.2 31 Jan 1995
* @author Bozo the Clown
**/
class Window extends BaseWindow {
...
}
@see string
@see URL
@see classname#methodname
Example:
/**
* The current number of elements.
* must be non-negative, and less than or equal to capacity.
**/
protected int count_;
@param paramName description. (Note: In
alpha versions of Java, this is listed as @arg,
not @param.)
@return description of return value
@exception exceptionName description
@see string
@see URL
@see classname#methodname
Be as precise as reasonably possible in documenting effects. Here are some conventions and practices for semi-formal specifications.
@return condition: (condition)
@exception exceptionName IF
(condition)
@param paramname WHERE
(condition)
IllegalArgumentException. In particular, indicate
whether reference arguments are allowed to be null.
WHEN (condition)
waits until the condition holds.
RELY (condition)
GENERATE T
Threads)
constructed in the course of the method.
ATOMIC
synchronized methods or blocks).
PREV(obj)
OUT(message)
notifyAll) that are
sent to other objects as required aspects of functionality, or
referrred to in describing the effects of other methods.
foreach (int i in lo .. hi) predicate
foreach (Object x in e) predicate
foreach (Type x) predicate
Type.
-->
unique
unique instance variable that always refers to an object
that is not referenced by any other object.
fixed
EQUIVALENT to { code segment }
Example:
/** * Insert element at front of the sequence * * @param element the element to add * @return condition: * <PRE> * size() == PREV(this).size()+1 && * at(0).equals(element) && * foreach (int i in 1..size()-1) at(i).equals(PREV(this).at(i-1)) * </PRE> **/ public void addFirst(Object element);
/* ... */ comments to describe algorithmic
details, notes, and related documentation that spans more than a
few code statements.
Example:
/*
* Strategy:
* 1. Find the node
* 2. Clone it
* 3. Ask inserter to add clone
* 4. If successful, delete node
*/
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
Or, often better:
static final int INVALID= -1; int index = INVALID;
Use any consistent set of choices for code layout, including:
{'') placement at end of line or beginning
of next line.
lowercase.
Java Language Specification, page 107 as prefixes.
(For example, edu.oswego.cs.dl.)
CapitalizedWithInternalWordsAlsoCapitalized
ClassNameEndsWithException.
InterfaceNameEndsWithIfc.
ClassNameEndsWithImpl or
ClassNameEndsWithObject
UPPER_CASE_WITH_UNDERSCORES
trailingUnderscore_
(Yes, this is ugly. It is good that it is ugly!)
twoTrailingUnderscores__
lower_case_with_underscores
firstWordLowerCaseButInternalWordsCapitalized()
newX
toX
X x() or X getX().
void x(X value) or void setX(X value).
Minimize * forms of import. Be precise
about what you are importing. Check that all declared imports
are actually used.
import at all (thus requiring that every
class reference be fully dot-qualified), which avoids all possible
ambiguity at the expense of requiring more source code changes if package
names change.
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 template files for the most common kinds of
class files you create: Applets, library classes, application classes.
If you can conceive of someone else implementing a class's
functionality differently, define an interface, not an abstract
class. Generally, use abstract classes only when they are
``partially abstract''; i.e., they implement some functionality
that must be shared across all subclasses.
Consider whether any class should implement Cloneable
and/or Serializable.
Declare a class as final only if it is a subclass or
implementation of a class or interface declaring all of its
non-implementation-specific methods. (And similarly for
final methods).
Minimize reliance on implicit initializers for instance variables
(such as the fact that reference variables are initialized to
null).
Minimize statics (except for static final constants).
Generally prefer long to int,
and double to float. But 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).
ints; similarly, fewer
precision problems occur with doubles than
floats. On the other hand, because of limitations
in Java atomicity guarantees, use of longs and doubles must be
synchronized in cases where use of ints and floats 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).
Generally prefer protected to private.
protected variables and methods is harder,
since you you have to either loosen or check assumptions about
their properties. (Note that in Java, protected
methods are also accessible from unrelated
classes in the same package. There is hardly every any reason to
exploit this though.)
Avoid unnecessary instance variable access and update methods.
Write get/set-style methods only when they are
intrinsic aspects of functionality.
Minimize direct internal access to instance variables inside methods.
Use protected access and update methods instead (or
sometimes public ones if they exist anyway).
Avoid giving a variable the same name as one in a superclass.
Prefer declaring arrays as Type[] arrayName
rather than Type arrayName[].
Ensure that non-private statics 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.
Write methods that only do ``one thing''. In particular,
separate out methods that change object state from those that
just rely upon it. For a classic example in a
Stack, prefer having two methods Object
top() and void removeTop() versus the single
method Object pop() that does both.
Define return types as void unless they return
results that are not (easily) accessible otherwise. (i.e.,
hardly ever write ``return this'').
a.meth1().meth2().meth3()) can be the sources of
synchronization problems and other failed expectations about the
states of target objects.
Avoid overloading methods on argument type. (Overriding on
arity is OK, as in having a one-argument version versus a two-argument
version). If you need to specialize behavior according
to the class of an argument, consider instead choosing
a general type for the
nominal argument type (often Object) and using
conditionals checking instanceof. Alternatives
include techniques such as double-dispatching, or often best,
reformulating methods (and/or those of their arguments)
to remove dependence on exact argument type.
class Classifier {
String identify(Object x) { return "object"; }
String identify(Integer x) { return "integer"; }
}
class Relay {
String relay(Object obj) { return (new Classifier()).identify(obj); }
}
public class App {
public static void main(String[] args) {
Relay relayer = new Relay();
Integer i = new Integer(17);
System.out.println(relayer.relay(i));
}
}
Declare all public methods as synchronized; or if not, describe the
assumed invocation context and/or rationale for lack of
synchronization.
Prefer synchronized methods to synchronized
blocks.
If you override Object.equals, also override Object.hashCode,
and vice-versa.
Taligent's Java Cookbook
(mirrored
here)
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 to
implement Cloneable).
clone
might not do what you want.
Always document the fact that a method invokes wait
Whenever reasonable, define a default (no-argument) constructor
so objects can be created via Class.newInstance().
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.)
abstract methods, avoiding problems
occurring when they forget to do so but should have.
Use method equals instead of operator == when
comparing objects. In particular, do not use == to
compare Strings.
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.
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.
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.
Declare a local variable 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.)
Avoid assignments (``='') inside if
and while conditions.
='' should have
been ``=='' except when the variable is a
boolean.
Document cases where the return value of a called method
is ignored.
int unused = obj.methodReturningInt(args);
Ensure that there is ultimately a catch for
all unchecked exceptions that can be dealt with.
java.util.NoSuchElementException. Declare and
catch them anyway.
Embed casts in conditionals. For example:
C cx = null;
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.
Document fragile constructions used solely for the sake of
optimization.
Jonathan Hardwick's Java Optimization pages.
Do not require 100% conformance to rules of thumb such as
the ones listed here!
For some other standards and style guides, see
Mark
Fussell's Java Development Standards
(mirrored
here)
The Coding Standards Repository for various languages.
(mirrored
here)
Coding Standards for C, C++, and Java by
Vision 2000 CCS Package and Application Team
(mirrored
here)
Kent Sandvik's Java Coding Style Guidelines
(mirrored
here)
Taligent's Java Cookbook for porting C++ to Java.
(mirrored
here)
Naval Postgraduate School Java Style Guide.
(mirrored
here)
Solo
Software Engineering home page.

AmbySoft Inc. Java Coding Standards
new link added by Doug Lea (Last modified: Sat Jul 12 08:54:48 EDT 1997)
(mirrored
here)
A list of approx. 65 "pre-prepared" links to this page
is available at URL
http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/dougLea-LinksTo.html. (
updated August 6, 1997)
These links are (or will be) used in other pages related to "OO design and Coding Standards".
Doug Lea (
dl@cs.oswego.edu)
Last modified: Mon May 5 06:45:04 EDT 1997
|
Brussels July 8, 1997
mirror of Mon May 5 06:45:04 EDT 1997 by Doug Lea ( dl@cs.oswego.edu)
published by marc.meurrens@acm.org
( http://homepages.ulb.ac.be/~meurrens)
original URL: http://gee.cs.oswego.edu/dl/html/javaCodingStd.html
current URL: http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/DougLea.html
internet programming Links: http://www.ulb.ac.be/esp/ip-Links (ip-Links)
Université Libre de Bruxelles: http://www.ulb.ac.be (ULB)
La Cambre - Architecture: http://www.lacambre-archi.be
Belgian JAVA User Group: http://www.bejug.org (BeJUG)
|
|
Use this form to send your feedback and/or submit a link
|
Conventions used in these pages:
html file, text file or java or CPP source located on our site
download area (on our site) or file to be downloaded (use the right button of your mouse)
document on a belgian academic or scientific site
document (on another site) or link to be fixed or link we didn't visit/evaluate; documents indicated with their full URL will be displayed in their own "top" window.
ftp download or
file to be downloaded (use the right button of your mouse)
indicates a "mailto" link.
and indicate links added or updated within the last month.
Click on the |
| |||||||||||||||||