Reproduced Google Java Style Chinese version

Source: Internet
Author: User
Tags naming convention printable characters uppercase letter

Transferred from: http://www.blogjava.net/zh-weir/archive/2014/02/08/409608.html

Google Java Style Chinese versionBased on the last change in Official document 2013.12.19. Translator: Weir Zhang (Zh.weir) Narrator: The level is limited, many places just free translation. Inaccurate, we will take the original document as the standard. Original address: http://google-styleguide.googlecode.com/svn/trunk/javaguide.html First, IntroductionThis document is a complete definition of the Google Java programming specification. Java source files written in accordance with this specification can be called Google Style. As with other programming specification guidelines, the specification includes not only the structural aesthetics of the Code, but also other industry conventions and universally adopted standards. The specifications in this document are basically standards that the industry has agreed on, and we try to avoid defining areas where there are disputes. 1.1 Term DescriptionUnless otherwise specified in this document, A, Class (class) refers to the normal class type, enum enum type, interface type, and annotation type. B, Comment (note) is always referred to as implementation comments (Implementation note,/*/). We do not use the word "document comment", but we will say Javadoc directly. Other terms, which are described in the documentation, will be explained separately. 1.2 Document DescriptionThe code in this document does not necessarily conform to all specifications. Even though the code follows Google Style, it's not the only code specification. The optional format style in the example should not be used as a specification for enforcement. Second, the Source document Foundation 2.1 File nameThe source file name consists of the class name (case-sensitive) of the top-level class it contains, plus the. java suffix. (except for Package-info.java files). 2.2 File code: UTF-8Source files are encoded using UTF-8. 2.3 Special Characters 2.3.1 Space characterIn addition to line breaks, the ASCII horizontal white space character (0x20) is the only space character supported in the source file. This means: A, other whitespace characters will be escaped. B, tab characters are not used as indentation controls. 2.3.2 Special Escape stringAny character that needs to escape the string representation (for example, \b, \ t, \ n, \f, \ r, \ \, \ \ etc) is represented by this escape string, not by the octal number of the corresponding character (for example, \012) or Unicode code (such as \u000a). 2.3.3 Non-ASCII characters  for the remaining non-ASCII characters, it is permissible to use Unicode characters (for example, ∞) directly, or to escape using the corresponding Unicode code (for example, \u221e). The only thing to consider is how you can make your code easier to read and understand.   NOTE: When using Unicode code escaping, or even sometimes using Unicode characters directly, it is helpful to add a bit of explanatory note to someone else to read the code.   Example:
Example Discussion
String unitAbbrev = "μs"; best:perfectly clear even without a comment.
String unitAbbrev = "\u03bcs"; // "μs" Allowed, but there's no reason to does this.
String unitAbbrev = "\u03bcs"; // Greek letter mu, "s" Allowed, but awkward and prone to mistakes.
String unitAbbrev = "\u03bcs"; Poor:the Reader has no idea what the IS.
return ‘\ufeff‘ + content; // byte order mark Good:use escapes for non-printable characters, and comment if necessary.
Note: Do not use it because you are concerned that some programs will not handle the charge ASCII characters properly, resulting in poor code legibility. If such a problem arises, it should be resolved by the program that is having the problem. III. Structure of source filesource files in order, from the following parts: A, license or copyright statement information. (If you need to declare) B, Package declaration statement. C, import statement. D, class declaration (each source file can only have a single top-level Class). There should be only one row of empty rows between each section as an interval. 3.1 lincense or copyright statement information. If you need to declare lincense or copyright information, you should declare it at the beginning of the file. 3.2 Package DeclarationThe line declared by the package does not have a limit on the length of the bank. A single line length limit (4.4 in detail, 80 or 100) does not apply to package declarations. 3.3 Import Statement 3.3.1 Do not use wildcard characters importYou should not use wildcard import, whether it is a static import or not. 3.3.2 No Line length limitThe line of the import statement has no limit on the length of the lines. The single line length limit (4.4 in detail, 80 or 100) does not apply to the row of the import statement. 3.3.3 sequence and blank lineThe import statement should be divided into groups, each separated by a single line of blank lines. The order of grouping is as follows: A, all of the static imports are grouped into a group. b, the import of Com.google package is grouped into one group. C, a reference to the third-party package used. Each top-level third-party package is grouped into a group. The third-party packages are sorted by ASCII code. For example: Android, com, junit, org, Sund, Java package belong to a group. E, javax package is grouped into one group. Empty lines are not separated between import statements within the same group. Import statements in the same group are sorted by ASCII code. Class 3.4 Declarations 3.4.1 Declare only one top classThere can be only one top class in each source file. Package-info.java files are excluded. 3.4.2 class member OrderThe Order of class members has a significant effect on the legibility of code, but there is no uniform and correct standard. Different classes may have different sorting methods. It is important that each class be sorted according to a certain logical law. When asked, it is possible to explain why this sort is so. For example, the newly added member method is not simply placed on the last side of the class code, but sorted by date is not logically ordered. 3.4.2.1 Overloaded methods: should not be separatedWhen a class has more than one constructor, or more than one member method of the same name, these functions should be written together and should not be separated by other members. iv. FormatTerm Description: A block structure (Block-like construct) refers to the implementation portion of a class, member function, and constructor (the middle part of the curly brace). Note that in the following section 4.8.3.1, the initialization of the array, all array initialization can be considered a block structure (not mandatory). 4.1 curly Braces 4.1.1 Curly braces are used where neededCurly braces are generally used for statements such as if, else, for, do, and while. Even when its implementation is empty or if there is only one sentence, it needs to be used. 4.1.2 Non-empty statement block with K&r styleFor non-empty statement blocks, the curly braces follow the K&r style: A, the left parenthesis does not wrap before wrapping. b, the opening parenthesis followed by a newline. C, wrap before closing parenthesis. D, if the closing parenthesis ends a block of statements or a function body, a constructor body, or a named class body, a newline is required. For example, when the right parenthesis is followed by an else or a comma, the line should not be wrapped. Example: Some exceptions will be mentioned when the enumeration type is in Section 4.8.1. 4.1.3 Empty statement block: Make your code more conciseAn empty statement block that can be followed by a closing curly brace directly after the left curly brace, with no spaces or line breaks in between. However, when a statement block is composed of several statement blocks, a newline is required. (Example: If/else-if/else try/catch/finally). Example: void DoNothing () {} 4.2 statement block indentation: 2 spacesEach time a new block of statements is generated, the indentation increases by two spaces. When this block of statements ends, indentation reverts to the number of indents at the previous level. Indentation requirements apply to both code and annotations in the entire statement block. (examples can be found in the previous example in Section 4.1.2). 4.3 lines with at most one line of codeThe end of each line of code requires a newline. 4.4 Line length limit: 80 orDifferent items can be selected with a limit of 80 characters or 100 characters. In addition to the following special cases, other code content is subject to this length limit. This will be explained in detail in section 4.5. Exception: A, the line length limit, cannot implement place (for example: Javadoc long URL address, or a long Jsni method of reference); B, package and import statements are not limited by length. (see section 3.2, 3.3); c, the command line line in the note, will be copied directly into the shell execution. 4.5 long line breakTerminology Description: When a line of code is legal according to other specifications, just to avoid exceeding the line length limit and newline, called long line break. Long line breaks, without a comprehensive, deterministic specification for all scenarios. But a lot of the same situation, we often use some effective method of breaking the break. Note: Wrapping long lines as functions, or using local variables, can also resolve some cases where the line length limit is exceeded. Not necessarily a break. 4.5.1 where to breakThe main principle of breaking a break is to choose to break at a higher level of syntax logic. Some other principles are as follows: A, when a statement with a non-assignment operation breaks, lines up before the operation symbol. (This differs from other specifications such as Google's C + + specifications and Javascrip specifications). b, when an assignment operation statement breaks, it is usually broken after the assignment symbol. But you can also break a previous break. C, when calling a function or constructor that requires a line break, the opening parenthesis that is connected to the function name is one row. That is, after the opening parenthesis. D, when the comma is broken, you want to break the preceding statement separated by commas. That is, after the comma. 4.5.2 Indent of a break: at least 4 charactersAfter a line break, after the first line, we call the continuation line. Each continuation line is indented at least four characters, based on the first line. When there are multiple continuation lines after the original line, the indentation can be greater than 4 characters. If multiple continuation lines are line-breaking by the same syntax elements, they can use the same indentation. 4.6.3 section describes horizontal alignment and resolves an issue where multiple spaces are used to align with previous line indents. 4.6 Blank Space 4.6.1 Vertical BlankA single line of blank lines is used in the following cases: A, a blank line between class members: for example, member variables, constructors, member functions, inner classes, static initialization statement blocks (static initializers), instance initialization statement blocks (instance initializers). Exception: Blank lines between member variables are not required. A blank line in the middle of a general number of member variables is a logical grouping of member variables. b, inside the function, set the blank line as the interval according to the need of logical grouping of code. C, before the first member of the class, or after the last member ends, with a blank line interval. (optional) d, the case where blank lines are required in the other sections of this document. (for example, the import statement in section 3.3) the use of multiple lines of blank lines is allowed, but not required and discouraged, for a single empty row. 4.6.2 Horizontal BlankIn addition to syntax, other rules, word separation, annotations, and Javadoc, horizontal ASCII spaces only occur in the following cases: A, all reserved keywords and the left parenthesis on the same line immediately after it need to be separated by a space. (for example, if, for, catch) b, all reserved keywords need to be separated from the right curly brackets before it. (for example, else, catch) C, spaces are required before the left curly braces. There are only two exceptions: @SomeAnnotation ({A, B}) string[][] x = {{"foo"}};d, all the two-ary operators, and both sides of the ternary operator, all of which require spaces to be separated. After e, comma, colon, semicolon, and closing parenthesis, spaces are required. F,//Double slash begins a line of comments. Double slash should be separated by a space on both sides. And you can use more than one space, but do not make mandatory requirements. When declaring a variable, the variable type and the variable name need to be separated by a space. H, when initializing an array, the curly braces can be separated by a space, or they may not be used. For example new int[] {5, 6}And new int[] { 5, 6 }) Note: This principle does not affect whitespace at the beginning or end of a line. Separates only the characters within the line. 4.6.3 Horizontal alignment: Do not make mandatory requirementsTerm Description: Horizontal alignment means that one of our symbols is aligned up and down with a symbol on the previous line by adding multiple spaces. This alignment is allowed, but does not make mandatory demands.   Here is an example of no horizontal alignment and horizontal alignment; private int x;   This is fineprivate color color;          This too private int x;    Permitted, but the future editsprivate color color; May leave it unaligned note: Horizontal alignment increases the readability of your code, but increases the difficulty of maintaining your code in the future. Given that maintenance requires only one line of code to be changed, the previous alignment can be no change. In order to align, you are more likely to change one line of code, and you need to make changes to several nearby lines of code, and the changes to these lines of code may cause some code changes to remain aligned. The original change, we call the "explosion radius." This change, in the worst case scenario, can lead to a lot of meaningless work, even in the best case, affecting version history information, slowing down the speed of code review, and causing more conflict in the merge code. 4.7 block Brackets: suggested useA non-mandatory grouping bracket can only be omitted if the code is written and the code reviewer thinks that it is not possible for the code to understand the error without it, or if it does not make the code easier to understand. There is no reason to think that everyone reading the code can remember the precedence of all Java operators. 4.8 Special Structures 4.8.1 enumeration TypesEach comma is followed by an enumeration variable, and no line break is required. Enumeration types, and if there are no functions and Javadoc, the processing format can be handled by array initialization. Example: Private enum Suit {CLUBS, HEARTS, Spades, DIAMONDS} enum types are also classes (class), so other formatting requirements for class classes are also applicable to enumeration types. 4.8.2 Variable Declaration4.8.2.1 each time a variable is declared do not take a declaration, declaring multiple variables. For example int a, b;4.8.2.2 declare when needed, as soon as possible the initialization of local variables should not be habitually declared at the beginning of the statement block, but should be as far as possible from the place where it was first used, to reduce their scope of use. Local variables should be initialized at the time of declaration. Initialization should also be completed as soon as possible if it cannot be initialized at the time of declaration. 4.8.3 Array4.8.3.1 Array Initialization: The initialization of all arrays can be handled like block code, and can be handled in the same format as block code. For example, the following format is allowed: 4.8.3.2 cannot declare an array of square brackets like C-style, which should be part of a variable type, and therefore should not be put together with variable names. For example: It should be string[] args, not String args[]4.8.4 switch StatementTerm Description: A switch statement refers to a set or groups of statement blocks in a switch curly brace.  Each set of statement blocks is preceded by one or more switch labels, such as Case FOO: or default:. 4.8.4.1 indents, like other statement blocks, indent two characters after the switch curly brace. After each switch label, the new non-tagged line immediately following it is indented two characters in the same way that curly braces are handled.  After the label ends, revert to the previous indent, similar to the curly brace end. 4.8.4.2 continue to execute the comments in the switch statement, each tag corresponding to the code after execution, should end with a statement (for example: Break, continue, return or throw an exception), otherwise it should be explained by the comment, The code needs to continue executing the next tag's code down. Note that the text can be described as long as the code needs to continue to execute (usually//fall through). This comment does not require a comment after the last label. For example, 4.8.4.3 the default tag requires an explicit declaration of each switch statement, you need to explicitly declare the default label. The declaration needs to be displayed even without any code. 4.8.5 AnnotationsAnnotations should be applied to a class, function, or constructor immediately after Javadoc. Each line has only one annotations. The annotations row is not constrained by the length of the line, nor does it need to increase indentation. For example: @Override @nullablepublic String getnameifpresent () {...} exception: if annotations has only one and no parameters. It can be placed on the same line as the class or method name. For example: @Override public int hashcode () {...} When annotations is applied to a member variable, it is immediately after Javadoc. The difference is that multiple annotations can be placed on the same line. For example: @Partial @Mock Dataloader loader; There are no specific specifications for the use of annotations for parameters or local variables. 4.8.6 NotesThe indentation of the annotation style comment for the 4.8.6.1 statement block is the same as the code that it commented on. You can use/* * * * * */To comment, or you can use//comment. When using/**/for multiline comments, each line should start with a * and the * should be aligned up and down. For example, if you want the integrated development environment to automatically align annotations when you have multiple lines of comments, you should use/**/,//generally not automatically aligned. 4.8.7 modifierModifiers for multiple classes and member variables, sorted by the order described in Java lauguage specification. Specifically: Public protected private abstract static final transient volatile synchronized native STRICTFP v. Naming 5.1 General Specification for all named identifiersIdentifiers should only use ASCII letters, numbers, and underscores, which are case sensitive. Therefore all identifiers should be able to match the regular expression \w+. In Google style, identifiers do not need to use special prefixes or suffixes, such as: Name_, mName, s_nameAnd kName5.2 Specifications for different types of identifiers 5.2.1 Package NameThe package name is all in lowercase letters, through. Connect the levels together. The underscore should not be used. 5.2.2 class namesThe name of the type, in the form of uppercase and lowercase characters that begin with a capital letter (uppercamelcase). Class naming generally uses nouns or noun phrases. Interface can sometimes use adjectives or adjective phrases. The annotation does not have a definite fixed specification. To name a test class, start with the name of the class it is testing, and end with Test at the end. For example: Hashtest, HashIntegrationTest5.2.3 Method NameThe method is named with a lowercase letter spacing (lowercamelcase). Method naming generally uses verbs or verb phrases. In JUnit's test methods, you can use underscores to differentiate the name of the test logic, often using the following structure: test <MethodUnderTest>_ <state>。 For example: Testpop_emptystack. Test methods can also be named in other ways. 5.2.4 constant NameConstants are named, all use uppercase characters, and words are separated by underscores. (Constance_case). A constant is a static member variable, but not all static member variables are constants. When you choose to name a variable using a constant naming convention, you need to make sure that the variable is a constant. For example, if the state of the variable can change, then this variable is almost certainly not a constant. It's just that the plan won't change. The variable is not sufficient to be a constant. The following are examples of constants and extraordinary quantities:
Constants are usually named with nouns or noun phrases. 5.2.5 the member variable name of the very amountThe very variable names of member variables (including static and non-static variables) are named after Lowercamelcase. Nouns or noun phrases are generally used. 5.2.6 Name of the parameterThe parameter name is named by Lowercamelcase. You should avoid using a character as a parameter naming method. 5.2.7 local variable nameLocal variables are named with Lowercamelcase. It can be used in a shorter, looser way than other types of naming. But even so, you should try to avoid naming cases with a single letter, except for temporary variables that are used in the loop body. Even if the local variable is final and immutable, it cannot be considered a constant, nor should it be named by a constant. 5.2.8 type nameType names are named in two ways: A, a single uppercase letter, and sometimes followed by a number. (for example, E, T, X, T2). B, like the general class name (see 5.2.2), and then the last uppercase letter. (for example, Requestt, Foobart). 5.3 The definition of Camel caseSometimes some phrases can be written in camel cases in many ways. For example, some abbreviation words, or some combination of words: IPV6 or IOS. For the sake of unification, Google style gives a way to be almost certain. A, convert all characters to ASCII characters, and remove ' such symbols. For example, "Müller s algorithm" is converted to "Muellers algorithm". B. Split the result of the previous conversion into a single word.    Divide from spaces and from other remaining punctuation marks. Note: Some words that are already camel cases should also be split at this time. (for example, AdWords is split into ad words). But for example, a word like iOS, it's not a camel case word, it's a word that people use, so it doesn't have to be split. C, after the above two, first convert all the letters to lowercase, and then the first letter of each word to uppercase. D, finally, connect all the words together to form a marker. Note: The original capitalization rules of the words should be completely ignored. Here are some examples: * indicates acceptable, but not recommended. Note that some of the words in English, can be used-connected or not used-direct use. For example, "nonempty" and "non-empty" are all possible. Therefore, the method name is Checknonempty or checknonempty is possible. vi. Programming Practices 6.1 @override should be used@override annotations should be used as long as it is grammatically compliant. 6.2 exception captures should not be ignoredIn general, catch exceptions should not be ignored, but should be handled appropriately. For example, if you print the error log, or if you think that the exception does not occur, you should re-throw it as an assertion exception. If this catch exception does not require any processing, it should also be explained by a comment. For example, exceptions: in a test class, an exception can be ignored if the specified exception is sometimes thrown against the method. But this exception usually needs to be named: expected. For example: 6.3 Static member access: should be through the class, not the objectWhen a static member is accessed, it should be accessed through the class name, rather than using the class's specific instance object. For example:
6.4 Do not use the Finalizers methodThe Finalize method for overloading object is very, very rare. Note: This should not be used in the method. If you think you must use it, please read and understand effective Java seventh "Avoid finalizers" first. Then do not use it. Seven, Javadoc 7.1 Format Specification 7.1.1 Universal FormatThe general format of the most basic Javadoc is as follows: or for single-line format: The common format can be used at any time. When a Javadoc block has only one row, you can use a single-line format instead of a common format. 7.1.2 ParagraphBlank line: Refers to the line in Javadoc that has only the upper and lower lines between the top and bottom two paragraphs of a * character. The first line of each paragraph precedes the first character, has a <p> label, and does not have any spaces after it. 7.1.3 @ clauseAll standard @ clauses should be added in the following order: @param, @return, @throws, @deprecated. And these four kinds of @ clauses, should not appear in an Javadoc block without description. When the @ clause cannot be written on a line, it should break. Extends the position of the line at the @ character of the first line, indenting at least 4 character units. 7.2 Summary FragmentsThe Javadoc of each class or member is started by a digest fragment. This fragment is very important. Because it is the only text description that the class or method can see when it is used. The main summary is just a fragment, it should be a noun phrase or a verb phrase, not a complete sentence. But it should use punctuation like a complete sentence. Note: A common mistake is to use javadoc:/** in this form @return the customer ID */. That's not right. Should read:/** Returns the Customer ID. */. 7.3 Where should I use JavadocAt a minimum, Javadoc should be applied to all member variables and methods of the public class, public, and protected. and a small number of exceptional cases. The exceptions are as follows. 7.3.1 Exception: The method itself is sufficient to illustrate the situationWhen the method itself is obvious, it is not necessary to Javadoc. For example: Getfoo. There is no need to add Javadoc "Returns the foo". The methods in the unit test are basically able to know the function of the method by means of the method name. Therefore, there is no need to increase javadoc. Note: Sometimes you should not refer to this exception to omit information that some users need to know. For example: Getcannicalname. When most code readers do not know what canonical name means, Javadoc should not be omitted, thinking that only/** Returns the canonical name can be written. */ 。 7.3.2 Exceptions: Overloaded MethodsOverloaded methods sometimes do not need to write Javadoc. 7.3.3 Exceptions: Optional JavadocSome class and member variables or methods that are not visible outside the package, or you can use Javadoc as needed. You can use Javadoc when a comment is used to describe the overall goal or behavior of the class, variable, or method.

Reproduced Google Java Style Chinese version

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.