-
Notifications
You must be signed in to change notification settings - Fork 0
Java Coding style Guidelines
While these are just guidelines, we should adhere to the following coding-style to have easier readability, which in turn helps us manage our code better. Overall, we'll follow Google's Java Style Guide but have a few caveats for our specific codebase. Also, only the following listed below really needs to be considered.
Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement.
Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs:
No line break before the opening brace. Line break after the opening brace. Line break before the closing brace. Line break after the closing brace, only if that brace terminates a statement or terminates the body of a method, constructor, or named class. For example, there is no line break after the brace if it is followed by else or a comma.
Examples:
return () -> {
while (condition()) {
method();
}
};
return new MyClass() {
@Override public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
} else if (otherCondition()) {
somethingElse();
} else {
lastThing();
}
}
};
Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block. (See the example in Section 4.1.2, Nonempty blocks: K & R Style.)
Java code has a column limit of 100 characters. A "character" means any Unicode code point. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.5, Line-wrapping.
Terminology Note: When code that might otherwise legally occupy a single line is divided into multiple lines, this activity is called line-wrapping.
There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there are several valid ways to line-wrap the same piece of code.
Note: While the typical reason for line-wrapping is to avoid overflowing the column limit, even code that would in fact fit within the column limit may be line-wrapped at the author's discretion.
Tip: Extracting a method or local variable may solve the problem without the need to line-wrap.
The prime directive of line-wrapping is: prefer to break at a higher syntactic level. Also:
When a line is broken at a non-assignment operator the break comes before the symbol. (Note that this is not the same practice used in Google style for other languages, such as C++ and JavaScript.) This also applies to the following "operator-like" symbols: the dot separator (.) the two colons of a method reference (::) an ampersand in a type bound (<T extends Foo & Bar>) a pipe in a catch block (catch (FooException | BarException e)). When a line is broken at an assignment operator the break typically comes after the symbol, but either way is acceptable. This also applies to the "assignment-operator-like" colon in an enhanced for ("foreach") statement. A method or constructor name stays attached to the open parenthesis (() that follows it. A comma (,) stays attached to the token that precedes it. A line is never broken adjacent to the arrow in a lambda, except that a break may come immediately after the arrow if the body of the lambda consists of a single unbraced expression. Examples:
MyLambda<String, Long, Object> lambda =
(String label, Long value, Object obj) -> {
...
};
Predicate<String> predicate = str ->
longExpressionInvolving(str);
Note: The primary goal for line wrapping is to have clear code, not necessarily code that fits in the smallest number of lines.
When line-wrapping, each line after the first (each continuation line) is indented at least +4 from the original line.
When there are multiple continuation lines, indentation may be varied beyond +4 as desired. In general, two continuation lines use the same indentation level if and only if they begin with syntactically parallel elements.
Section 4.6.3 on Horizontal alignment addresses the discouraged practice of using a variable number of spaces to align certain tokens with previous lines.
A single blank line always appears:
Between consecutive members or initializers of a class: fields, constructors, methods, nested classes, static initializers, and instance initializers. Exception: A blank line between two consecutive fields (having no other code between them) is optional. Such blank lines are used as needed to create logical groupings of fields. Exception: Blank lines between enum constants are covered in Section 4.8.1. As required by other sections of this document (such as Section 3, Source file structure, and Section 3.3, Import statements). A single blank line may also appear anywhere it improves readability, for example between statements to organize the code into logical subsections. A blank line before the first member or initializer, or after the last member or initializer of the class, is neither encouraged nor discouraged.
Multiple consecutive blank lines are permitted, but never required (or encouraged).
Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only.
Separating any reserved word, such as if, for or catch, from an open parenthesis (() that follows it on that line Separating any reserved word, such as else or catch, from a closing curly brace (}) that precedes it on that line Before any open curly brace ({), with two exceptions: @SomeAnnotation({a, b}) (no space is used) String[][] x = {{"foo"}}; (no space is required between {{, by item 8 below) On both sides of any binary or ternary operator. This also applies to the following "operator-like" symbols: the ampersand in a conjunctive type bound: <T extends Foo & Bar> the pipe for a catch block that handles multiple exceptions: catch (FooException | BarException e) the colon (:) in an enhanced for ("foreach") statement the arrow in a lambda expression: (String str) -> str.length() but not the two colons (::) of a method reference, which is written like Object::toString the dot separator (.), which is written like object.toString() After ,:; or the closing parenthesis ()) of a cast On both sides of the double slash (//) that begins an end-of-line comment. Here, multiple spaces are allowed, but not required. Between the type and variable of a declaration: List list Optional just inside both braces of an array initializer new int[] {5, 6} and new int[] { 5, 6 } are both valid Between a type annotation and [] or .... This rule is never interpreted as requiring or forbidding additional space at the start or end of a line; it addresses only interior space.
Terminology Note: Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
This practice is permitted, but is never required by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.
Here is an example without alignment, then using alignment:
private int x; // this is fine
private Color color; // this too
private int x; // permitted, but future edits
private Color color; // may leave it unaligned
Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a "blast radius." This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.
Optional grouping parentheses are omitted only when author and reviewer agree that there is no reasonable chance the code will be misinterpreted without them, nor would they have made the code easier to read. It is not reasonable to assume that every reader has the entire Java operator precedence table memorized.
Every variable declaration (field or local) declares only one variable: declarations such as int a, b; are not used.
Exception: Multiple variable declarations are acceptable in the header of a for loop.
Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
Block comments are indented at the same level as the surrounding code. They may be in /* ... / style or // ... style. For multi-line / ... */ comments, subsequent lines must start with * aligned with the * on the previous line.
/*
* This is // And so /* Or you can
* okay. // is this. * even do this. */
*/
Comments are not enclosed in boxes drawn with asterisks or other characters.
Tip: When writing multi-line comments, use the /* ... */ style if you want automatic code formatters to re-wrap the lines when necessary (paragraph-style). Most formatters don't re-wrap lines in // ... style comment blocks.
Method names are written in lowerCamelCase.
Method names are typically verbs or verb phrases. For example, sendMessage or stop.
Underscores may appear in JUnit test method names to separate logical components of the name, with each component written in lowerCamelCase. One typical pattern is _, for example pop_emptyStack. There is no One Correct Way to name test methods.
Non-constant field names (static or otherwise) are written in lowerCamelCase.
These names are typically nouns or noun phrases. For example, computedValues or index.
Parameter names are written in lowerCamelCase.
One-character parameter names in public methods should be avoided.
Local variable names are written in lowerCamelCase.
Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.
- 5.1 Rules common to all identifiers
- 5.2.4 Constant names
- 5.3 Camel case: defined