-
Notifications
You must be signed in to change notification settings - Fork 2
Java Code Style Guideline
- Null Checks
- Use of @Override
- Ternary Operator
- Field and method references
- Use unchecked exceptions over checked
- Use Optional
- Avoid switch statement
- Interface names without
Iprefix
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.
Source files are encoded in UTF-8.
Indentation is done with tabs, where one indentation level consists of one tab.
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.
The import statements are structured as follow:
- import
java.* - import
javax.* - blank line
- import all other imports
- blank line
- import static all other imports
Always use absolute imports.
// Do it like this:
import java.util.Arrays;
// Not like this:
import java.util.*;The following governs how the elements of a source file are organized:
- static fields
- normal fields
- constructors
- (private) methods called from constructors
- static factory methods
- JavaBean properties (i.e., getters and setters)
- method implementations coming from interfaces
- private or protected methods that get called from method implementations coming from interfaces
- other methods
-
equals,hashCode, andtoString
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.
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();
}
}
}
};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()) {
....
}Only one statement per line. If needed split the statement into multiple 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 = ...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.
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_spaceType 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 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 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 are written in camel case with the first letter lower case. There is no naming difference between member and local variables.
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");
//...
}Always add @Override on methods overriding or implementing a method declared in a super type.
Wrap the ternary operator within parentheses, i.e. return (foo != null ? foo : "default");
Also make sure that the not null condition comes first.
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;Subclass RuntimeException for your own exceptions.
Use Optional as a return type for methods when returning value may or may not be "present."
Try to avoid switch as much as possible.
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 {}Each unit test class must end with a Test suffix.
Each integration test class must end with a IntegrationTest suffix.
Method name should include just enough details to convey the main purpose of the test and must have prefix should. Examples:
constructorShouldThrowExceptionForNullUser() {...}
shouldNotAcceptPasswordWithoutDigits() {...}
constructorShouldCreateValidOrderForValidUser() {...}Use the BDD Mockito support.
Use AssertJ for fluent assertions.