Java Coding Standards (Google version)

[Citation description]
This article is excerpted from: http://hawstein.com/posts/google-java-style.html

[Foreword]
This document is the complete definition of the Google Java programming style specification. We consider a Java source file to conform to Google's Java programming style if and only if it conforms to the rules in this document.
As with other programming style guides, it's not just the aesthetics of coding formats that are discussed here, but also some conventions and coding standards. However, this document mainly focuses on the rules we generally follow, and we try to avoid providing opinions on those that are not explicitly mandated.

1.1 Terminology Description
In this document, unless otherwise specified: the
term class may refer to a common class, enumeration class, interface or annotation type (@interface).
The term comment is only used to refer to implementation comments, we Don't use the term "documentation comments", use Javadoc instead.
Additional terminology descriptions will occasionally appear in later documents.

1.2 Guidelines Description The sample code in
this document is not intended to be a specification. That said, while the sample code follows Google's programming style, it doesn't mean it's the only way to present it. The formatting choices in the example should not be enforced as rules.

[Source file basics]
2.1 File name The
source file is named by its top-level class name, case-sensitive, and the file extension is .java.

2.2 File encoding: UTF-8
source file encoding format is UTF-8.

2.3 Special characters
2.3.1 Whitespace characters
In addition to line terminator sequences, the ASCII horizontal whitespace character (0x20, or space) is the only whitespace character allowed in the source file, which means:
all other whitespace characters in strings are escaped.
Tabs are not used for indentation.

2.3.2 Special escape sequences
For any character with a special escape sequence (\b, \t, \n, \f, \r, \", \' and \), we use its escape sequence, and Not the corresponding octal (such as \012) or Unicode (such as \u000a) escape.

2.3.3 Non-ASCII characters
For the remaining non-ASCII characters, whether to use the actual Unicode character (such as ∞), or use the equivalent Unicode conversion Escape characters (such as \u221e), depending on which 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, this will help others Read and understand.

For example:
String unitAbbrev = "μs"; | Like, very clear even without comments
String unitAbbrev = "\u03bcs"; // "μs" | Allowed, but no reason to do it
String unitAbbrev = "\u03bcs "; // Greek letter mu, "s" | Allowed, but clumsy and error-prone
String unitAbbrev = "\u03bcs";

return '\ ufeff ' + content; // byte order mark | Good, use escaping for non-printing characters, and write comments if necessary Your code becomes less readable. When a program doesn't handle non-ASCII characters correctly, it doesn't work correctly, and you're going to fix those problems. (The implication is to boldly use non-ASCII characters, if really necessary)

[Source file structure]
A source file contains (in order):

license or copyright information (if necessary)
package statement
import statement
a Each section above the top-level class (only one)
is separated by a blank line.

3.1 License or copyright information
If a file contains license or copyright information, it should be placed first in the file.

3.2 The package statement
The package statement does not wrap, and the column restrictions (section 4.4) do not apply to the package statement. (that is, the package statement is written in one line)

3.3 import statement
3.3.1 Do not use wildcards for import
That is , do not appear in an import statement like this: import java.util.*;

3.3.2 Do not wrap the
import statement without wrapping, column restrictions (4.4 section) does not apply to import statements. (Each import statement is on its own line)

3.3.3 Order and spacing
Import statements can be divided into the following groups, in this order, each group is separated by a blank line:

all static imports are grouped independently of
com.google imports (only if the source file is under the com.google package)
third-party packages . Each top-level package is a set, lexicographically. For example: android, com, junit, org, sun
java imports
javax imports
group without blank lines, in lexicographical order.

3.4 Class declarations
3.4.1 Only one top-level class declaration
Each top-level class is in a source file with the same name as it (with the .java suffix, of course).
Exception: package-info.java, there may be no package-info class in this file.

3.4.2 Order of class members The order
of class members has a strong impact on learnability, but there is no single general rule. The ordering of members may be different for different classes. Most importantly, each class should have some logic to order its members, and the maintainer should be able to explain this ordering logic. For example, new methods cannot always be habitually added to the end of a class, because that would be chronological rather than logical ordering.

3.4.2.1 Overloading: Never Separation
When a class has multiple constructors or multiple methods with the same name, these functions/methods should appear together in order, and do not put other functions/methods in between.

【Format】
Term Description: Block-like construct refers to the body of a class, method or constructor. Note that initial values ​​in array initialization can optionally be treated as block structures (Section 4.8.3.1).

4.1 Braces
4.1.1 Use curly braces (even if optional)
Curly braces are used with if, else, for, do, while statements, even if there is only one statement (or empty), the curly braces should be written.

4.1.2 Non-empty blocks: K & R style
For non-empty blocks and block-like structures, braces follow the Kernighan and Ritchie style (Egyptian brackets):

no newline
before opening brace, newline after opening brace, newline
before closing brace,
if right If the curly brace is the termination of a statement, function body, or class, a newline occurs after the closing curly brace; otherwise, no newline occurs. For example, if the closing brace is followed by an else or a comma, no line break is made.

Example:
return new MyClass() {
  @Override public void method() {
    if (condition()) {
      try {
        something();
      } catch (ProblemException e) {
        recover();
      }
    }
  }
};
Section 4.8.1 gives Some exceptions from the enum class are made.

4.1.3 Empty block: a concise version can be used
An empty block structure contains nothing, and curly braces can be written as {} concisely without newlines. Exception: If it is part of a multi-block statement (if/else or try/catch/finally), the closing brace wraps even if there is nothing inside the brace.

Example:
void doNothing() {}

4.2 Block indent: 2 spaces
Whenever a new block starts, the indent increases by 2 spaces, and when the block ends, the indent returns to the previous indent level. Indentation levels apply to code and comments. (See the code example in Section 4.1.2)

4.3 One statement per line Use a new line after
each statement.

4.4 Column Limit: 80 or 100
One item can choose a column limit of 80 characters or 100 characters in a line, except for the following exceptions, if any line exceeds this character limit, it must automatically wrap.

Exception: Lines that
cannot satisfy the column limit (for example, a long URL in the Javadoc, or a long JSNI method reference).
package and import statements (see Sections 3.2 and 3.3).
Command lines in comments that may be cut and pasted into the shell.

4.5 Automatic Line
Wrapping Terminology Note: In general, a line of long code is divided into multiple lines in order to avoid exceeding the column limit (80 or 100 characters), which is called automatic line wrapping (line-wrapping).
We don't have comprehensive, deterministic guidelines for how to wrap lines in every situation. Many times, there are several valid word wrapping methods for the same piece of code.
Tip: Extracting methods or local variables can solve the problem of too long code without wrapping lines (it is a reasonable way to shorten the name length)

4.5.1 Where to break
The basic rule of thumb for word wrapping is: prefer to break at a higher syntactic level.
If you break at a non-assignment operator, then break before that symbol (like +, which will be on the next line). Note: This is different from Google's programming style in other languages ​​(eg C++ and JavaScript). This rule also applies to the following "class operator" symbols: dot separator (.), & in type bounds (<T extends Foo & Bar>), pipe in catch blocks (catch (FooException | BarException e)
If you break at an assignment operator, it's common practice to break after that symbol (like =, which stays on the same line as what came before it). This rule also applies to semicolons in foreach statements.
Method names or The constructor name and the opening parenthesis stay on the same line.
The comma (,) stays on the same line as the content before it.

4.5.2 Indent at least +4
spaces when wrapping lines. When wrapping lines, each line after the first line is at least longer than The first line is indented by more than 4 spaces (Note: the tab character is not used for indentation. See section 2.3.1).
When there is continuous word wrapping, the indentation may be more than 4 spaces indented (syntax elements exist more than 4 spaces) level). In general, two consecutive lines use the same indentation if and only if they begin with
a syntactic element of the same level. Section 4.6.3 Horizontal Alignment states that the use of variable numbers of spaces to align the front is discouraged

4.6 Blank
4.6.1 Vertical Blank A blank row is required in
the following cases :

Between consecutive members within a class: fields, constructors, methods, nested classes, static initializer blocks, instance initializer blocks.
Exceptions: two Blank lines between consecutive fields are optional, and blank lines for fields are mainly used to logically group fields.
In the function body, blank lines are used between logical groupings of statements.
Blank lines before the first member or after the last member within a class are optional (neither encouraged nor discouraged, depending on personal preference).
To satisfy the blank-line requirements of other sections in this document (such as Section 3.3: Import Statements)
multiple consecutive blank lines are permitted, but not necessary (and are not encouraged).

4.6.2 Horizontal whitespace
In addition to language requirements and other rules, and in addition to the use of a single whitespace in text, comments and Javadoc, a single ASCII whitespace also occurs in the following places:

separating any reserved word from the immediately following opening bracket (() (like if, for catch, etc.).
Separates any reserved word from its preceding closing brace (}) (like else, catch).
Before any opening brace ({), two exceptions:
@SomeAnnotation({a, b }) (no spaces are used).
String[][] x = foo; (no spaces between curly brackets, see Note below).
On either side of any binary or ternary operator. This also applies to the following "classes" operator" notation:
&(<T extends Foo & Bar>) in type bounds.
Pipe notation (catch (FooException | BarException e) in catch block.
Semicolon in foreach statement.
Between , : ; and closing bracket ( After ))
If a comment is made after a statement, there should be spaces on both sides of the double slash (//). Multiple spaces are allowed here, but not necessary.
Between types and variables: List list.
In array initialization, spaces within curly braces are optional, that is, new int[] {5, 6} and new int[] { 5, 6 } are both acceptable.
Note: This rule does not require or prohibit extra whitespace at the end of a line switch or at the end, only internal whitespace is required.

4.6.3 Horizontal alignment: not required
Terminology note: Horizontal alignment refers to aligning the characters of a line with the corresponding characters of the previous line by adding a variable number of spaces.
This is allowed (and you can see such code in quite a few places), but the Google style of programming doesn't require it. We don't need to keep this style even for code that already uses horizontal alignment.

The following example shows unaligned code first, then 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: Alignment increases code readability, but it creates problems for future maintenance. Consider that at some point in the future, we need to modify a line in a bunch of aligned code. This can cause otherwise beautiful alignment code to become misaligned. Most likely it will prompt you to adjust the whitespace around the code to realign the pile of code horizontally (like the programmer wants to keep this horizontally aligned style), which will make you do a lot of wasted work, increase the work of the reviewer and May lead to more merge conflicts.

4.7 Use parentheses to delimit groups: recommended
We should not remove parentheses unless both the author and the reviewer feel that removing the parentheses will not make the code misunderstood, or that removing the parentheses makes the code easier to read. There is no reason to assume that the reader can memorize the entire Java operator precedence table.

4.8 Concrete structure
4.8.1 Enumeration class The
enumeration constants are separated by commas, and line breaks are optional.
An enum class without methods and documentation can be written in the format of array initialization:
private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }
Since an enum class is also a class, all formatting rules that apply to other classes also apply to enum classes .

4.8.2 Variable declarations
4.8.2.1 Declare only one variable at a time
Do not use combined declarations such as int a, b;.

4.8.2.2 Declare only when needed, and initialize it as soon as possible
Do not declare a local variable at the beginning of a code block (this is the practice of C language), but declare it when you need it for the first time. Local variables are best initialized when they are declared, or as soon as possible after they are declared.

4.8.3 Arrays
4.8.3.1 Array initialization: can be written as a block structure
Array initialization can be written as a block structure, for example, the following writing 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 Brackets are part of the type: String[] args, not String args[].

4.8.4 switch statement
Terminology note: The braces of a switch block are one or more groups of statements. Each statement group consists of one or more switch labels (case FOO: or default: ) followed by one or more statements.

4.8.4.1 Indentation Consistent
with other block structures, the content of a switch block is indented by 2 spaces.
Start a new line after each switch label, indent 2 spaces, and write one or more statements.

4.8.4.2 Fall-through: Comments
Within a switch block, each statement group is terminated either by break, continue, return, or throwing an exception, or by a comment indicating that program execution will continue to the next statement group, any Comments that express this are OK (typically // fall through). This special comment does not need to appear in the last statement group (usually default).

Example:
switch (input) {
  case 1:
  case 2:
    prepareOneOrTwo();
    // fall through
  case 3:
    handleOneTwoOrThree();
    break;
  default:
    handleLargeNumber(input);
}

4.8.4.3 The default case is to be written out
Every switch statement contains a default statement group, even if it contains no code.

4.8.5 Annotations Annotations
follow the documentation block and apply to classes, methods and constructors. An annotation is on a line by itself. These line breaks are not word wrapping (section 4.5, Word wrapping), so the indentation level is unchanged.

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 documentation block, and multiple annotations applied to a field are allowed to appear on the same line as the field.

For example:
@Partial @Mock DataLoader loader;
There are no specific rules for parameter and local variable annotations.

4.8.6 Comments
4.8.6.1 Block comment style
Block comments are at the same indentation level as the surrounding code. They can be either /* ... */ style or // ... style. For multi-line /* ... */ comments, subsequent lines must start with * and align with * on the previous line. The following example comments are all OK.

/*
* This is // And so /* Or you can
* okay. // is this. * even do this. */
*/
Comments should not be enclosed in frames drawn by asterisks or other characters.
Tip: When writing a multi-line comment, if you want to re-wrap when necessary (ie the comment behaves like a paragraph), then use /* ... */.

4.8.7 Modifiers
Class and member modifiers, if present, appear in the order recommended by the Java Language Specification.
public protected private abstract static final transient volatile synchronized native strictfp

[naming convention]
5.1 Rules common to all identifiers
Identifiers can only use ASCII letters and numbers, so every valid identifier name can match the regular expression \w+ .
Special prefixes or suffixes used in other Google programming language styles, such as name_, mName, s_name and kName, are no longer used in Java programming style.

5.2 Rules for Identifier Types
5.2.1 Package Name
Package names are all lowercase, and consecutive words are simply concatenated without underscores.

5.2.2 Class Names
Class names are written in UpperCamelCase style.
Class names are usually nouns or noun phrases, and interface names may sometimes be adjectives or adjective phrases. There is currently no specific rule or well-established convention for naming annotation types.
The naming of a test class begins with the name of the class it is testing and ends with Test. For example, HashTest or HashIntegrationTest.

5.2.3 Method names
Method names are written in lowerCamelCase style.
Method names are usually verbs or verb phrases.
Underscores may appear in JUnit test method names to separate logical components of the name. A typical pattern is: test<MethodUnderTest>_<state>, eg testPop_emptyStack. There is no single correct way to name test methods.

5.2.4
Constant names The naming pattern of constant names is CONSTANT_CASE, all letters are capitalized, and words are separated by underscores. So, what exactly is a constant?
Every 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 the observed state of any one of the instances is mutable, it will almost certainly not be a constant. Just never intending to mutate an object is generally not enough, it has to be really constant to show it as a constant.

// Constants
static final int NUMBER = 5;















Non-constant field names are written in lowerCamelCase style.
These names are usually nouns or noun phrases.

5.2.6 Parameter names
Parameter names are written in lowerCamelCase style.
Parameters should avoid single character names.

5.2.7 Local variable names
Local variable names are written in the lowerCamelCase style and may have looser abbreviations than other types of names.
Although abbreviations are looser, avoid single-character names, except for temporary variables and loop variables.
Even if a local variable is final and immutable, it should not be shown as a constant, and naturally it cannot be named using the rules for constants.

5.2.8 Type variable names
Type variables can be named in one of two styles:
a single uppercase letter, which can be followed by a number (eg E, T, X, T2).
In the class naming method (section 5.2.2), followed by an uppercase T (eg RequestT, FooBarT).

5.3 CamelCase (CamelCase) CamelCase
is divided into a large camelCase (UpperCamelCase) and a small camelCase (lowerCamelCase). Sometimes we have more than one reasonable way to convert an English phrase to camel case, like an abbreviation or unusual construction (eg "IPv6" or "iOS"). Google specifies the following conversion schemes.
Names start in prose form:
convert the phrase to plain ASCII, and remove any single quotes. For example: "Müller's algorithm" will become "Muellers algorithm".
Split this result into words, separated by spaces or other punctuation marks (usually hyphens).
Recommendation: If a word already has a common camelcase representation, split it by its composition (eg "AdWords" will be split into "ad words"). Note that "iOS" is not a true camelcase representation, so this recommendation does not apply to it.
Now lowercase all letters (including abbreviations), then capitalize the first letter of the word:
the first letter of each word is capitalized to get camelCase names.
The first letter of each word except the first is capitalized to get the little camel case name.
Finally concatenate all the words to get an identifier.

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 *
Asterisks indicate yes, but not recommended.

Note: Some word forms with hyphens are not unique in English. For example: "nonempty" and "non-empty" are both correct, so are the method names checkNonempty and checkNonEmpty.

[Programming Practice]
6.1 @Override: Use if you can.
As long as it is legal, use the @Override annotation.

6.2 Caught Exceptions: Don't Ignore
Except for the following examples, it is rarely correct to not respond to caught exceptions. (Typical responses are to print the log, or re-throw it as an AssertionError if it's deemed impossible.)
If it really doesn't require any response in the catch block, it needs to be commented out (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);
Exceptions: In tests, if a caught exception is named expected, it can be ignored without comment. The following is a very common situation to ensure that the method under test throws an expected exception, so there is no need for a comment here.

try {
  emptyStack.pop();
  fail();
} catch (NoSuchElementException expected) {
}

6.3 Static Members: Calling with a Class Call a static class member
using the class name, not an object or expression.

Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very bad

6.4 Finalizers: disabled
Rarely overloads Object.finalize .
Tip: Don't use finalize. If you must use it, please read and understand Effective Java Clause 7: "Avoid Finalizers" carefully, and then don't use it.

[Javadoc]
7.1 Format
7.1.1 General Form
The basic format of a Javadoc block is as follows:

/**
* Multiple lines of Javadoc text are written here,
* wrapped normally...
*/
public int method(String p1) { ... }
or the following single-line form:

/** An especially short bit of Javadoc. */
Basic format always ok. When the entire Javadoc block fits on one line (and there is no Javadoc tag @XXX), the single-line form can be used.

7.1.2 Paragraphs
Blank lines (ie, lines containing only the leftmost asterisk) appear between paragraphs and before Javadoc tags (@XXX), if any. Except for the first paragraph, each paragraph has the tag <p> before the first word, and there is no space between it and the first word.

7.1.3 Javadoc tags The
standard Javadoc tags appear in the following order: @param, @return, @throws, @deprecated. If these four tags appear, the description cannot be empty. When the description does not fit on one line, consecutive lines need to be indented at least 4 more spaces.

7.2 Summary Fragments The Javadoc for
each class or member begins with a short summary fragment. This snippet is so important that in some cases it is the only text that appears, such as in class and method indexes.
It's just a small snippet, it can be a noun phrase or a verb phrase, but it's not a complete sentence. It won't start with A {@code Foo} is a... or This method returns..., nor will it be a complete imperative like Save the record.... However, because of the capitalization and punctuation, it looks like a complete sentence.
Tip: A common mistake is to write simple Javadoc as /** @return the customer ID */, which is incorrect. It should be written as /** Returns the customer ID. */.

7.3 Where to use Javadoc Javadoc is used
at least on every public class and every public and protected member of it, with some exceptions:

7.3.1 Exceptions: Self-explanatory methods Javadoc is optional
for simple and obvious methods like getFoo (ie, can not be written). There's really nothing worth writing in this case other than "Returns the foo".
A test method in a unit test class is probably the most self-explanatory example, we usually know what it does from the descriptive naming of these methods, so no additional documentation is needed.
Tip: If there is some relevant information that the reader needs to know, the exception above should not be used as a reason to ignore that information. For example, for the method name getCanonicalName, the documentation should not be ignored, since the reader is likely to have no idea what the term canonical name refers to.

7.3.2 Exception: Overloading Javadoc is not required
if a method overrides a method in a superclass.

7.3.3 Optional Javadoc
For classes and methods that are not visible outside the package, Javadoc is also used if necessary. If a comment is used to define the overall purpose or behavior of a class, method, or field, then the comment should be written as Javadoc, which is more uniform and friendly.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326566126&siteId=291194637