Java Coding Style Guide

Summary

This style guide is intended to help the computer professional produce better Java programs. It presents a set of specific guidelines for using the features of Java in a disciplined manner. The goal is to develop high quality, reliable, reusable, portable software. For a number of reasons, no programming language can ensure the achievements of these desirable objectives on its own. Programming must be embedded in a disciplined development process that addresses a number of topics in a well managed way. The use of Java is one of those. It must conform to good programming practice based on well established software engineering principles. This style guide is intended to bridge the gap between these principles and the actual practice of programming in Java.

Clear, readable, understandable source text eases program evolution, adaptation and maintenance. First, such source text is more likely to be correct and reliable. Second, effective code adaptation is a prerequisite to code reuse, a technique that has the potential for drastic reductions in system development costs. Easy adaptation requires thorough understanding of the software, and that is facilitated considerably by clarity. Finally, since maintenance (really evolution) is a costly process that continues throughout the life of a system, clarity plays a major role in keeping maintenance costs down. Over the entire life cycle, code has to be read and understood far more often than it is written; the investment of effort in writing readable, understandable code is thus well worthwhile. Many of the guidelines in this style guide are designed to promote clarity of the source text.

This style guide is intended for those involved in the development of real software systems written in Java. Different roles in a software project can exploit the style guide in different ways. The programmer can use it as a reference on good Java style. It can be used in code reviews as a common reference. Finally, lessons learned in real projects can be captured by extending the style guide.

To help you adhere to this guideline, we provide some Coding Style IDE Integration

Class layout and comments

This chapter describes the layout for classes, interfaces, enums and annotations. These all share a set of common properties, so they will be described together and for readability all called 'classes' here.

Files and filenames

Files longer than 2000 lines are cumbersome and should be avoided.

File names

The file must be named after the class it represents. As for most cases each file contains only one class, this is an easy naming convention. For nested or inner classes the name of the main class must be the name of the file. As names in Java are case-sensitive, the filename is case-sensitive also.

File organization

Each Java source file contains a single class or interface. Of course, this excludes inner classes as these must be defined without an (outer) class, and thus in the same file.

Java source files have the following ordering:

  • class header;
  • package and import statements;
  • class and interface declarations.

Class header

Each source file starts with a legal class headers stating license etc. These are fixed and can be generated. using the amdatu maven plugin.

Class header
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Package and import statements

The first non-comment line of most Java source files is a package statement. After an empty line import statements can follow. For example:

Package and imports
package org.amdatu.web.rest.doc;

import java.awt.Frame;
import java.io.InputStream;

A few notes must be made here:

  1. Package rules.
    When not using an explicit package statement in your code the code still is in a package, the default package. This easily results in name clashes and as package naming should be a part of the design, always use an explicit package name. For naming rules of packages see naming conventions.
  2. Import statements need to be explicit in order to overcome name clashes.
    They must be grouped by name.
  3. Import order.
    First in this section should be the standard Java imports like: java.io.IOException. Second should be the Java extensions (i.e. javax), third, the third party stuff. Finally the project-specific imports should be added.

Class, interface, enum and annotation declarations

The following comment block is an example for the comment that belongs to the declaration of a class, interface, enum or annotation. Note that by convention we use a generic author tag naming the Amdatu Project Team.

Class javadoc
/**
 * Configuration manager. Manages the configuration of an application. Has features
 * to import and export whole configurations and notifies components that need to
 * receive settings.
 *
 * @author <a href="mailto:amdatu-developers@amdatu.org">Amdatu Project Team</a>  
 */

The following table describes the parts of a class, interface, enum or annotation declaration, in the order that they should appear.

Part of declaration

Notes

documentation

According to comment block as shown above.

class, interface, enum or annotation statement

Utility classes should be final.

(static) variables

These should be grouped by functionality rather than by scope.

instance variables

These should be grouped by functionality rather than by scope.

constructors

Start with the default constructor if any. Utility classes should always have a private constructor

methods

These methods should also be grouped by functionality rather than by scope or accessibility. E.g. a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier. When implementing an interface, group the methods that are part of the interface.

inner classes

Are placed at the bottom of the file.

Annotations

Annotations for classes and methods should be done on the line directly above the class or method. They should be indented to the same level. An example:

@Manageable(description = "Starts the system.")
public void start() {
    // ...
}

Annotations for parameters can be inlined like this:

public void setValue(@Validation("x > 0 && x < 10", "Should be between 0 and 10.") int x) {
    // ...
}

Indentation

Four spaces should be used as unit of indentation for Java code and two spaces for XML. Use spaces or let your editor convert tabs to spaces as some editors might show the tabs different than they were intended! Tabs must be set exactly every 4 spaces in Java code and 2 spaces in XML files.

Line length

The length of a single line of code is limited to 120 characters. Make sure that the flow of the code is clear and that, when printing the file, it is well formed when using a reasonable font. Commented lines shouldn't be longer than 120 characters either.

Wrapping lines

When an expression will not fit on a single line, break it according to these general principles:

  • break after a comma;
  • break before an operator;
  • prefer higher level breaks to lower level breaks;
  • indent the new line with a tab;
  • if the above rules lead to confusing code or to code that's squished up against the right margin, please use common sense.

Comment

Comment styles

The Java language supports three different kinds of comments:

  1. single line comments;
  2. block comments;
  3. JavaDoc comments.

Single line comments

The compiler ignores everything from // to the end of the line. Use this style when adding a description or some kind of explanation on the same line of code or the line above. Between your comment and the // should be exactly one blank.

int a; // acceleration of the car

// all names that should be searched
String[] names;

Block comments

The compiler ignores everything from /* to */. Use this style for internal comments and copyright headers.

/*
 * This code is Copyright (c) 2009 Apache Software Foundation. All rights reserved.
 * You are not allowed to remember or reproduce anything you read below.
 */

JavaDoc comments

This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JavaDoc tool uses doc comments when preparing automatically generated documentation (See: JavaDoc keywords and HTML tags). Note that JavaDoc only uses this documentation when it occurs at an expected position in the file like the class definition or a member declaration.

These comments are used to provide English descriptions of the classes, interfaces, enums, annotations, methods and the description of data structures and algorithms. These comments should be used at the beginning of each class and before each method. If one of previous JavaDoc comments lack in the code, an error will be given by Checkstyle. If documentation for public variables lacks, Checkstyle will give a warning instead. The official JavaDoc guidelines (see references at the end of this document) should be followed, as they provide a good and clear writing style.

A method block comment looks as follows:

/**
 * Position the splitter location at a specified position.
 * This method can for instance be used when the last position
 * is stored as a preference setting for the user.
 *
 * @param position New position of divider, defined in pixels
 *     from the left of the containing window.
 * @exception org.apache.ace.units.si.exceptions.PositionException Whenever
 *     an invalid position is passed.
 * @see com.sun.java.swing.JSplitPane
 */
public void setSplitterLocation(int position) throws PositionException {
HTML tags

For class headers, method headers and member variables JavaDoc is used in order to generate API documentation. Some HTML-tags that can be used in order to make the comment blocks more readable:

Tag

Short description

<p>

New paragraph.

<br>

Break, a carriage return. For separation of two paragraphs, usage of <p> is preferred.

<ul><li></li></ul>

Unordered list of items. Each item should start with a <li> tag. Most browsers format this as a bullet list.

<code></code>

<pre></pre>

Code samples. Use this when refering to class names, method names, parameter names, etc, or

when providing examples on how to use

There is no need to embed the parameter name in the @param tag in <code> tags; this is done by JavaDoc automatically. The same holds for the exception name in the @exception or @throws tag. In the clarifying text however, use the <code> tags when refering to parameter names etc. The example below shows the <code> tag being used for the array parameter in the text, but not in its definition.

Example:

/**
 * Prints a range from an object array. The range
 * is specified by the first element to print, and
 * ranges to the last element of the array.
 *
 * @param list contains the objects to print
 * @param first index of first element in
 *     the <code>list</code> to print
 */
public void printRange(List<Printable> list, int first) {

Java syntax and its layout

Declarations

When declaring a variable or method make the accessibility as restrictive as possible. When using multiple keywords use the following ordering of keywords:

  1. accessibility
    Start with the accessibility as it makes clear if the method or variable is reachable at all.
  2. static (if applicable)
  3. final (if applicable)
  4. return type (methods only) or type (for variables)
    For readability, the type is as close to the name as possible.

This order is also compatible with the order that is used in Java for the main() method. This results in following sequence:

// A familiar one:
public static void main(String[] args) {}
private static String m_lastCreated = null;
private static final int RED = 4711;

Number per line

One declaration per line is recommended since it encourages commenting and it does not lead to confusing code. It also is more clear about the explicit initialization of variables as discussed in Initialization.

Example:

int level = 0; // level where user enters the system
int horizontalSize = 0; // horizontal size of current level layer

is preferred over:

int level, horizontalSize; // level and size of current level layer

Placement

In a method, declare local variables just before they are needed. This overcomes the problem of a big list of parameters at the beginning of a method and the use of a variable becomes more clearly in the context of the code, e.g. its initialization.

Initialization

The initialization of class variables is strictly not necessary because of the default initialization that takes place for these kinds of members. For some types, e.g. Booleans, this requires detailed knowledge of all the default values so it is more clear and explicit to initialize each member.

Variables that are used and declared within methods must always be initialized explicitly (the compiler will generate an error when you forget this).

Class and Interface Declarations

When coding Java classes and interfaces, the following formatting rules should be followed:

  • no space between a method and its parameter list;
  • "{" appears at the end of the same line as the declaration;
  • "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement, in which the case the "}" should appear immediately after the "{".

Example:

public class DefaultStrategy extends Strategy {
	private int m_attempts = 0;

	public DefaultStrategy(int attempts) {
                super();
		m_attempts = attempts;
	}

	void execute() {}
}

Statements

Simple statements

Each line should contain at most one statement.

Compound statements

Compound statements are statements that contain lists of statements enclosed in braces ("{...}"):

  • The enclosed statements should be indented one more level than the compound statement.
  • The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line and be indented to the beginning of the compound statement.
  • Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

if, if-else, if else-if else statements

There are a lot of nested possibilities for if-else constructions. All these variations can be programmed in very cryptic ways that easily and often will lead to buggy code. By being more explicit in the used coding style a lot of confusion can be taken away.

When using only one statement in a compound block brackets are optional. It is good practice, and therefore required, to always use brackets because mistakes can be made easily when adding a second statement and brackets are forgotten.

The following example illustrates the correct use of brackets in a few different if-then-else constructions:

if (condition) {
	statement1;
	statement2;
}
else {
	statement3;
}

if (condition) {
	statement1;
	statement2;
}
else if (condition1) {
	statement3;
	statement4;
}
else {
	statement5;
	statement6;
}

Note that in the example the else if construction is started at a new line so the statement can not be overlooked.

switch

When using a switch statement use following guidelines:

  • Consider including a default case, unless it would do nothing. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.
  • The so-called fall-through construction should be avoided. Only when there are good reasons to use it, make sure that it is very clear that a fall-through is used (comment it).

The next example shows the sample code that uses the guidelines for a switch statement:

switch (condition) {
	case A:
		statements;
		// falls through here, because...
	case B:
		statements;
		break;
	default:
		statements;
		break;
}

try - catch

A try - catch statement should have the following format:

try {
	statements;
}
catch (ExceptionClass e) {
	statements;
}

When using finally to add code that always will be executed this will look like:

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

Note that the catch and the finally start at a new line in order to be compliant to the guidelines for if-then-else statements.

for loops

New style for loops are generally preferred over old style ones, unless you explicitly need the index, or you have to make the code run on pre-Java 5 virtual machines.

Old style, a good example that needs the index anyway:

// lookup a value in a list, return the index
List<Element> list;
for (int i = 0; i < list.size(); i++) {
    if (value.equals(list.get(i)) {
        return index;
    }
}

New style, a good example that iterates over a list without any need for an index or type casts:

// iterate over a list, printing all values
List<Element> list;
for (Element e : list) {
    System.out.println(" - " + e);
}

Empty code blocks are allowed, but the closing bracket should be on the line directly after the opening bracket:

try {
   // Do some things
}
catch (Exception e) {
}

White Space

Blank lines

Blank lines improve readability by setting of sections of code that are logically related. One blank line should always be used in the following circumstances:

  • between class and interface definitions;
  • between methods;
  • before a block or single line comment;
  • between logical sections inside a method to improve readability.

Blank spaces

Blank spaces should be used in the following circumstances:

  • A keyword followed by a parenthesis should be separated by a space.

    while (index > 5) {
        // ...
    }
    

    Note that blanks should not be used between a method call and its opening parenthesis. This helps to distinguish keywords from function calls.

  • Blanks should appear after commas in argument lists.
  • All binary and ternary operators except "." should be separated from their operands by spaces. Blanks should never separate unary operators such as unary minus, increment("++") and decrement("--") from their operands.

    a += c + d;
    a = (a + b) / (c * d);
    a = (b > c) ? b : c;
    xCoord--;
    
  • The expressions in a for statement should be separated by blanks.

    for (expr1; cond1; expr2) {
    
  • Casts should be followed by a blank.

    myInstance.doIt((TreeFrame) frame);
    

Naming conventions

Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier.

Identifier Type

Rules for Naming

Examples

(inner) classes, interfaces, enums and annotations

Names should be nouns, in mixed case with the first letter of each word capitalised. Try to keep your names simple and descriptive. Use whole words and avoid acronyms and abbreviations.

class Raster;
class TreeFrame;

interfaces

Like class names, but if there is a name clash, the interface wins.

Repository

services

Same as interfaces, so don't append "Service" as you usually do not know if an interface is a service or not.

-

implementation classes

If a class implements an interface, it should use the name of the interface as part of its name, adding something specific for this implementation to it, or Impl if that does not make sense.

class FileBasedRepository implements Repository;
class VersionServlet implements HttpServlet;

exceptions

Like class names; always ending in "Exception"

InputException

methods

Methods should be verbs in mixed case with the first letter lowercase. Within each method name capital letters separate words. Property methods or get-set methods are used as follows:
When a method is used to get a value start the method name with 'get'. When a method is used to set a value start the method name with 'set'.

run();
runFast();
setBackground();

variables (except for (constant) static final variables and member variables)

All variables are in mixed case with a lowercase first letter. Words are separated by capital letters.

int index;
float myWidth;

member variables

The same capitalisation as for normal variables prefixed with 'm_'.

int m_index;
float m_myWidth;

constant (static final) variables, enum names

Names should be all uppercase with words separated by underscores ("_").

public static final int BLACK = 99;

packages

Lowercase only; avoid lengthy package names; always start with org.amdatu.

org.amdatu.demo.bundle

Exceptions

For some reason, for example if reflection is use, you might need to violate the coding style. In this case, Checkstyle will give an error on your code. To prevent Checkstyle from auditing errors, several comments are available.

CommentEffect
@checkstyle:offAll code and comments between this comment and the on-comment, will not be checked by Checkstyle.
@checkstyle:onCode and comments after this comment will be checked again. This comment has effect only if the off-comment is used before this.
@checkstyle:ignoreThe next line will be not be checked. Code and comments after the next line will be checked as usual.

Example:

// @checkstyle:on
private boolean myBoolean; // Not checked
private String myString; // Not checked
// @checkstyle:off
 
private String mySecondString; // Checked (and will audit an error)
 
// @checkstyle:ignore
private Object myObject; // Not checked
private Class m_class; // Checked (and will not audit an error)

References