Java Code Conventions

Summary

This style guide summarizes the conventions used by trialox for writing Java-Code. For a discussion on the motivation for such a convention, see : http://wiki.trialox.org/confluence/display/DEV/Java+Code+Conventions+Motivation.

File Organisation

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

Each Java source file contains a single class or interface. A class may contain inner classes, but we never put multiple top-level classes or interfaces in the same file, instead of having a separate private class/interface in the same file we would use a static inner-class or interface. 

Java source files have the following ordering:

  1. Beginning comments
  2. Package and Import statements
  3. Class and interface declarations

Beginning comments

All source files must begin with the comments shown in the following code sample.

/*
 * Copyright (c) 2009 trialox.org (trialox AG, Switzerland).
 *
 * 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.
 */

See http://www.apache.org/dev/apply-license.html

The year in the copyright is the year of the creation of the file or a range inclusing the years of subsequent changes (changing the year on changes is optional, when major changes are done the year of modification should be added)

Package and Import Statements

The first non-comment line must be the package statement. After a single empty line import statements can follow. For example:

package org.trialox.fundracing;

import java.io.InputStream;
import java.util.ArrayList;
  • Always use an explicit package name.
  • Import statements need to be explicit.
  • Sort import statements are sorted using the package-name as primary and the class name as secondary key
  • You may use single empty lines to group import statements (by vendor/project)

Class and Interface Declarations

The following comment block is an example for the comment that belongs to the declaration of a class or an interface. The combination of JavaDoc syntax and keywords that are expanded by the source integrity tool result in the following block:

/**
 * The <code>Desktop</code> class allows a Java application to launch
 * associated applications registered on the native desktop to handle
 * a {@link java.net.URI URI} or a file.
 * <p>Supported operations include:
 * <ul>
 *   <li>launching the user-default browser to show a specified
 *       URI;</li>
 *   <li>launching the user-default mail client with an optional
 *       <code>mailto</code> URI;</li>
 *   <li>launching a registered application to open, edit or print a
 *       specified file.</li>
 * </ul>
 * <p>This class provides methods corresponding to these
 * operations. The methods look for the associated application
 * registered on the current platform, and launch it to handle a URI
 * or file. If there is no associated application or the associated
 * application fails to be launched, an exception is thrown.
 *
 * @since 1.6
 */

The following table describes the parts of a class or interface declaration, in the order that they should appear. See Comments for examples that include comments.

  Part Notes
1 Class/Interface documentation The documentation block should be preceded by two empty lines. See Comments for information on what should be in this comment.
2 Class or interface statement Class (static) variables:: These should be grouped by functionality rather than by scope.
3 Instance variables These should be grouped by functionality rather than by scope.
4 Constructors Start with the default constructor if any.
5 Methods and Inner classes
These should also be grouped by functionality rather than by type, 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. Generally the invoked methods are placed below the invoking method. If there is a field of class variable of the type of an inner class/interface this is declared immediately after the constructors.

Indentation

A tabulator is used as unit of indentation. Tabs are used only for indentation and occur exclusively at the beginning of a line. How a tab is rendered depends on the preference of the viewer, but for calculating the line length (see below) we equate a tab to a length of 4 characters.

Avoid indents of more than 5 levels.

Line length

Avoid lines longer than 80 characters. Make sure that the flow of the code is clear and that, when printing the file, it is well formed. Examples for use in documentation should have a shorter line length-generally no more than 70 characters.

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 2 tabs aligned with the beginning of the expression
  • if the above rules lead to confusing code or to code that's squished up against the right margin, please use common sense.

Here are some examples of breaking method calls:

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.

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

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

Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 2 tabs.

// CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg, String yetAnotherArg,
        Object andStillAnother) {
    ...
}

// INDENT 2 TABS TO AVOID VERY DEEP INDENTS
private static synchronized horkingLongMethodName(int anArg,
        Object anotherArg, String yetAnotherArg,
        Object andStillAnother) {
    ...
}

Line wrapping example for if statements:

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

Comments

Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are meant for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective. to be read by developers who might not necessarily have the source code at hand.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program.

Comment Styles

The Java language supports three different kinds of comments:

// text

The compiler ignores everything from // to the end of the line. Use this style when adding a description or some kind of explanation to the code.

/* text */

The compiler ignores everything from /* to */. The next documentation style is preferred.

/** Documentation. */

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 JDK JavaDoc tool uses doc comments when preparing automatically generated documentation (See: JavaDoc keywords and HTML tags). But JavaDoc only uses this documentation when it occurs at an expected position in the file like the class definition or a member declaration.

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.
 * @throws org.apache.felix.player.PositionException  whenever an
 *     invalid position is passed.
 * @see com.sun.java.swing.JSplitPane
 */
public void setSplitterLocation(int position) throws PositionException

We use comments with // to comment out code (also there should be only rarely be such code in the repository) and for comments within a method. For longer prose at the beginning of classes and methods that is not meant to be part of Javadoc we use /.../.+

JavaDoc keywords and HTML tags

For class headers, method headers and member variables JavaDoc is used in order to generate API documentation from the source later on. Tags come in two types:

  • Block tags - Can be placed only in the tag section that follows the main description. Block tags are of the form: @tag.
  • Inline tags - Can be placed anywhere in the main description or in the comments for block tags. Inline tags are denoted by curly braces: {@tag}.

Block tags

Include block tags in the following order:

  Keyword Short description
1 @param Used to define one parameter and describe this parameter. Multiple @param tags should be listed in argument-declaration order. This makes it easier to visually match the list to the declaration.
2 @return Return value of a method.
3 @throws Offered as hyperlink to the exception that can be thrown by a method. Multiple @throws tags should be listed alphabetically by the exception names.
4 @author The name entered here is shown as the author. Multiple @author tags should be listed in chronological order, with the creator of the class listed at the top.
5 @version Can be used to label a specific version of a package or application so the documentation shows this version number also.
6 @see When there are similarities with another class this tag is used to offer the reader a hyperlink to the mentioned class.
7 @since Specifies the product version when the Java name was added to the API.
8 @deprecated Adds a comment indicating that this API should no longer be used

A @param tag is "required" (by convention) for every parameter, even when the description is obvious. The @return tag is required for every method that returns something other than void, even if it is redundant with the method description. (Whenever possible, find something non-redundant (ideally, more specific) to use for the tag comment.)

These principles expedite automated searches and automated processing. Frequently, too, the effort to avoid redundancy pays off in extra clarity.

As a reminder, the fundamental use of these tags is described on the Javadoc Reference page. Generally the following additional guidelines to create comments for each tag should be used:

  • Separate the parameter name and the description by two spaces
  • Indent wrapping descriptions by one tab
  • The description begins with a lowercase letter if it is a phrase (contains no verb), or an uppercase letter if it is a sentence. End the phrase or sentence with a period.

Some inline tags

Keyword Short description
{@code} or {@literal} Displays text (in code font) without interpreting the text as HTML markup or nested javadoc tags. This enables you to use regular angle brackets (< and >) instead of the HTML entities (lt and gt) in doc comments.
{@link} or {@linkplain} Inserts an in-line link with visible text label that points to the documentation for the specified package, class or member name of a referenced class.
{@inheritDoc} Inherits (copies) documentation from the "nearest" inheritable class or implementable interface into the current doc comment at this tag's location.
{@value} Displays the value of the named constant.

HTML-tags

The following HTML-tags may 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. By most browsers, this is formatted as a bulleted list.
<code></code> Code samples; use this when refering to class names, method names, parameter names, etc.
<pre></pre> Preformatted text. Use these tags to protect figures and schemas "drawn" in Ascii, against formatting by the browser (which normally ignores whitespace and line breaks)
<dl><dt></dt><dd></dd></dl> Definition lists; <dt> specifies the term that is defined and <dd> the definition of this term. Not frequently used.

Format HTML tags using a two-space indent.

Note: 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 @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 array  contains the objects to print.
 * @param first  index of first element in the <code>array</code>
 *     to print.
 */
public void printRange(Object[] array, int first)

Declarations

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

For variables:

  1. accessibility (private, protected or public)
  2. static, if applicable
  3. final, if applicable
  4. transient, if applicable (only in classes that implements Serializable)
  5. volatile, if applicable
  6. type

For methods:

  1. accessibility (private, protected or public)
  2. static, if applicable
  3. final, if applicable
  4. synchronized, if applicable
  5. return type

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; // indentation level
int size;  // size of table

Initialization

The initialization of class variables is strictly not necessary because of the default initialization that takes place for these kinds of members. Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first. If instance variable require initialization that is independent of the constructor used, initialize them where they are declared or if this is not possible using an initializer (analogously to a static initializer for class variables).

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.

But it is recommended to write clear structured code which inevitably implies grouping of initialization (and declaration) statements.

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
void myMethod() {
    if (condition) {
        int count = 0;     // AVOID!
        ...
    }
    ...
}

Classes and Interfaces

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

  • No space between a method name and the parenthesis "(" starting its parameter list
  • Open brace "{" appears at the end of the same line as the declaration statement using a space between
  • Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{" using a single space between
  • Methods are separated by a blank line
  • Methods longer than 100 lines are cumbersome and should be avoided
class Sample extends Object {
    int ivar1;
    int ivar2;

    Sample(int i, int j) {
        ivar1 = i;
        ivar2 = j;
    }

    int emptyMethod() { }

    ...
}

Statements

Simple Statements

Each line should contain at most one statement. Example:

argv++;          // Correct
argc--;          // Correct
argv++; argc--;  // AVOID!

Compound Statements

Compound statements are statements that contain lists of statements enclosed in braces "{ statements }". See the following sections for examples.

  • 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.

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

if (condition) {
    statements;
}

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

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

Note: if statements always use braces {}. Avoid the following error-prone forms:

// AVOID! THIS OMITS THE BRACES {}!
if (condition)
    statement;

// AVOID! SAME FORM AS ABOVE
if (condition) statement; // AVOID

For long if else-if statements with complex flow and conditions is often very useful to add big comments. In order to get a readable struct you can use the following format:

// This is the comment for the first 'if'
// statement, which may contain multiple lines
if (condition) {
    statement;
}
// This is the comment for the first 'else-if'
// statement, which may contain multiple lines
else if (condition) {
    statement;
} else if (condition) { // a very short comment here
    statement;
}
// Finally there comes the comment for the 'else'
// statement.
else {
    statement;
}

switch Statements

When using a switch statement use following guidelines:

  • Every switch statement should include a default case.
  • 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).
  • Add a break in the default case. It may be redundant if it is the last statement, but it prevents a fall-through error if later another case is added.

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

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

try-catch Statements

A try-catch statement should have the following format:

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

A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.

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

Use the same convention for adding comments as given for if-else statements.

White Space

Blank lines

Blank lines improve readability by setting of sections of code that are logically related.

Two blank lines should always be used in the following circumstances:

  • between class and interface definitions;
  • between a group of methods that belong together (by its functionality or because they are part of the same interface).

One blank line should always be used in the following circumstances:

  • between methods;
  • between logical sections inside a method to improve readability.

Logical file sections

You may use simple non -javadoc comments to separate logical file sections; to make the separation more clear you may use a //-comment with 77 '=' signs, e.g.

// =============================================================================
/*
 * implementing <code>java.utilComparator</code>
 */

Blank Spaces

We never use spaces for indentation, we never use tabs except for indentation. A space is never followed by a space.

Use a space before and after assignments (=, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |=), but not before/after unary operators (++, --, -, !, ~). For all other operators, usage of surrounding blank space is optional.

int a = 0f;
int b = 34 + b;
int b += (b+3) * (c+4)
String text = "At index "+i+" there is an error";
a++;
b += ++a;
while ((a++) < (--b))



A keyword followed by a parenthesis should be separated by a space. Note that blanks should not be used between a method call and its opening parenthesis. This helps to distinguish keywords from function calls.
while (true) {
    ...
}


A blank space should appear after commas in argument lists.
System.out.printf("%2$s %s %<s %s", "a", "b", "c", "d");



The expressions in a for statement should be separated by blanks.
for (expr1; cond1; expr2)



No spaces after a cast.
myMethod((byte)aNum, (Object)x);





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-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.

Rules for Naming

Identifier Type Rules for Naming Examples
Packages Package name is always written in all-lowercase ASCII letters.
com.sun.eng
com.apple.quicktime
Classes Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used). class Raster;
{{class ImageSprite;
class UriHandler;
}}
Test Cases TestCases are named like regular classes, except their names end with "Test".
Interfaces Interface names should be capitalized like class names. interface RasterDelegate;
interface Storing;
Methods Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. run();
runFast();
getBackground();
Variables Variables are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should be short yet meaningful. One-character variable names should be avoided except for temporary "throwaway" variables. int i;
char c;
float myWidth;
Constants The names of variables declared class constants should be all uppercase with words separated by underscores ("_"). static final int MIN_WIDTH= 4;
static final int MAX_WIDTH= 999;

Common variable names

Identifier Type Examples
Temporary variables i, j, k, m and n
Exceptions ex
Events event

Attributions

Every project contains a file NOTICE.txt in the project root. (This file is copied to META-INF in the jar.)

The file starts with the following line

Copyright 2008 trialox.org (trialox AG, Switzerland)

And attributions for  included software separated by a blank line, the following are examples:

Contains code from the following book:
Jonathan Knudsen, "Java Cryptography", O'Reilly Media, Inc., 1998
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
This product includes software developed by the XML:DB Initiative
(http://www.xmldb.org/).
Portions are Copyright (c) 1998-2000 World Wide Web Consortium
(Massachusetts Institute of Technology, Institut National de Recherche en
Informatique et en Automatique, Keio University). All Rights Reserved.

Labels

 
(None)
  1. Aug 28, 2008

    Reto Bachmann says:

    When private classes and interfaces are associated with a public class, you can ...

    When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class.


    I would rather suggest never to declare more than one top-level class per file and use private static inner classes and interfaces rather than having separate classes in the same file, this makes the relation between the classes explicit. Also when I see a class-file without I know in which *.java file it is defined.

  2. Aug 30, 2008

    Reto Bachmann says:

    warum kein space vor dem = zeichen in assignements? scheint mir ziehmlich unübli...

    warum kein space vor dem = zeichen in assignements? scheint mir ziehmlich unüblich (java soources, apache code)

    1. Sep 02, 2008

      Tobias Hofer says:

      It is unusual and has its source in my preference for compact syntax. The compac...

      It is unusual and has its source in my preference for compact syntax. The compact assignment syntax conforms better to other operations like the postfix operations:

      a++;
      a+= 3;
      a= 3;
  3. Aug 30, 2008

    Reto Bachmann says:

    Four spaces should be used as unit of indentation. Use spaces or let your editor...

    Four spaces should be used as unit of indentation. Use spaces or let your editor convert tabs to spaces as some editors might show the tabs different than they were intended!

    Tab drücken exakt aus was ich eine: einmal einrücken. mir ist es gleich wie das sich einer anschaut. Ich schalge vor leerzeichen in der regel nur einzeln zu verwenden und für identation ausschliesslich tabs verwenden

    1. Sep 02, 2008

      Tobias Hofer says:

      There are some very bad issues concerning text formatting with tabs that won't a...

      There are some very bad issues concerning text formatting with tabs that won't arise if spaces are used instead. The source code will look same while editing or printing. That's not guaranteed if tabs are in use, especially if tabs and spaces get mixed for proper indentation. There is also a problem in properly indenting comments or documentation. If tabs are used, then the source code would look messy if not the same tab setting is used for viewing as the editor did use.

      1. Sep 02, 2008

        Reto Bachmann says:

        My proposal (copied) &nbsp; Use tabs to indent only; Use spaces afterwards, al...

        My proposal (copied)

         

        Use tabs to indent only;
        Use spaces afterwards, always.

        never tab after a space;
        never space before a tab;

        I don't think that there is a problem if some preffer to see tab as more spaces than other

  4. Sep 16, 2008

    Michael Szalay says:

    Do not use tabs. Source code looks really bad when using another tab setting the...

    Do not use tabs. Source code looks really bad when using another tab setting then the writer did. Every IDE has a feature to replace the tab by 4 spaces, I suggest to use that feature.

    1. Sep 16, 2008

      Reto Bachmann says:

      Source code doesn't looks bad when using our code conventions, only the right ma...

      Source code doesn't looks bad when using our code conventions, only the right margin might not be exactly where the writer of the code intended it to be.

  5. Nov 05, 2008

    Reto Bachmann says:

    ttp://java.sun.com/j2se/javadoc/writingdoccom ...