-
Notifications
You must be signed in to change notification settings - Fork 3
Coding Style Definitions
Coding conventions used in this project are extracted from the Google Java Guide listed here.
Definitions:
- Whitespace characters : Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file.
This implies that:
- All other whitespace characters in string and character literals are escaped.
- Tab characters are not used for indentation.
- Special escape sequences : For any character that has a special escape sequence (\b, \t, \n, \f, \r, ", ' and \), that sequence is used rather than the corresponding octal (e.g. \012) or Unicode (e.g. \u000a) escape.
-
Braces :Braces are used with
if,else,for,doandwhilestatements, even when the body is empty or contains only a single statement. -
Nonempty blocks: K & R style :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();
}
}
};-
Empty blocks :An empty block or block-like construct may be in K & R style. Alternatively, it 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
Examples:
// This is acceptable
void doNothing() {}
// This is equally acceptable
void doNothingElse() {
} // This is not acceptable: No concise empty blocks in a multi-block statement
try {
doSomething();
} catch (Exception e) {}- One statement per line: Each statement is followed by a line break.
-
Vertical Whitespace: A single blank line 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.
- Between statements, as needed to organize the code into logical subsections.
- Optionally before the first member or initializer, or after the last member or initializer of the class (neither encouraged nor discouraged).
- Multiple consecutive blank lines are permitted, but never required (or encouraged).
- Between consecutive members or initializers of a class: fields, constructors, methods, nested classes, static initializers, and instance initializers.
-
Horizontal Whitespace: 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,fororcatch, from an open parenthesis (() that follows it on that line - Separating any reserved word, such as
elseorcatch, 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 the last item 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()
- the ampersand in a conjunctive type bound:
- 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}andnew int[] { 5, 6 }are both valid
-
- Separating any reserved word, such as
This rule is never interpreted as requiring or forbidding additional space at the start or end of a line; it addresses only interior space.
-
Variable declarations
-
One variable per declaration: Every variable declaration (field or local) declares only one variable: declarations such as
int a, b;are not used.
-
One variable per declaration: Every variable declaration (field or local) declares only one variable: declarations such as
Exception: Multiple variable declarations are acceptable in the header of a for loop.
- Declared when needed: 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.
-
Arrays
- Array initializers: can be "block-like": 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}-
Comments: Any line break may be preceded by arbitrary whitespace followed by an implementation comment. Such a comment renders the line non-blank.
-
Block comment style: 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.
-
Block comment style: Block comments are indented at the same level as the surrounding code. They may be in
/*
* This is // And so /* Or you can
* okay. // is this. * even do this. */
*/- Modifiers: 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-
Rules common to all identifiers: Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores. Thus each valid identifier name is matched by the regular expression
\w+.
In Google Style special prefixes or suffixes, like those seen in the examples name_, mName, s_name and kName, are not used.
-
Package names: Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example,
com.example.deepspace, notcom.example.deepSpaceorcom.example.deep_space. -
Class names: Class names are written in
UpperCamelCase.
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).
Test classes are named starting with the name of the class they are testing, and ending with Test. For example, HashTest or HashIntegrationTest.
-
Method names: Method names are written in
lowerCamelCase.
Method names are typically verbs or verb phrases. For example, sendMessage or stop.
-
Constant names: Constant names use
CONSTANT_CASE: all uppercase letters, with each word separated from the next by a single underscore.
Examples:
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final ImmutableMap<String, SomeMutableType> mutableValues =
ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};-
@Override: always used: A method is marked with the@Overrideannotation whenever it is legal. This includes a class method overriding a superclass method, a class method implementing an interface method, and an interface method respecifying a superinterface method. -
Caught exceptions: not ignored: Except as noted below, it is very rarely correct to do nothing in response to a caught exception.
try {
int i = Integer.parseInt(response);
return handleNumericResponse(i);
} catch (NumberFormatException ok) {
// it's not numeric; that's fine, just continue
}
return handleTextResponse(response);Exception: In tests, a caught exception may be ignored without comment if its name is or begins with expected. The following is a very common idiom for ensuring that the code under test does throw an exception of the expected type, so a comment is unnecessary here.
try {
emptyStack.pop();
fail();
} catch (NoSuchElementException expected) {
}- General form: The basic formatting of Javadoc blocks is as seen in this example:
/**
* Multiple lines of Javadoc text are written here,
* wrapped normally...
*/
public int method(String p1) { ... }.. or in this single-line example:
/** An especially short bit of Javadoc. */The basic form is always acceptable. The single-line form may be substituted when the entirety of the Javadoc block (including comment markers) can fit on a single line. Note that this only applies when there are no block tags such as @return.
-
- Sprint 1
- Sprint 2
- Sprint 3
- Sprint 4