Guides for SE student projects »

Java coding standard (basic)

Versions: [Basic Rules] [Basic + Intermediate Rules] [All Rules]

Use the Google Java style guide for any topics not covered in this document.

Naming

Names representing packages should be in all lower case.

com.company.application.ui

More on package naming

For school projects, the root name of the package should be your group name or project name followed by logical group names. e.g. todobuddy.ui, todobuddy.file etc.

Rationale: Your code is not officially ‘produced by NUS’, therefore do not use edu.nus.comp.* or anything similar.

Class/enum names must be nouns and written in PascalCase.

Line, AudioSystem

Variable names must be in camelCase.

line, audioSystem

Constant names must be all uppercase using underscore to separate words.

MAX_ITERATIONS, COLOR_RED

Names representing methods must be verbs and written in camelCase.

getName(), computeTotalWidth()

Underscores may be used in test method names using the following three part format featureUnderTest_testScenario_expectedBehavior()

e.g. sortList_emptyList_exceptionThrown() getMember_memberNotFount_nullReturned

Third part or both second and third parts can be omitted depending on what's covered in the test. For example, the test method sortList_emptyList() will test sortList() method for all variations of the 'empty list' scenario and the test method sortList() will test the sortList() method for all scenarios.

All names should be written in English.

Rationale: The code is meant for an international audience.

Boolean variables/methods should be named to sound like booleans

//variables
isSet, isVisible, isFinished, isFound, isOpen, hasData, wasOpen

//methods
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

As much as possible, use a prefix such as is, has, was, etc. for boolean variable/method names so that linters can automatically verify that this style rule is being followed.

Setter methods for boolean variables must be of the form:

void setFound(boolean isFound);

Rationale: This is the naming convention for boolean methods and variables used by Java core packages. It also makes the code read like normal English e.g. if(isOpen) ...

Plural form should be used on names representing a collection of objects.

Collection<Point> points;
int[] values;

Rationale: Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements. One space character after the variable type is enough to obtain clarity.

Iterator variables can be called i, j, k etc.

Variables named j, k etc. should be used for nested loops only.

for (Iterator i = points.iterator(); i.hasNext(); ) {
    ...
}

for (int i = 0; i < nTables; i++) {
    ...
}

Rationale: The notation is taken from mathematics where it is an established convention for indicating iterators.

Layout

Basic indentation should be 4 spaces (not tabs).

for (i = 0; i < nElements; i++) {
    a[i] = 0;
}

Rationale: Just follow it

Line length should be no longer than 120 chars.

Try to keep line length shorter than 110 characters (soft limit). But it is OK to exceed the limit slightly (hard limit: 120 chars). If the line exceeds the limit, use line wrapping at appropriate places of the line.

Indentation for wrapped lines should be 8 spaces (i.e. twice the normal indentation of 4 spaces) more than the parent line.

setText("Long line split"
        + "into two parts.");
if (isReady) {
    setText("Long line split"
            + "into two parts.");
}

Use K&R style brackets (aka Egyptian style).

Good

while (!done) {
    doSomething();
    done = moreToDo();
}

Bad

while (!done)
{
    doSomething();
    done = moreToDo();
}

Rationale: Just follow it.

Method definitions should have the following form:

public void someMethod() throws SomeException {
    ...
}

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 and the do-while statements should have the following form:

while (condition) {
    statements;
}
do {
    statements;
} while (condition);

The switch statement should have the following form: Note there is no indentation for case clauses.
Configure your IDE to follow this style instead.

switch (condition) {
case ABC:
    statements;
    // Fallthrough
case DEF:
    statements;
    break;
case XYZ:
    statements;
    break;
default:
    statements;
    break;
}

The explicit //Fallthrough comment should be included whenever there is a case statement without a break statement.

Rationale: Leaving out the break is a common error, and it must be made clear that it is intentional when it is not there.

A try-catch statement should have the following form:

try {
    statements;
} catch (Exception exception) {
    statements;
}


try {
    statements;
} catch (Exception exception) {
    statements;
} finally {
    statements;
}

Statements

Package and Import Statements

Put every class in a package.

Every class should be part of some package.

Rationale: It will help you and other developers easily understand the code base when all the classes have been grouped in packages.

Imported classes should always be listed explicitly.

Good

import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;

Bad

import java.util.*;


Rationale: Importing classes explicitly gives an excellent documentation value for the class at hand and makes the class easier to comprehend and maintain. Appropriate tools should be used in order to always keep the import list minimal and up to date. IDE's can be configured to do this easily.

Types

Array specifiers must be attached to the type not the variable.

Good

int[] a = new int[20];

Bad

int a[] = new int[20];

Rationale: The arrayness is a feature of the base type, not the variable. Java allows both forms however.

Loops

The loop body should be wrapped by curly brackets irrespective of how many lines there are in the body.

Good

for (i = 0; i < 100; i++) {
    sum += value[i];
}

Bad

for (i = 0, sum = 0; i < 100; i++)
    sum += value[i];

Rationale: When there is only one statement in the loop body, Java allows it to be written without wrapping it between { }. However that is error prone and very strongly discouraged from using.

Conditionals

The conditional should be put on a separate line.

Good

if (isDone) {
    doCleanup();
}

Bad

if (isDone) doCleanup();


Rationale: This helps when debugging using an IDE debugger. When writing on a single line, it is not apparent whether the condition is really true or not.

Single statement conditionals should still be wrapped by curly brackets.

Good

InputStream stream = File.open(fileName, "w");
if (stream != null) {
    readFile(stream);
}

Bad

InputStream stream = File.open(fileName, "w");
if (stream != null)
    readFile(stream);

The body of the conditional should be wrapped by curly brackets irrespective of how many statements.

Rationale: Omitting braces can lead to subtle bugs.

Comments

All comments should be written in English.

Furthermore, use American spelling and avoid local slang.

Rationale: The code is meant for an international audience.

Javadoc comments should have the following form:

/**
 * Returns lateral location of the specified position.
 * If the position is unset, NaN is returned.
 *
 * @param x  X coordinate of position.
 * @param y Y coordinate of position.
 * @param zone Zone of position.
 * @return Lateral location.
 * @throws IllegalArgumentException  If zone is <= 0.
 */
public double computeLocation(double x, double y, int zone)
    throws IllegalArgumentException {
  ...
}

Note in particular:

  • The opening /** on a separate line
  • Write the first sentence as a short summary of the method, as Javadoc automatically places it in the method summary table (and index).
    • In method header comments, the first sentence should start in the form Returns ..., Sends ..., Adds ... (not Return or Returnning etc.)
  • Subsequent * is aligned with the first one
  • Space after each *
  • Empty line between description and parameter section
  • Punctuation behind each parameter description -No blank line between the documentation block and the method/class

Javadoc of class members can be specified on a single line as follows:

/** Number of connections to this database */
private int connectionCount;

Comments should be indented relative to their position in the code.

Good

while (true) {
    // Do something
    something();
}

Bad

while (true) {
        // Do something
    something();
}

Bad

while (true) {
// Do something
    something();
}

Rationale: This is to avoid the comments from breaking the logical structure of the program.

References

  1. http://geosoft.no/development/javastyle.html
  2. http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
  3. http://developers.sun.com/sunstudio/products/archive/whitepapers/java-style.pdf
  4. Effective Java, 2nd Edition by Joshua Bloch
  5. http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

Contributors

  • Nimantha Baranasuriya - Initial draft
  • Dai Thanh - Further tweaks
  • Tong Chun Kit - Further tweaks
  • Barnabas Tan - Converted from Google Docs to Markdown Document