Java Programming Style specification (Google)

Source: Internet
Author: User
Tags class operator coding standards modifiers throw exception uppercase letter word wrap

Google Java Programming style guide

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 Basics
2.1 File name

The source file is named with its topmost class name, is case-sensitive, and has a. java file name extension.
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 (such as \012) or Unicode (such as \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"; | Even if no comments are clear.
String Unitabbrev = "\u03bcs"; "Μs" | Allowed, but there was no reason to do so
String Unitabbrev = "\u03bcs"; Greek letter Mu, "s" | Allowed, but it's clumsy and error prone.
String Unitabbrev = "\u03bcs"; | It's bad, the reader doesn't see what it is.
Return ' \ufeff ' + content; BYTE Order Mark | Good, for nonprinting characters, use escape 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 like this import statement: 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.google Imports (only if this source file is under the Com.google package)
Third-party packages. Each top-level package is a set of dictionary-ordered. For example: Android, com, junit, org, Sun
Java Imports
Javax Imports

The lines within the group are not empty, sorted by dictionary order.
Class 3.4 declarations
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. java suffix).

Exception: Package-info.java, there is no Package-info class in the file.
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 using curly braces (even optional)

Curly braces are used with if, else, for, do, and while 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

There is nothing in an empty block structure, curly braces can be neatly written in {} and do not need to be wrapped. 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).
Package and import statements (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 you break at a non-assignment operator, 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 break at the assignment operator, 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 to semicolons in a foreach 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 Blanks
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.
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.
In the body of a function, a blank line is used between logical groupings of statements.
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 immediately following (() (such as if, for catch, and so on).
Separates any reserved word from its preceding closing brace (}) (for example, else, catch).
Before any opening curly braces ({), two exceptions:
@SomeAnnotation ({A, B}) (with no 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:
& (<t extends Foo & bar>) in the type bounds.
Pipe symbol in Catch block (catch (fooexception | Barexception e).
The semicolon in the foreach statement.
After,:; and closing 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, spaces within curly braces are optional, i.e. new int[] {5, 6}, and new int[] {5, 6} are all 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 the 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, such as int 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[] args, not String 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: 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 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 is terminated either by a break, continue, return or throw exception, or by a comment stating that the program will continue to execute to the next set of statements, and that any comment that can express that meaning is OK (typically with//fall Through). This special note does not need to appear in the last statement group (typically default). 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 a group of default statements, even if it does not contain any of the 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 Pieces of annotation style

The block comment is at the same indentation level as the code surrounding it. They can be/*//style, also can be//... Style. For multiple lines of/* ... */note, subsequent lines must start with * and align with the previous line's *. The following sample comments are OK.

/*
* This are//and so/*/CAN
* Okay.          Is this. * even do this. */
*/

Note Do not enclose in frames drawn by asterisks or other characters.

Tip: When writing multiline comments, if you want to be able to re-line if necessary (that is, the comment is like a paragraph style), then use/* ... */.

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 conventions
5.1 rules that are common to all identifiers

Identifiers can only use ASCII letters and numbers, so each 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 name is all lowercase, and successive words are simply concatenated, without underlining.
5.2.2 Class Name

Class names are written in uppercamelcase 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 start with the name of the class it is testing, ending with test. For example, Hashtest or hashintegrationtest.
5.2.3 Method Name

Method names are written in lowercamelcase 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>, such as Testpop_emptystack. There is no single right way to name a test method.
5.2.4 Constant Name

The constant name mode is constant_case, all letters are capitalized, and the words are 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 plan to change the object is generally 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 Lowercamelcase field name is written in the style.

These names are usually nouns or noun phrases.
5.2.6 Name of the parameter

The name of the parameter is written in lowercamelcase style.

Parameters should avoid naming with a single character.
5.2.7 local variable name

Local variable names are written in lowercamelcase 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 camel-named method 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 the prose form (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), and then capitalize the first letter of the word:
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.
Finally, connect all the words together 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*

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 names Checknonempty and Checknonempty are also correct.

Programming practices
6.1 @Override: Can be used

As long as it is legal, the @override annotation to use.
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, to re-throw it as a assertionerror.) )

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 testing, if a caught exception is named expected, 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 overload the object.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.

Javadoc
7.1 Format
7.1.1 General Form

The basic format of the Javadoc block is as follows:

/**
* Multiple lines of Javadoc text is 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 <p&gt before the first word, 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, @deprecated, the preceding 4 kinds of tags, if present, 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 not be a {@code Foo} is a ... Or This method returns ... At the beginning, it will not be a complete imperative, such as the Save the record .... However, it looks like a complete sentence because it is capitalized and punctuation is added.

TIP: A common mistake is to write the simple Javadoc as/** @return the customer ID */, which is incorrect. 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 as Getfoo,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, for the method name Getcanonicalname, the document description should not be overlooked because the reader probably does not know what the word canonical name 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.

Java Programming Style specification (Google)

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.