Introduction

This document describes a list of Java code conventions for the Elsie project. The default code conventions are described in the document Code Conventions for the Java Programming Language at java.sun.com.

Class and Interface Declarations

Use fully qualified class name in the import statements. List import statements in alphabetical order. Use blank lines to seperate products. Examples:

import java.util.ArrayList;
import java.util.Hashtable;

import org.apache.foo.Bar;
import org.apache.bar.Foo;
        

Note: In Eclipse, you may use 'Ctrl+Space' or 'Ctrl+Alt+M' to complete the import statements automatically.

When the class/interface declaration is too long (longer than 80 characters), separate the line before extends or implements without indentation. Example:

public class MyClassWithAVeryLongName
extends TheFatherClassWithAVeryLongName
implements TheInterfaceWithAVeryLongName {
    ...
}
        

Comments and Javadoc

Write javadoc for all methods (private, protected, package and public). Write necessary javadoc for variables. When the <p> tag is used when writing javadoc, always close it by </p>. When writing javadoc for a variable, try to keep the comment on just one line. Examples:


/** Javadoc for this variable. */
private int myVariable;

/**
 * If the javadoc for this variable is long enough to occupy multiple
 * lines, then this form of comment is also perfectly acceptable.
 */
private int myVariable;

/**
 * Documentation of this method.
 * <p>
 * If the &lt;p&gt; tag is used, always close it by a &lt;/p&gt; tag.
 * </p>
 * @param intArg  an integer argument.
 * @param strArg  a String argument.
 * @return an integer calculated from arguments.
 * @throws SomeException  some exception when an error occurs.
 * @throws AnotherException  another exception when some other errors occur.
 */
public int myMethod(int intArg, String strArg)
throws SomeException, AnotherException {
    ...
}
        

When writing javadoc for a class or an interface, add your name in the @author tag, and add a @version tag which should be: @version $Revision$ $Date$. If this class or interface is introduced in a newer version, don't forget to add a @since tag. Examples (remove the underscores):

/**
 * Describe the purpose of this class here.
 * @author <a href="mailto:your_email_address@foo.com">Your Name</a>
 * @version $_Revision_$ $_Date_$
 * @since 1.2
 */
public class MyClass {
    ...
}
        

When writing comments inside a method, use // ... instead of /* ... */.

Indentation

Avoid lines longer than 80 characters, since they're not convenient for reading.

Use 4 spaces as the unit of indentation.

When an expression or a declaration does not fit on a single line, break it to a new line by indenting 8 spaces. Example:

int var = aMethodWithAVeryLongName(anExpressionWithAVeryLongName,
        anotherMethodWithAVeryLongName(anotherExpressionWithAVeryLongName,
                yetAnotherExpressionWithAVeryLongName));
        

When a method takes too many arguments and thus its declaration does not fit on a single line, break it to a new line by aligning the arguments. Example:

private static methodName(int anArgument,
                          Object anotherArgument,
                          String yetAnotherArgument,
                          Object andStillAnother) {
    ...
}
        

When breaking a long expression, break before an operator, and prefer high-level breaks to lower-level breaks. Examples:

System.out.println("This is a very very very very very very "
        + "long log to output.");

longName1 = longName2 * (longName3 + longName4 - longName5)
        + 4 * longname6;
        

Line wrapping for if statements should generally use the 8-space rule. Examples:

if ((condition1 && condition2)
        || (condition3 && condition4)
        || !(condition5 && condition6)) {
    doSomethingAboutIt();
}             
        

Here is an example for formatting long ternary expressions:

someVariable = (aLongBooleanExpression)
        ? beta 
        : gamma;  
        

Blank Spaces

Binary operators 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 = (a + b) / (c * d);
a += c + d;
a++;
printSize("size is " + size + "\n");
        

When declaring or calling methods with multiple arguments, use a blank space between two arguments. Examples:

public int myMethod(int arg1, int arg2, String arg3) {
    ...
}

myVariable = myMethod(arg1, arg2, arg3);
        

Class casts should be followed by a blank space. Example:

myVariable = (MyObject) myMethod((byte) aNum, (Object) x);
        

The expressions in a for statement should be separated by blank spaces, even when some parts are missing. Examples:

for (initialization; condition; update) {
    ...
}

for ( ; condition; update) {
    ...
}

for ( ; condition; ) {
    ...
}
        

Statements

A return statement with a simple value should not use parentheses. Use parentheses when returning a calculated value. Examples:

return;

return myDisk.size();

return (sizeIsGot ? size : defaultSize);
        

The conditional part of if and while statements should not use the equality operator for testing true or false values.

Always write if and while statements with { }.

The if-else class of statements should have the following form:

if (condition) {
    statements;
}

if (condition) {
    statements;
} else {
    statements;
}

if (condition) {
    statements;
} else if (condition) {
    statements;
} else {
    statements;
}
        

The for statement should have the following form:

for (initialization; condition; update) {
    statements;
}
        

The while or do-while statement should have the following form:

while (condition) {
    statements;
}

do {
    statements;
} while (condition);
        

Avoid using Iterators or Enumerations that are initialized outside of the loop, as the following examples:

for (Iterator it = someCollection.iterator(); iter.hasNext(); ) {
    do something;
}

for (Iterator it = someMapWithALongName.keySet().iterator();
        it.hasNext(); ) {
    do something;
}

for (Enumeration en = someServletRequest.getParameterNames();
        en.hasMoreElements(); ) {
    do something;
}
        

The switch statement should have the following form:

switch (condition) {
case ABC:
    statements;
    // Fall through to DEF.

case DEF:
    statements;
    break;

case XYZ:
    statements;
    break;

default:  // Default case is required for every switch.
    statements;
    break;  // Redundant break is required for default case.
}
        

Every time a case falls through (a case that doesn't include a break statement), add a comment where the break statement would normally be. The comment should indicate where the case will fall through to. Every switch statement should include a default case with a redundant break statement.

The try-catch-finally statement should have the following format:

try {
    statements;
} catch (ExceptionClass ex) {
    statements;
} finally {
    statements;
}
        

Best Practices

If you declare a method but not yet implement it (a TODO method), throw out an UnsupportedOperationException. That will make your incomplete class compilable, while notify you that you should provide implementation code. Example:

public class MyClass {
    ...
    public void methodToBeImplemented() {
        throw new UnsupportedOperationException("Implement me!");
    }
    ...
}