Google Java Style
Google Java style defines some hard-and-fast rules, no non-enforceable advices.
- Import ordering:
- All static import.
- First-party packages.
- Third-party packages.
- java imports.
- javax imports.
- Class member ordering: It should have some logical order, but no hard and fast rule here.
- Overloads (and constructors) should appear sequentially, with no intervening members.
- Always use braces, even when the body of a block contains only one statement.
- Egyptian brackets.
- No line break after the brace if it is followed by a comma.
- A few exceptions for enum classes and empty block
{}.
- Some exceptions for column limit:
- A long URL in Javadoc.
- Command lines in a comment that may be cut-and-pasted into a shell.
- package and import statements.
- Line wrapping:
- Prefer to break at a higher syntactic level.
- At least +4 spaces.
- Space rules:
@SomeAnnotation({a, b})
String[][] x = foo;
new int[] {5, 6};
for (x : collection) {}
(X) x; // Space in casting.
enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }- Horizontal alignment: Never required.
- One variable per declaration. Declare when needed, initialized as soon as possible.
int a;
int b;- Array initializers can be block-like:
new int[] {
0, 1,
2, 3,
};- Fall-through in a switch case must be commented
// fall through. defaultstatement must be present, even if it contains no code.- Modifier ordering:
public protected private abstract static final transient volatile synchronized native strictfp long-valued literals use an uppercaseLsuffix, never lowercase.- Naming rules:
- Generally, don’t use underscores.
ThisIsClassthisIsMethod- Underscores may appear in JUnit test method names:
test<MethodUnderTest>_<state> CONSTANT_CASEnonConstantFieldNames(static or otherwise) with no ‘m’ or ‘s’ prefix.XmlHttpRequest // Acronyms.customerId // Id.supportsIpv6OnIos // IPv6 and iOS.YouTubeImporter, AdWords // YouTube and AdWords.
- You should always use
@Overrideunless when the parent method is@Deprecated. - Exception for empty
catchblock in tests (use special nameexpected):
try {
emptyStack.pop();
fail();
} catch (NoSuchElementException expected) {
}- At-clauses ordering in Javadoc:
@param,@return,@throws,@deprecated. - When an at-clause doesn’t fit on a single line, continuation lines are indented 4+ spaces from the position of the @.
- Javadoc summary fragments are not a (imperative) sentence. They are usually just a noun phrase or verb phrase.
