Skip to content

Java Code Style Guideline

Dzmitry Shylovich edited this page Apr 6, 2015 · 3 revisions
  1. Introduction
  2. Source file basics
  3. Source file structure
  1. Formatting
  1. Naming
  1. Programming Practices
  1. Tests

1. Introduction

This document defines the coding standards for source files in the Idea project.

The structure of this document is based on the Google Java Style reference.

2. Source file basics

File encoding: UTF-8

Source files are encoded in UTF-8.

Indentation

Indentation is done with tabs, where one indentation level consists of one tab.

3. Source file structure

A source file consists of the following, in this exact order:

  • Package statement
  • Import statements
  • Exactly one top-level class

Exactly one blank line separates each of the above sections.

Import statements

Ordering

The import statements are structured as follow:

  • import java.*
  • import javax.*
  • blank line
  • import all other imports
  • blank line
  • import static all other imports
No wildcard imports

Always use absolute imports.

 // Do it like this:
 import java.util.Arrays;
 // Not like this:
 import java.util.*;

Java source file organization

The following governs how the elements of a source file are organized:

  1. static fields
  2. normal fields
  3. constructors
  4. (private) methods called from constructors
  5. static factory methods
  6. JavaBean properties (i.e., getters and setters)
  7. method implementations coming from interfaces
  8. private or protected methods that get called from method implementations coming from interfaces
  9. other methods
  10. equals, hashCode, and toString

Note that private or protected methods called from method implementations should be placed immediately below the methods where they're used. In other words if there 3 interface method implementations with 3 private methods (one used from each), then the order of methods should include 1 interface and 1 private method in sequence, not 3 interface and then 3 private methods at the bottom.

4. Formatting

Braces

Block-like constructs: K&R style

Braces mostly follow the Kernighan and Ritchie style (a.k.a., "Egyptian brackets") for nonempty blocks and block-like constructs:

  • No line break before the opening brace but prefixed by a single space
  • Line break after the opening brace
  • Line break before the closing brace
  • Line break after the closing brace if that brace terminates a statement or the body of a method, constructor, or named class with the exception of the else, catch and finally statements that also lead to a line break

Example:

return new MyClass() {
    @Override 
    public void method() {
        if (condition()) {
            something();
        }
        else {
            try {
                alternative();
            } 
            catch (ProblemException ex) {
                recover();
            }
        }
    }
};

Line wrapping: around 100 characters

Aim to wrap code and Javadoc at 100 characters but favor readability over wrapping as there is no deterministic way to line-wrap in every situation.

When wrapping a lengthy expression put the separator symbol at the end of the line, rather on the next line (think comma separated arguments as an example). For instance:

if (thisLengthyMethodCall(param1, param2) && anotherCheck() &&
        yetAnotherCheck()) {
....
}

One statement per line

Only one statement per line. If needed split the statement into multiple lines.

Blank Lines

Add one blank line after a method signature that is multiline, i.e.

@Override
protected Object invoke(FooBarOperationContext<FooBarOperation> context,
            FooBarInvoker invoker) {

    CacheKeyInvocationContext<CachePut> invocationContext = ...

Class declaration

Try as much as possible to put the implements, extends section of a class declaration on the same line as the class itself.

Order the classes so that the most important comes first.

5. Naming

Package names

Package names are all lowercase, with consecutive words simply concatenated together (no underscores) and should not contain more the 10 characters. For example:

// Do it like this:
com.example.deadspace
// Not like this:
com.example.deadSpace
com.example.dead_space

Type names

Type names are written in camel case with the first letter upper case. Class names are typically nouns or noun phrases. For example, Character or ImmutableList. Interface names may also be nouns or noun phrases (for example, List), but may sometimes be adjectives or adjective phrases instead (for example, Readable).

Method names

Method names are written in camel case with the first letter lower case. They should begin with a verb. Use java common verb for beginning method names (e.g. get, set, is, has, add, remove, create).

Constant names

Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores.

Every constant is a static final field, but not all static final fields are constants. Constant case should therefore be chosen only if the field is really a constant.

// Constants
private static final Object NULL_HOLDER = new NullHolder();
public static final int DEFAULT_PORT = -1;

// Not constants
private static final ThreadLocal<Executor> executorHolder = new ThreadLocal<Executor>();
private static final Set<String> internalAnnotationAttributes = new HashSet<String>();

Variable names

Variable names are written in camel case with the first letter lower case. There is no naming difference between member and local variables.

6. Programming Practices

Null Checks

Use the Objects.requireNonNull static method to check that a method argument is not null. Format the exception message so that the name of the parameter comes first with its first character capitalized, followed by "cannot/must not be null". For instance:

public void handle(Event event) {
    Objects.requireNonNull(event, "Event must not be null");
    //...
}

Use of @Override

Always add @Override on methods overriding or implementing a method declared in a super type.

Ternary Operator

Wrap the ternary operator within parentheses, i.e. return (foo != null ? foo : "default");

Also make sure that the not null condition comes first.

Field and method references

A field of a class should always be referenced using this.

 // Do it like this:
 this.member = "Hello world!";
 // Not like this:
 member = "Hello world!";

Static members are accessed using the class name.

// Do it like this:
 MyClass.staticMember = 1;
 // Not like this:
 this.staticMember = 1;

Use unchecked exceptions over checked

Subclass RuntimeException for your own exceptions.

Use Optional

Use Optional as a return type for methods when returning value may or may not be "present."

Avoid switch statement

Try to avoid switch as much as possible.

Interface names without I prefix

Don't use I prefix for Interface name. Use Impl suffix for implementation class name. Example:

// Do it like this:
public interface MyService {}
public class MyServiceImpl implements MyService {}
// Not like this:
public interface IMySevice {}

7. Tests

Naming

Each unit test class must end with a Test suffix. Each integration test class must end with a IntegrationTest suffix.

Method names

Method name should include just enough details to convey the main purpose of the test and must have prefix should. Examples:

constructorShouldThrowExceptionForNullUser() {...}
shouldNotAcceptPasswordWithoutDigits() {...}
constructorShouldCreateValidOrderForValidUser() {...}

Mocking

Use the BDD Mockito support.

Asserting

Use AssertJ for fluent assertions.