Google Java Programming style guide Chinese version

Source: Internet
Author: User
Tags coding standards modifiers printable characters word wrap


Hawstein
Source: http://hawstein.com/posts/google-java-style.html
Disclaimer: This document is licensed under the following protocols: Free reprint-Non-commercial-non-derivative-retention Attribution | Creative Commons by-nc-nd 3.0, reproduced please specify the author and source.

Directory
    1. Objective
    2. Source File Basics
    3. source file Structure
    4. Format
    5. Naming conventions
    6. Programming practices
    7. Javadoc
    8. 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:


    1. The term class can represent an ordinary class, an enumeration class, an interface, or a annotation type (@interface)
    2. 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:


    1. All whitespace characters in all other strings are escaped.
    2. 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 so
String unitAbbrev = "\ u03bcs"; // Greek letter mu, "s" | Allowed, but this is awkward and error-prone
String unitAbbrev = "\ u03bcs"; | Very bad, the reader ca n’t see what this is
return ‘\ ufeff’ + content; // byte order mark | Good, for non-printable characters, use escape and write a comment if necessary
Tip: Never make your code less readable due to fear that some programs may not handle non-ASCII characters correctly. When the program cannot correctly handle non-ASCII characters, it will naturally not run correctly, and you will fix these problems. (The implication is to use non-ASCII characters boldly 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 part above is separated by a blank line.

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

3.2 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 on one line)

3.3 import statement 3.3.1 import do not use wildcards
That is, do not appear such import statements: import java.util. *;

3.3.2 Don't wrap
Import statements do not wrap, and column restrictions (Section 4.4) do not apply to import statements. (Each import statement is a separate line)

3.3.3 Sequence 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
com.google imports (only if this source file is under the com.google package)
Third-party packages. Each top-level package is a group, lexicographical. For example: android, com, junit, org, sun
java imports
javax imports
There are no blank lines in the group, arranged in lexicographic order.

3.4 Class declaration 3.4.1 There is only one top-level class declaration
Each top-level class is in a source file with the same name (of course, it also contains the .java suffix).

Exception: package-info.java, there is no package-info class in this file.

3.4.2 Order of class members
The order of members of a class has a great influence on ease of learning, but there is no single general rule. Different classes may order members differently. The most important point is that each class should sort its members with some kind of logic, and the maintainer should be able to explain this sorting logic. For example, new methods cannot always be habitually added to the end of the class, because it is sorted chronologically rather than logically.

3.4.2.1 Overload: never separate
When a class has multiple constructors or multiple methods with the same name, these functions / methods should appear together in sequence, and do not put other functions / methods in the middle.

format
Explanation of terms: Block-like construct refers to the main body of a class, method or constructor. It should be noted that the initial value in the initialization of the array can be selectively regarded as a block structure (Section 4.8.3.1).

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

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

No line break before left brace
Line break after left brace
Line break before closing brace
If the closing brace is the end of a statement, function body, or class, the line break follows the closing brace; otherwise, there is no line break. For example, if the closing brace is followed by else or a comma, then no line breaks.
Examples:

return new MyClass () {
  @Override public void method () {
    if (condition ()) {
      try {
        something ();
      } catch (ProblemException e) {
        recover ();
      }
    }
  }
};
Section 4.8.1 gives some exceptions to the enum class.

4.1.3 Empty block: a concise version can be used
An empty block structure contains nothing. The braces can be concisely written as {} without the need for line breaks. Exception: If it is part of a multi-block statement (if / else or try / catch / finally), even if there is nothing in the braces, the closing brace must be wrapped.

Examples:

void doNothing () {}
4.2 Block indentation: 2 spaces
Whenever a new block starts, the indentation increases by 2 spaces, and when the block ends, the indentation returns to the previous indentation level. The indentation level applies to code and comments. (See code example in section 4.1.2)

4.3 One statement per line
Line breaks after each statement.

4.4 Column limit: 80 or 100
An item can select a column limit of 80 characters or 100 characters. Except for the following exceptions, any line that exceeds this character limit must be automatically wrapped.

exception:

Rows that are unlikely to meet column limits (for example, a long URL in 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 Word wrap
Terminology description: In general, a long line of code is divided into multiple lines in order to avoid exceeding the column limit (80 or 100 characters), which we call line-wrapping.

We do not have comprehensive, deterministic criteria to determine how to wrap in every situation. Many times, there will be several effective ways of word wrapping for the same piece of code.

Tip: The extraction method or local variables can solve the problem of too long code without line breaks (it is reasonable to shorten the naming length)

4.5.1 Where to disconnect
The basic rule for word wrapping is: prefer to break at a higher grammar level.

If you break at the non-assignment operator, then break before the symbol (for example, +, it will be on the next line). Note: This is different from the programming style of other Google languages (such as C ++ and JavaScript). This rule also applies to the following "operator-like" symbols: dot delimiter (.), & (<T extends Foo & Bar>) in type boundaries, and pipe symbols in catch blocks (catch (FooException | BarException e)
If you break at the assignment operator, the usual practice is to break after the symbol (for example, =, it stays on the same line as the previous content). This rule also applies to semicolons in foreach statements.
The method name or constructor name stays on the same line as the left bracket.
The comma (,) stays on the same line as the content before it.
4.5.2 Indent at least +4 spaces when wrapping lines
When auto-wrapping, each line after the first line is indented by 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 automatic line break, the indentation may be indented by more than 4 spaces (when there are multiple levels of syntax elements). In general, two consecutive lines use the same indentation if and only if they start at the same level of syntax elements.

The section 4.6.3 Horizontal Alignment states that it is discouraged to use a variable number of spaces to align the symbols on the previous line.

4.6 Blank 4.6.1 Vertical blank
A blank line is required in the following situations:

Between consecutive members in a class: fields, constructors, methods, nested classes, static initialization blocks, instance initialization blocks. In the function body, blank lines are used between logical groupings of statements.
Exception: Blank lines between two consecutive fields are optional. Blank lines used for fields are mainly used to logically group fields.
Blank lines before the first member or after the last member in the class are optional (this is neither encouraged nor opposed to, depending on personal preference).
To meet the blank line requirements of other sections in this document (such as section 3.3: import statement)
Multiple consecutive blank lines are allowed, but there is no need 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, comments and Javadoc use a single space, a single ASCII space also appears in the following places:

Separate any reserved words from the left parenthesis (() (such as if, for catch, etc.) immediately following it.
Separate any reserved words from the closing brace (}) before them (such as else, catch).
Before any left brace ({), there are two exceptions:
@SomeAnnotation ({a, b}) (without 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 "operator-like" symbols:
& (<T extends Foo & Bar>) in the type boundary.
Pipe symbol in catch block (catch (FooException | BarException e).
The semicolon in the foreach statement.
After,:; and closing bracket ())
If you make a comment after a statement, the double slash (//) must be blank on both sides. Multiple spaces can be allowed here, but it is not necessary.
Between types and variables: List list.
In the initialization of the array, the spaces in braces are optional, that is, both new int [] {5, 6} and new int [] {5, 6} are possible.
Note: This rule does not require or prohibit the switch or the end of a line requires extra spaces, only the internal spaces are required.

4.6.3 Horizontal alignment: no requirement
Explanation of terms: 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 such code can be seen in many places), but the Google programming style does not require this. Even for code that already uses horizontal alignment, we don't need to maintain this style.

The following example shows the unaligned code first, then the 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 can increase code readability, but it will cause problems for future maintenance. Considering sometime in the future, we need to modify a line in a bunch of aligned code. This may cause the original beautiful alignment code to become misaligned. It is likely that it will prompt you to adjust the white space of the surrounding code to realign the stack of code horizontally (for example, the programmer wants to maintain this horizontal alignment style), which will let you do a lot of useless work, increase the work of the reviewer and May lead to more merge conflicts.

4.7 Use parentheses to define groups: recommended
Unless both the author and the reviewer believe that removing parentheses will not make the code misunderstood, or removing parentheses will make the code easier to read, we should not remove parentheses. We have no reason to assume that the reader can remember the entire Java operator priority table.

4.8 Concrete structure 4.8.1 Enumeration class
The enumeration constants are separated by commas, and line breaks are optional.

Enumeration classes without methods and documentation can be written in an array initialization format:

private enum Suit {CLUBS, HEARTS, SPADES, DIAMONDS}
Since the enumeration class is also a class, all format rules that apply to other classes also apply to enumeration classes.

4.8.2 Variable declaration 4.8.2.1 Only declare one variable at a time
Do not use combination statements, such as int a, b ;.

4.8.2.2 Only declare when needed, and initialize as soon as possible
Don't declare local variables at the beginning of a code block at once (this is the C language), but only when you need to use 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 Array 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,
  twenty three
}

new int []
    {0, 1, 2, 3}
4.8.3.2 Non-C style array declaration
The square brackets are part of the type: String [] args, not String args [].

4.8.4 switch statement
Explanation of terms: The braces of the switch block are one or more statement groups. Each statement group contains one or more switch tags (case FOO: or default :), followed by one or more statements.

4.8.4.1 Indent
Consistent with other block structures, the contents of the switch block are indented to 2 spaces.

Start a new line after each switch label, indent 2 spaces, and write one or more sentences.

4.8.4.2 Fall-through: notes
Within a switch block, each statement group is either terminated by break, continue, return, or throws an exception, or a comment is used to indicate that the program will continue to the next statement group. Any comment that can express this is OK (Typically use // fall through). This special comment does not need to appear in the last statement group (usually default). Examples:

switch (input) {
  case 1:
  case 2:
    prepareOneOrTwo ();
    // fall through
  case 3:
    handleOneTwoOrThree ();
    break;
  default:
    handleLargeNumber (input);
}
4.8.4.3 The default case should be written
Each switch statement contains a default statement group, even if it contains no code.

4.8.5 Annotations
Annotations immediately follow the document block and apply to classes, methods, and constructors, with one annotation on its own line. These line breaks are not automatic line breaks (Section 4.5, Automatic Line Wraps), so the indentation level is unchanged. E.g:

@Override
@Nullable
public String getNameIfPresent () {...}
Exception: A single comment can appear on the same line as the first line of the signature. E.g:

@Override public int hashCode () {...}
Comments applied to the field appear immediately after the document block. Multiple comments applied to the field are allowed to appear on the same line as the field. E.g:

@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 code around them. They can be / * ... * / style or // ... style. For multi-line / * ... * / comments, subsequent lines must start with * and be aligned 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 multi-line comments, if you want to be able to renew the line if necessary (that is, the comment looks like a paragraph style), then use / * ... * /.

4.8.7 Modifiers
Class and member modifiers, if they exist, appear in the order recommended in the Java language specification.

public protected private abstract static final transient volatile synchronized native strictfp
Naming conventions 5.1 Rules common to all identifiers
The identifier 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 the Java programming style.

5.2 Rules for identifier types 5.2.1 Package name
The package names are all lowercase, and consecutive words are simply connected without underscores.

5.2.2 Class name
The class names are written in the style of UpperCamelCase.

Class names are usually nouns or noun phrases, and interface names may sometimes be adjectives or adjective phrases. There are no specific rules or proven conventions for naming annotation types.

The naming of the test class begins with the name of the class to be tested and ends with Test. For example, HashTest or HashIntegrationTest.

5.2.3 Method name
Method names are written in the style of lowerCamelCase.

The method name is usually a verb or verb phrase.

An 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 example testPop_emptyStack. There is no single correct way to name a test method.

5.2.4 Constant names
The constant name naming pattern is CONSTANT_CASE, all letters are capitalized, and words are separated by underscores. So, what 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 the observed state of any of this instance is variable, it will almost certainly not be a constant. It is generally not enough to never plan to change the object. It must be truly constant before it can be shown 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 Non-constant field names
Non-constant field names are written in the style of lowerCamelCase.

These names are usually nouns or noun phrases.

5.2.6 Parameter name
The parameter name is written in the style of lowerCamelCase.

The parameter should avoid naming with a single character.

5.2.7 Local variable names
Local variable names are written in the style of lowerCamelCase. Compared to other types of names, local variable names can have more relaxed abbreviations.

Although the abbreviation is more relaxed, it is still necessary to avoid naming with single characters, 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 of constants.

5.2.8 Type variable names
Type variables can be named in one of two styles:

A single capital letter can be followed by a number (eg: E, T, X, T2).
Use class naming (section 5.2.2), followed by a capital T (eg RequestT, FooBarT).
5.3 CamelCase
The camel case nomenclature is divided into big camel case nomenclature (UpperCamelCase) and small camel case nomenclature (lowerCamelCase). Sometimes, we have more than a reasonable way to convert an English phrase into a camel case, such as an abbreviation or unusual structure (such as "IPv6" or "iOS"). Google specifies the following conversion scheme.

The name starts with a prose form:

Convert the phrase to pure ASCII code and remove any single quotes. For example: "Müller ’s algorithm" will become "Muellers algorithm".
Split the result into words, and separate them in spaces or other punctuation marks (usually hyphens).
Recommendation: If a word already has a commonly used hump representation, split it according to its composition (eg "AdWords" will be split into "ad words") It should be noted that "iOS" is not a true hump representation, so this recommendation does not apply to it.
Now lowercase all letters (including abbreviations), then capitalize the first letter of the word: finally connect all the words together to get an identifier.
The first letter of each word is capitalized to get a big hump-style name.
Except for the first word, the first letter of each word is capitalized to get a little camel-style naming.
Examples:

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 *
An asterisk indicates yes, but it is not recommended.

Note: In English, some hyphenated words are not unique. For example: "nonempty" and "non-empty" are both correct, so the method names checkNonempty and checkNonEmpty are also correct.

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

6.2 Exceptions caught: cannot be ignored
Except for the examples below, it is rarely correct not to respond to caught exceptions. (The typical response is to print the log, or if it is considered impossible, then throw it back as an AssertionError.)

If it does not 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);
Exception: In testing, if a caught exception is named expected, it can be ignored without comments. The following is a very common situation to ensure that the tested method will throw an expected exception, so there is no need to add a comment here.

try {
  emptyStack.pop ();
  fail ();
} catch (NoSuchElementException expected) {
}
6.3 Static members: use class to call
Use class names to call static class members instead of specific objects or expressions.

Foo aFoo = ...;
Foo.aStaticMethod (); // good
aFoo.aStaticMethod (); // bad
somethingThatYieldsAFoo (). aStaticMethod (); // very bad
6.4 Finalizers: disabled
Object.finalize is rarely overloaded.

Tip: Do not use finalize. If you must use it, please read and understand Effective Java Article 7: "Avoid Finalizers" carefully, and then do not use it.

Javadoc 7.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 the following single line form:

/ ** An especially short bit of Javadoc. * /
 

The basic format is always OK. When the entire Javadoc block can fit on one line (and there is no Javadoc tag @XXX), a single line form can be used.

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

7.1.3 Javadoc markup
Standard Javadoc tags appear in the following order: @param, @return, @throws, @deprecated, if the preceding four tags appear, the description cannot be empty. When the description cannot fit on one line, consecutive lines need to be indented by at least 4 more spaces.

7.2 Summary snippet
The Javadoc for each class or member begins with a short summary snippet. This snippet is very important. In some cases, it is the only text that appears, such as in class and method indexes.

This is just a small segment, which can be a noun phrase or verb phrase, but not a complete sentence. It will not start with A {@code Foo} is a ... or This method returns ..., nor will it be a complete imperative sentence, such as Save the record ... However, because of the capitalization and punctuation at the beginning, it looks like a complete sentence.

Tip: A common mistake is to write the simple Javadoc as / ** @return the customer ID * /, which is incorrect. It should be written as / ** Returns the customer ID. * /.

7.3 Where do I need to use Javadoc
Use Javadoc at least for each public class and each of its public and protected members. The following are some exceptions:

7.3.1 Exception: self-explanatory methods
For simple and obvious methods such as getFoo, Javadoc is optional (that is, it is not necessary to write). In this case, besides writing "Returns the foo", there is really nothing worth writing.

The test methods in the unit test class are probably the most common examples that are self-explanatory. We can usually know what they do from the descriptive names of these methods, so no additional documentation is needed.

Tip: If there is some relevant information that readers need to understand, then the above exception should not be used as a reason to ignore this information. For example, for the method name getCanonicalName, the document description should not be ignored, because the reader may not know what the canonical name refers to.

7.3.2 Exception: overloading
If a method overloads a method in a superclass, Javadoc is not necessary.

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.

postscript
This document is translated from Google Java Style, author @Hawstein.

Google Java programming style guide Chinese version

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.