Hawstein
Source: http://hawstein.com/posts/google-java-style.html
Disclaimer: This article uses the following protocol to authorize:Free Reprint-Non-commercial-non-derivative-preserve Attribution | Creative Commons by-nc-nd 3.0 , reproduced please specify the author and source.
Directory
- Objective
- Source File Basics
- source file Structure
- Format
- Naming conventions
- Programming practices
- Javadoc
- Postscript
Objective
This document is a complete definition of the Google Java Programming style specification. When and only if a Java source file conforms to the rules in this document, we think it conforms to Google's Java programming style.
As with other programming style guides, this is not just about the beauty of the coding format, but also about conventions and coding standards. However, this document focuses primarily on the rules that we generally follow, and we try to avoid providing advice to those who are not explicitly obligated to do so.
1.1 Term description
In this document, unless otherwise noted:
- The term class can represent an ordinary class, an enumeration class, an interface, or a annotation type (@interface)
- The term comment is used only to refer to the implementation of annotations (Implementation comments), we do not use the word "documentation comments", but rather javadoc.
Other term descriptions will occasionally appear in subsequent documents.
1.2 Guide Notes
The sample code in this document is not a specification. That said, while the sample code follows Google's programming style, it doesn't mean that this is the only way to show the code. The format selection in the example should not be enforced as a rule.
Source file Base 2.1 file name
The source file is named with its topmost class name, is case-sensitive, and has a file name extension.java.
2.2 File code: UTF-8
The source file encoding format is UTF-8.
2.3 Special characters 2.3.1 whitespace characters
In addition to the line terminator sequence, the ASCII horizontal null characters (0x20, or space) is the only white space character allowed in the source file, which means:
- All whitespace characters in all other strings are escaped.
- tab characters are not used for indentation.
2.3.2 Special Escape sequences
For any character that has a special escape sequence (\b, \ t, \ n, \f, \ r, \ ", \" and \), we use its escape sequence instead of the corresponding octal (for example\012) or Unicode (for example\u000a) escape.
2.3.3 Non-ASCII characters
For the remaining non-ASCII characters, the actual Unicode characters (such as ∞) are used, or equivalent Unicode escape characters (such as \u221e) are used, depending on which one makes the code easier to read and understand.
Tip: When using Unicode escape characters or some actual Unicode characters, it is recommended to make some comments to explain, which helps others to read and understand.
For example:
String unitAbbrev = "μs"; | Like, very clear even without comments
String unitAbbrev = "\ u03bcs"; // "μs" | allowed, but there is no reason to do this
String unitAbbrev = "\ u03bcs"; // Greek letter mu, "s" | allowed, but this is clumsy and error-prone
String unitAbbrev = "\ u03bcs"; | sucks, readers do n’t see what it is
return ‘\ ufeff’ + content; // byte order mark | Good, for non-printing characters, use escapes and write comments if necessary
TIP: Never let your code become less readable because you're afraid some programs might not handle non-ASCII characters correctly. When the program does not correctly handle non-ASCII characters, it does not run correctly, and you will be able to fix these problems. (it means daring to use non-ASCII characters, if necessary.)
source file Structure
A source file contains (in order):
- License or copyright information (if required)
- Package statement
- Import statement
- A top-level class ( only one )
Each of these sections is separated by a blank line.
3.1 License or copyright information
If a file contains license or copyright information, it should be placed at the front of the file.
3.2 Package Statement
The package statement does not wrap, and the column limit (Section 4.4) does not apply to the package statement. (That is, the package statement is written in one line)
3.3 Import Statement 3.3.1 Import do not use a wildcard character
That is, do not appear with an import statement like this:import java.util.*;
3.3.2 don't change.
The import statement does not wrap, and the column limit (Section 4.4) does not apply to the import statement. (separate rows per import statement)
3.3.3 Order and Spacing
The import statement can be divided into the following groups, each separated by a blank line in this order:
- All static imports are separated into groups
- com.googleImports (only if the source file iscom.googleunder the package)
- Third-party packages. Each top-level package is a set of dictionary-ordered. For example: Android, com, junit, org, Sun
- javaImports
- javaxImports
The lines within the group are not empty, sorted by dictionary order.
Class 3.4 Declaration 3.4.1 only one top class declaration
Each top-level class is in a source file that has the same name as it (and, of course, a.javasuffix).
Exception:package-info.javaThere can be no class in the filepackage-info.
3.4.2 Class Member Order
The order of the members of a class has a great impact on usability, but there is no single universal rule. The ordering of members may be different for different classes. Most importantly, each class should sort its members with some logic, and the maintainer should be able to interpret the sort logic. For example, a new method cannot always be habitually added to the end of a class, because it is ordered in chronological order rather than some sort of logic.
3.4.2.1 Overload: Never Separate
When a class has more than one constructor, or multiple methods with the same name, these functions/methods should appear in order, not in the middle of other functions/methods.
Format
Term Description : a block structure (Block-like construct) refers to the body of a class, method, or constructor. It is important to note that the initial values in the array initialization can be optionally treated as a block structure (4.8.3.1 section).
4.1 Curly braces 4.1.1 with curly braces (even optional)
Curly bracesif, else, for, do, whileare used with statements, even if there is only one statement (or null), you should write the curly braces.
4.1.2 Non-empty blocks: K & R Style
For non-empty blocks and block structures, the braces follow the Kernighan and Ritchie styles (Egyptian brackets):
- No line break before opening curly braces
- Wrap after opening curly braces
- Wrap before closing curly braces
- If the closing brace is a statement, a function body, or the termination of a class, the closing curly brace is followed by a newline; Otherwise, the line is not wrapped. For example, if the right curly brace is followed by an else or a comma, the line is not wrapped.
Example:
return new MyClass() {
@Override public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
}
}
};
The 4.8.1 section gives some exceptions to the enum class.
4.1.3 Empty block: Can be used in a concise version
Nothing is included in an empty block structure, curly braces can be written succinctly{}, and no line breaks are required. Exception: If it is part of a multi-block statement (If/else or try/catch/finally), the closing brace is wrapped even if there is no content inside the curly braces.
Example:
void DoNothing () {}
4.2 Block indent: 2 spaces
Each time a new block is started, the indentation increases by 2 spaces, and when the block ends, the indentation returns the previous indentation level. The indentation level applies to code and comments. (See code example in Section 4.1.2)
4.3 Line one statement
Lines are wrapped after each statement.
4.4 Column limit: 80 or 100
An item can choose a 80-character or 100-character column limit, with the exception of the following, if any row exceeds the limit of the number of characters, it must be wrapped automatically.
Exception:
- Rows that cannot satisfy the column limit (for example, a long URL in Javadoc, or a long Jsni method reference).
- packageandimportstatements (see sections 3.2 and 3.3).
- Comments in the command line that may be clipped and pasted into the shell.
4.5 Automatic Line Wrapping
Terminology Description : In general, a line of code is divided into multiple lines to avoid exceeding the column limit (80 or 100 characters), which we call word wrap (line-wrapping).
We do not have comprehensive, deterministic criteria for deciding how to wrap in each case. Many times, there are several ways to wrap the same piece of code effectively.
Tip: The extraction method or local variable can solve the problem of long code without wrapping (it is reasonable to shorten the name length bar)
4.5.1 from where to disconnect
The basic guidelines for wrapping are: more inclined to break at a higher syntax level.
- If Non-assignment operator it is broken at, then break before the symbol (for example, +, it will be on the next line). Note: This is different from the programming style of other languages in Google (such as C + + and JavaScript). This rule also applies to the following "class operator" notation: Dot Delimiter (.), & () in type bounds<T extends Foo & Bar>, pipe symbol in Catch block (catch (FooException | BarException e)
- If you assignment operator disconnect at a place, it is common practice to break after the symbol (for example =, it stays on the same line as the previous content). This rule also applies toforeachsemicolons in the statement.
- The method name or constructor name stays on the same line as the left parenthesis.
- The comma (,) remains on the same line as the previous content.
4.5.2 indent at least 4 spaces when auto-wrapping is in a row
When auto-wrap, each line after the first line is indented at least 4 spaces more than the first line (note: tabs are not used for indentation.) See section 2.3.1).
When there is continuous auto-wrapping, the indentation may be indented more than 4 spaces (when there are multiple levels of syntax elements). In general, two consecutive rows use the same indentation when and only if they start at the sibling syntax element.
The 4.6.3 Horizontal Alignment section indicates that the use of a variable number of empty glyd to align the preceding line's symbols is discouraged.
4.6 Blank 4.6.1 Vertical Blank
You need to use a blank line in the following situations:
- Within a class of contiguous members: Fields, constructors, methods, nested classes, static initialization blocks, instance initialization blocks. In the body of a function, a blank line is used between logical groupings of statements.
- Exception : A blank line between two contiguous fields is optional, and the empty row used for the field is used primarily to logically group the fields.
-
- A blank line after the first member or the last member within a class is optional (neither encourages nor opposes this, depending on your preferences).
- To meet the blank line requirements for other sections in this document (e.g. Section 3.3: import statement)
Multiple consecutive empty lines are allowed, but it is not necessary to do so (we do not encourage this).
4.6.2 Horizontal Blank
In addition to language requirements and other rules, and in addition to text, annotations, and Javadoc use a single space, a single ASCII space also appears in the following places:
- Separates any reserved words from the left parenthesis ((such asif, for catch, etc.) immediately following it.
- Separates any reserved word from its preceding closing curly brace (}) (for exampleelse, catch).
- Before any opening brace ({), two exceptions:
- @SomeAnnotation({a, b})(Do not use spaces).
- String[][] x = foo;(There is no space between the braces, see note below).
- On either side of any binary or ternary operator. This also applies to the following "class operator" notation:
- & () in the type boundary<T extends Foo & Bar>.
- The pipe symbol () in the Catch blockcatch (FooException | BarException e.
- foreachThe semicolon in the statement.
- , : ;after and right parenthesis ())
- If you comment after a statement, the double slash (//) will have spaces on both sides. Multiple spaces can be allowed here, but not necessary.
- Between types and variables: List list.
- In array initialization, the spaces inside the curly braces are optional, i.e.,new int[] {5, 6}andnew int[] { 5, 6 }both are possible.
Note: This rule does not require or prohibit one line of the switch or the end requires additional space, only the internal space requirements.
4.6.3 Horizontal alignment: no requirement
term description : horizontal alignment refers to aligning the character of a line with the corresponding character of the previous line by adding a variable number of spaces.
This is allowed (and there are many places where you can see the code), but Google's programming style does not require it. Even for code that already uses horizontal alignment, we don't need to maintain that style.
The following example shows an unaligned code, followed by an aligned code:
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: Snapping increases code readability, but it can cause problems with future maintenance. Consider a future time when we need to modify a row in a bunch of aligned code. This could result in a very beautiful alignment code becoming misplaced. It is likely that it will prompt you to adjust the padding of the surrounding code so that the heap of code is re-horizontally aligned (for example, the programmer wants to maintain this level of alignment), which will allow you to do a lot of work without effort, increase reviewer and possibly lead to more merge conflicts.
4.7 using parentheses to qualify groups: recommended
Unless the author and reviewer both think that removing the parentheses will not cause the code to be misunderstood, or that the parentheses will make the code easier to read, we should not remove the parentheses. There is no reason to assume that the reader remembers the entire Java operator precedence table.
4.8 Concrete Structure 4.8.1 Enumeration class
Enumeration constants are separated by commas, and line breaks are optional.
An enumeration class without methods and documents can be written in the form of an array initialization:
Private enum Suit {CLUBS, HEARTS, Spades, DIAMONDS}
Because the enumeration class is also a class, all formatting rules that apply to other classes also apply to the enumeration class.
4.8.2 Variable declaration 4.8.2.1 declare only one variable at a time
Do not use combination declarations, for exampleint a, b;.
4.8.2.2 is declared when needed and initialized as soon as possible
Do not declare a local variable at the beginning of a block of code (this is the practice of the C language), but only when it is needed for the first time. Local variables are best initialized when declared, or initialized as soon as they are declared.
4.8.3 Array 4.8.3.1 Array initialization: Can be written as block structure
Array initialization can be written as a block structure, for example, the following notation is OK:
new int[] {
0, 1, 2, 3
}
new int[] {
0,
1,
2,
3
}
new int[] {
0, 1,
2, 3
}
new int[]
{0, 1, 2, 3}
4.8.3.2 non-C-style array declarations
The brackets are part of the type:String[] argsrather thanString args[].
4.8.4 Switch statement
Term description : A switch block is enclosed in curly braces for one or more statement groups. Each statement group contains one or more switch labels (case FOO:ordefault:) followed by one or more statements.
4.8.4.1 Indent
Consistent with other block structures, the contents of the switch block are indented into 2 spaces.
Start a new line after each switch label, then indent 2 spaces and write down one or more statements.
4.8.4.2 Fall-through: Notes
Within a switch block, each statement group terminates either bybreak, continue, returnor throwing an exception, or by a comment stating that the program will continue to execute to the next set of statements, and any comment that can express that meaning is OK (typically used// fall through). This special note does not need to appear in the last statement group (typicallydefault). Example:
switch (input) {
case 1:
case 2:
prepareOneOrTwo();
// fall through
case 3:
handleOneTwoOrThree();
break;
default:
handleLargeNumber(input);
}
4.8.4.3 the default situation is to be written.
Each switch statement contains adefaultstatement group, even if it does not contain any code.
4.8.5 Annotations (Annotations)
Annotations are immediately following the document block, applied to classes, methods, and constructors, and a single note is exclusive to one line. These line breaks do not belong to wrap (section 4.5, wrap), so the indentation level does not change. For example:
@Override
@Nullable
public String getNameIfPresent() { ... }
exception : A single annotation can appear on the same line as the first line of the signature. For example:
@Override public int hashcode () {...}
Annotations applied to a field appear immediately after the document block, and multiple annotations applied to the field allow the field to appear on the same line. For example:
@Partial @Mock Dataloader Loader;
There are no specific rules for parameter and local variable annotations.
4.8.6 notes 4.8.6.1 Block Annotation Style
The block comment is at the same indentation level as the code surrounding it. They can be either/* ... */style or// ...style. For multiple lines of/* ... */comments, subsequent lines must*start and align with the previous line*. The following sample comments are OK.
/*
* This is // And so /* Or you can
* okay. // is this. * even do this. */
*/
Note Do not enclose in frames drawn by asterisks or other characters.
Tip: When writing multiline comments, use if you want to be able to re-line if necessary (that is, the comment is like a paragraph style)/* ... */.
4.8.7 Modifiers
The modifiers of classes and members appear in the order recommended by the Java language Specification, if they exist.
Public protected private abstract static final transient volatile synchronized native STRICTFP
Naming convention 5.1 rules that are common to all identifiers
Identifiers can only use ASCII letters and numbers, so each valid identifier name can match a regular expression\w+.
Special prefixes or suffixes used in other Google programming language styles, such as,name_, mName s_nameandkName, are no longer used in the Java programming style.
5.2 Rule 5.2.1 Package name for identifier type
The package name is all lowercase, and successive words are simply concatenated, without underlining.
5.2.2 Class Name
Class names areUpperCamelCasewritten in style.
The class name is usually a noun or noun phrase, and the interface name can sometimes be an adjective or an adjective phrase. There are no specific rules or valid conventions for naming annotation types.
The test class is named to end with the name of the class it wants to testTest. For example,HashTestorHashIntegrationTest.
5.2.3 Method Name
Method names arelowerCamelCasewritten in style.
The method name is usually a verb or a verb phrase.
The underscore may appear in the JUnit test method name to separate the logical components of the name. A typical pattern is:test<MethodUnderTest>_<state>, for exampletestPop_emptyStack. There is no single right way to name a test method.
5.2.4 Constant Name
The constant name is named ModeCONSTANT_CASE, with all uppercase letters, and the words separated by underscores. So, what exactly is a constant?
Each constant is a static final field, but not all static final fields are constants. When deciding whether a field is a constant, consider whether it really feels like a constant. For example, if any one of the observed states of the instance is mutable, it will almost certainly not be a constant. Just never打算change the object generally is not enough, it must be really unchanged in order to show it as a constant.
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
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 Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};
These names are usually nouns or noun phrases.
5.2.5 Number of field names
The number of field names islowerCamelCasewritten in style.
These names are usually nouns or noun phrases.
5.2.6 Name of the parameter
The name of the parameter islowerCamelCasewritten in style.
Parameters should avoid naming with a single character.
5.2.7 local variable name
Local variable nameslowerCamelCaseare written in style, and local variable names can have looser abbreviations than other types of names.
Although the abbreviations are looser, you should avoid naming them with single characters, except for temporary and cyclic variables.
Even if the local variable is final and immutable, it should not be shown as a constant, nor can it be named with constant rules.
5.2.8 type variable Name
Type variables can be named in one of the following two styles:
- A single uppercase letter, followed by a number (such as: E, T, X, T2).
- Named by Class (5.2.2), followed by an uppercase T (for example: Requestt, Foobart).
5.3 Camel-named method (CamelCase)
The Hump-type nomenclature is divided into large hump-type nomenclature (UpperCamelCase) and small hump-type nomenclature (lowerCamelCase). Sometimes we have more than one reasonable way to convert an English phrase into a hump form, such as an abbreviation or an unusual structure (such as "IPv6" or "IOS"). Google has specified the following conversion scenarios.
The name散文形式begins with (prose form):
- Converts a phrase to a pure ASCII code and removes any single quotation marks. For example: "Müller ' s Algorithm" will become "Muellers algorithm".
- Divide the result into words, separated by spaces or other punctuation (often hyphens).
- Recommendation: If a word already has a common hump representation, split it up by its composition (such as "AdWords" will split into "ad words"). It is important to note that "IOS" is not a real hump representation, so the recommendation does not apply to it.
- Now all the letters are lowercase (including abbreviations), then capitalize the first letter of the word: Finally, all the words are concatenated together to get an identifier.
- The first letter of each word is capitalized, and comes to a large hump-type name.
- In addition to the first word, the first letter of each word is capitalized to get a small hump-type name.
-
Example:
Prose form Correct Incorrect
------------------------------------------------------------------
"XML HTTP request" XmlHttpRequest XMLHTTPRequest
"new customer ID" newCustomerId newCustomerID
"inner stopwatch" innerStopwatch innerStopWatch
"supports IPv6 on iOS?" supportsIpv6OnIos supportsIPv6OnIOS
"YouTube importer" YouTubeImporter
YoutubeImporter*
Asterisking indicates yes, but not recommended.
Note: in English, some word forms with hyphens are not unique. For example: "NonEmpty" and "non-empty" are all correct, so the method namecheckNonemptyandcheckNonEmptyboth are correct.
Programming Practice 6.1 @Override: can be used
As long as it is legal,@Overrideuse the annotations.
6.2 Caught exception: Can't ignore
In addition to the following example, it is rarely correct to respond to a caught exception. (A typical response is to print the log, or if it is considered impossible, treat it as a re-AssertionErrorthrow.) )
If it does not need to do any response in the catch block, a comment is required (as in the example below).
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 a test, if a caught exception is namedexpected, it can be ignored without comment. The following is a very common scenario to ensure that the method being tested throws an expected exception, so there is no need to annotate it here.
try {
emptyStack.pop();
fail();
} catch (NoSuchElementException expected) {
}
6.3 Static members: calling using the class
Use the class name to invoke a static class member instead of a specific object or expression.
Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very bad
6.4 Finalizers: Disable
Rarely to be overloadedObject.finalize.
TIP: Do not use finalize. If you want to use it, please read and understand effective Java 7th: "Avoid finalizers", then do not use it.
Javadoc7.1 Format 7.1.1 General form
The basic format of the Javadoc block is as follows:
/**
* Multiple lines of Javadoc text are written here,
* wrapped normally...
*/
public int method(String p1) { ... }
Or one of the following single-line forms:
/** a especially short bit of Javadoc. */
The basic format is always OK. A single-line form can be used when the entire Javadoc block can fit into a row (and there is no Javadoc tag @xxx).
7.1.2 Paragraph
Blank lines (that is, rows that contain only the leftmost asterisk) appear between paragraphs and before the Javadoc tag (@XXX), if any. In addition to the first paragraph, each paragraph has a label before the first word<p>, and there are no spaces between it and the first word.
7.1.3 Javadoc Mark
The standard Javadoc tags appear in the following order:,,,@param @return @throws @deprecatedbefore these 4 kinds of tags appear, the description cannot be empty. When the description cannot be accommodated in a row, successive lines need to be indented at least 4 more spaces.
7.2 Summary Fragments
The Javadoc of each class or member begins with a short digest fragment. This fragment is very important, and in some cases it is the only text that appears, such as in the class and method indexes.
This is just a small fragment, can be a noun phrase or a verb phrase, but not a complete sentence. It will notA {@code Foo} is a...start with orThis method returns...begin, and it will not be a complete imperative, as inSave the record.... However, it looks like a complete sentence because it is capitalized and punctuation is added.
TIP: A common mistake is to write a simple Javadoc/** @return the customer ID */, which is not true. It should be written/** Returns the customer ID. */.
7.3 Where to use Javadoc
Use Javadoc at least for each public class and every public and protected member of it, here are some exceptions:
7.3.1 Exceptions: Self-explanatory methods
For simple and obvious methods such asgetFoo, Javadoc is optional (i.e., can not be written). In this case, in addition to writing "Returns the Foo", there is really nothing worth writing about.
The test methods in the unit test class are probably the most common examples of self-evident, and we can usually tell from the descriptive naming of these methods what it does, so no additional documentation is required.
TIP: If there is some information that needs to be understood by the reader, the above exceptions should not be a justification for ignoring this information. For example, thegetCanonicalNamedocument description should not be overlooked for the method name because the reader may not knowcanonical namewhat the word refers to.
7.3.2 Exceptions: Overloading
If a method overloads a method in a superclass, then Javadoc is not required.
7.3.3 Optional Javadoc
For classes and methods that are not visible outside the package, you also want to use Javadoc if necessary. If a comment is used to define the overall purpose or behavior of a class, method, field, then this annotation should be written as Javadoc, which is more uniform and friendlier.
Postscript
This document is translated from Google Java Style, author @hawstein.
Google Java Programming style guide Chinese version (GO)