Formatting - Geisonszo/TecProg-Emergo GitHub Wiki
Terminology Note: block-like construct refers to the body of a class, method or constructor. Note that, by Section 4.8.3.1 on array initializers, any array initializer may optionally be treated as if it were a block-like construct.
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();
}
}
};
A few exceptions for enum classes are given in Section 4.8.1, Enum classes.
An empty block or block-like construct may be closed immediately after it is opened, with no characters or line break in between ({}), unless it is part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else or try/catch/finally).
Example:
void doNothing() {}
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.)
Each statement is followed by a line break.
Java code has a column limit of 100 characters. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.5, Line-wrapping.
Exceptions:
- Lines where obeying the column limit is not possible (for example, a long URL in Javadoc, or a long JSNI method reference).
-
package
andimport
statements (see Sections 3.2 Package statement and 3.3 Import statements). - Command lines in a comment that may be cut-and-pasted into a shell.
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 (::
), the ampersand in type bounds (<T extends Foo & Bar>
), and the pipe in catch blocks (catch (FooException | BarException e)
).
- This also applies to the following "operator-like" symbols: the dot separator (
-
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.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 appears:
-
Between consecutive members (or initializers) of a class: fields, constructors, methods, nested classes, static initializers, 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.
-
-
Between statements, as needed to organize the code into logical subsections.
-
Optionally before the first member or after the last member of the class (neither encouraged nor discouraged).
-
As required by other sections of this document (such as Section 3, Source file structure, and Section 3.3, Import statements).
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
orcatch
, from an open parenthesis ((
) that follows it on that line -
Separating any reserved word, such as
else
orcatch
, 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 enhancedfor
("foreach") statement -
the arrow in a lambda expression:
(String str) -> str.length()
but not
-
the two colons (
::
) of a method reference, which is written likeObject::toString
-
the dot separator (
.
), which is written likeobject.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<String> list
-
Optional just inside both braces of an array initializer
-
new int[] {5, 6} and new int[] { 5, 6 }
are both valid
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.
After each comma that follows an enum constant, a line break is optional. Additional blank lines (usually just one) are also allowed. This is one possibility:
private enum Answer {
YES {
@Override public String toString() {
return "yes";
}
},
NO,
MAYBE
}
An enum class with no methods and no documentation on its constants may optionally be formatted as if it were an array initializer (see Section 4.8.3.1 on array initializers).
private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }
Since enum classes are classes, all other rules for formatting classes apply.
Every variable declaration (field or local) declares only one variable: declarations such as int a, b;
are not used.
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.
Any array initializer may optionally be formatted as if it were a "block-like construct." For example, the following are all valid (not an exhaustive list):
new int[] { new int[] {
0, 1, 2, 3 0,
} 1,
2,
new int[] { 3,
0, 1, }
2, 3
} new int[]
{0, 1, 2, 3}
No C-style array declarations
The square brackets form a part of the type, not the variable: String[] args
, not String args[]
.
Terminology Note: Inside the braces of a switch block are one or more statement groups. Each statement group consists of one or more switch labels (either case FOO:
or default:
), followed by one or more statements.
As with any other block, the contents of a switch block are indented +2.
After a switch label, a newline appears, and the indentation level is increased +2, exactly as if a block were being opened. The following switch label returns to the previous indentation level, as if a block had been closed.
Fall-through: commented
Within a switch block, each statement group either terminates abruptly (with a break
, continue
, return
or thrown exception), or is marked with a comment to indicate that execution will or might continue into the next statement group. Any comment that communicates the idea of fall-through is sufficient (typically / / fall through
). This special comment is not required in the last statement group of the switch block. Example:
switch (input) {
case 1:
case 2:
prepareOneOrTwo();
// fall through
case 3:
handleOneTwoOrThree();
break;
default:
handleLargeNumber(input);
}
Notice that no comment is needed after case 1:
, only at the end of the statement group.
Each switch statement includes a default statement group, even if it contains no code.
Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). These line breaks do not constitute line-wrapping (see: Line-wrapping), so the indentation level is not increased. Example:
@Override
@Nullable
public String getNameIfPresent() { ... }
Exception: A single parameterless annotation may instead appear together with the first line of the signature, for example:
@Override public int hashCode() { ... }
Annotations applying to a field also appear immediately after the documentation block, but in this case, multiple annotations (possibly parameterized) may be listed on the same line; for example:
@Partial @Mock DataLoader loader;
There are no specific rules for formatting annotations on parameters, local variables, or types.
This section addresses implementation comments. Javadoc is addressed separately in Section Javadoc.
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.
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:
public protected private abstract default static final transient volatile synchronized native strictfp
long
-valued integer literals use an uppercase L
suffix, never lowercase (to avoid confusion with the digit 1
). For example, 3000000000L
rather than 3000000000l
.