This document serves as the complete definition of Google's coding standards for source code in the Java™ Programming Language. A Java source file is described as being in Google Style if and only if it adheres to the rules herein.
这篇文档提供Java源代码完整的Google标准定义。完全遵守这些规则的Java源代码文件被称为Google风格。
Like other programming style guides, the issues covered span not only aesthetic issues of formatting, but other types of conventions or coding standards as well. However, this document focuses primarily on the hard-and-fast rules that we follow universally, and avoids giving advice that isn't clearly enforceable (whether by human or tool).
和其他编程风格手册一样,本文覆盖的范围不仅涉及代码格式的美观,还涉及其他如约定和代码标准等。然后,这篇文档首要关注我们通常遵循的准确快速(hard-and-fast)规则, 避免给出模糊不清的建议(无论人或工具).
In this document, unless otherwise clarified 除非特别申明,否则仅适用此文档 :
@interface
).
@interface
)
Other "terminology notes" will appear occasionally throughout the document.
其他"术语说明"会偶尔出现在整个文档中。
Example code in this document is non-normative. That is, while the examples are in Google Style, they may not illustrate the only stylish way to represent the code. Optional formatting choices made in examples should not be enforced as rules.
本文档的示例代码是非权威的。就是说,虽然这些例子是Google风格的,但它们不是呈现代码的唯一风格。示例中选择的代码格式不应该被强制执行。
The source file name consists of the case-sensitive name of the top-level class it contains,
plus the .java
extension.
文件名由内容中最高级别的区分大小写的类名加上.java
后缀构成
Source files are encoded in UTF-8.
源代码文件被编码为UTF-8.
Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that:
除了换行符,ASCII空格字符 (0x20)是唯一出现在源代码文件中的空白字符。这意味着:
For any character that has a special escape sequence
(\b
,
\t
,
\n
,
\f
,
\r
,
\"
,
\'
and
\\
), that sequence
is used rather than the corresponding octal
(e.g. \012
) or Unicode
(e.g. \u000a
) escape.
任何特殊转义字符
(\b
,
\t
,
\n
,
\f
,
\r
,
\"
,
\'
和
\\
), 使用转义字符要好于八进制通配符
(e.g. \012
)或Unicode
(e.g. \u000a
)转义符。
For the remaining non-ASCII characters, either the actual Unicode character
(e.g. ∞
) or the equivalent Unicode escape
(e.g. \u221e
) is used, depending only on which
makes the code easier to read and understand.
剩下的非ASCII字符,无论是实际的Unicode字符
(e.g. ∞
)还是等价的Unicode转义字符
(e.g. \u221e
)都可以被使用,主要取决于哪种方式可以使代码更容易读和理解.
Tip: in the Unicode escape case, and occasionally even when actual Unicode characters
are used, an explanatory comment can be very helpful.
提示: 在使用Unicode转义字符的情况下,有时甚至使用真是的Unicode字符时,一条解释性的注释将会非常有用。
Examples 例子:
Example 示例 | Discussion 评论 |
---|---|
String unitAbbrev = "μs"; | Best: perfectly clear even without a comment. 最好:完美清晰,甚至不需要注释。 |
String unitAbbrev = "\u03bcs"; // "μs" | Allowed, but there's no reason to do 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 this is. 不好:读者无法理解这是什么。 |
return '\ufeff' + content;
// byte order mark 字节序列标记 | Good: use escapes for non-printable characters, and comment if necessary. 好:用转义代表不可见字符,且有必要的注释 |
Tip: Never make your code less readable simply out of fear that some programs might not handle non-ASCII characters properly. If that should happen, those programs are broken and they must be fixed.
提示:永远不要仅仅因为害怕一些程序可能无法正确处理非ASCII字符而让你的代码缺乏可读性。如果真遇到了,那么那些程序就是有问题的,它们必须被修复。
A source file consists of, in order:
一个源代码文件由以下内容构成,按顺序:
Exactly one blank line separates each section that is present.
出现的每段间只有一个空行分隔。
If license or copyright information belongs in a file, it belongs here.
如果许可或版权适用于一个文件,则写入文件中
The package statement is not line-wrapped. The column limit (Section 4.4, Column limit: 80 or 100) does not apply to package statements.
包语句是不换行的,列宽限制(段落 4.4, 列宽限制:80或100)不适用于包语句。
Wildcard imports, static or otherwise, are not used.
静态或其他,都不用导入通配符。
Import statements are not line-wrapped. The column limit (Section 4.4, Column limit: 80 or 100) does not apply to import statements.
导入语句是不换行的。列宽显示(段落4.4, 列宽限制: 80或100)不适用于导入语句。
Import statements are divided into the following groups, in this order, with each group separated by a single blank line:
导入语句按以下顺序被分割成以下组,每组之间以一个空行分隔:
com.google
imports
(only if this source file is in the com.google
package
space)com.google
导入
(仅当源代码文件在com.google
包下)android
, com
, junit
, org
,
sun
android
, com
, junit
, org
,
sun
java
importsjava
导入javax
importsjavax
导入Within a group there are no blank lines, and the imported names appear in ASCII sort order. (Note: this is not the same as the import statements being in ASCII sort order; the presence of semicolons warps the result.)
在一组内无空行分隔,导入名称按ASCII顺序排序。(注意:由于分号的存在,实际排序会不同于完整导入语句在ASCII中的排序结果。)
Each top-level class resides in a source file of its own.
每个顶级类(class)存在于它自己的源代码文件中。
The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.
类中成员的顺序可以被较容易的学习,但是没有一条简单正确的秘方告诉你如何做到。不同的类可能会有不同的成员顺序。
What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering.
重要的是每个类通过一些逻辑顺序对它的成员排序,这些逻辑可以被解释。 例如,新方法不只是习惯性的添加在类的末尾,因为这种“按添加时间顺序”排序不是一种逻辑顺序。
When a class has multiple constructors, or multiple methods with the same name, these appear sequentially, with no intervening members.
当一个类有多个构造函数或多个同名方法,它们必须连续出现在一起,中间不含任何其他成员。
Terminology Note: block-like construct refers to the body of a class, method or constructor. Note that, by Section 4.8.3.1 on array initializers, any array initializer may optionally be treated as if it were a block-like construct.
术语说明:块状概念涉及到类、方法或构造函数的主体。注意:段落4.8.3.1提及的数组初始化,任何像块状概念的数组初始化代码都可能被随意放置。
Braces are used with
if
,
else
,
for
,
do
and
while
statements, even when the
body is empty or contains only a single statement.
大括号用在
if
,
else
,
for
,
do
和
while
语句上,就算语句块中为空或者只有一行代码也要使用。
Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs:
非空块和块状结构的大括号使用 Kernighan and Ritchie 风格 ("埃及括号"):
else
or a
comma.else
或逗号,则不换行。Example 例子:
return new MyClass() { @Override public void method() { if (condition()) { try { something(); } catch (ProblemException e) { recover(); } } } };
A few exceptions for enum classes are given in Section 4.8.1, Enum classes.
一些枚举的特例会出现在段落 4.8.1, 枚举类.
An empty block or block-like construct may be closed immediately after it is
opened, with no characters or line break in between
({}
), unless it is part of a
multi-block statement (one that directly contains multiple blocks:
if/else-if/else
or
try/catch/finally
).
空的块或块状结构应该在左括号后被立即关闭,没有字符或空行在({}
)之间,除非它是多块语句的一部分 (语句直接包含多个块:if/else-if/else
或
try/catch/finally
).
Example 例子:
void doNothing() {}
Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block. (See the example in Section 4.1.2, Nonempty blocks: K & R Style.)
每次开始一个新块或块状结构,缩进增加两个空格。当块结束时,返回成之前的缩进。缩进级别同时应用在代码和注释上。(见段落 4.1.2 中的例子,非空块: K & R 风格。)
Each statement is followed by a line-break.
在每条语句后跟一个换行。
Projects are free to choose a column limit of either 80 or 100 characters. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.5, Line-wrapping.
项目可以自由选择行宽限制是80还是100字符。除了下面提及的,任何超过此限制的行都必须被分段,就像段落 4.5 中解释的, 分行.
Exceptions 特例:
package
and
import
statements (see Sections
3.2 Package statement and
3.3 Import statements).package
和
import
语句 (查看章节
3.2 包语句 and
3.3 导入语句)。Terminology Note: When code that might otherwise legally occupy a single line is divided into multiple lines, typically to avoid overflowing the column limit, this activity is called line-wrapping.
术语:当无法控制在一行内的代码被分成多行,例如为了避免超过列宽,这种行为被称为分行。
There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there are several valid ways to line-wrap the same piece of code.
没有综合的、准确的公式去说明究竟如何去在各种情况下分行。通常相同的代码会有多种有效的分行方式。
Tip: extracting a method or local variable may solve the problem without the need to line-wrap.
提示:提取一个方法或本地变量可能可以避免分行。
The prime directive of line-wrapping is: prefer to break at a higher syntactic level. Also:
主要的分行指导方针是:完美的分行在更高的语法级别。 然而:
.
), the ampersand in type bounds
(<T extends Foo & Bar>
), and the pipe in
catch blocks
(catch (FooException | BarException e)
)..
)、类型捆绑中的&符(<T extends Foo & Bar>
)、catch块中的管道符(catch (FooException | BarException e)
)。
for
("foreach") statement.for
("foreach")语句中“类似负值操作”的冒号。(
) that follows it.(
)在同一行。,
) stays attached to the token that
precedes it.,
)之前不分行。When line-wrapping, each line after the first (each continuation line) is indented at least +4 from the original line.
当分行时,在第一行之后的每行(每条续行)至少比原始行多锁进4个空格
When there are multiple continuation lines, indentation may be varied beyond +4 as desired. In general, two continuation lines use the same indentation level if and only if they begin with syntactically parallel elements.
当有多条续行时,锁进可能被改变超过要求的4个空格。一般情况下,当且仅当两条续行在语法上平行时,使用相同的锁进级别。
Section 4.6.3 on Horizontal alignment addresses the discouraged practice of using a variable number of spaces to align certain tokens with previous lines.
段落 4.6.3 水平对齐解释这种糟糕的实践关于使用不定的空格数来对齐之前行的某个标记。
A single blank line appears 单空行出现在:
Multiple consecutive blank lines are permitted, but never required (or encouraged).
多条连续空行是被允许的,但不被要求(或鼓励)的。
Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only.
语言或其他规则要求的以外,除了字符串、注释、Javadoc,单ASCII空格也只出现在以下地方。
if
,
for
or
catch
, from an open parenthesis
((
)
that follows it on that lineif
、for
或catch
和它之后的左括号((
)else
or
catch
, from a closing curly brace
(}
) that precedes it on that lineelse
或catch
之前同行的右大括号(}
){
), with two exceptions:{
)前,但有两个例外:
@SomeAnnotation({a, b})
(no space is used) (没有用空格)String[][] x = {{"foo"}};
(no space is required
between {{
, by item 8 below)
(两个{{
之间不用空格,见下面第8项)
<T extends Foo & Bar>
<T extends Foo & Bar>
catch (FooException | BarException e)
catch (FooException | BarException e)
:
) in an enhanced
for
("foreach") statementfor
语句("foreach")里的冒号(:
),:;
or the closing parenthesis
()
) of a cast,:;
或有括号()
)之后//
) that
begins an end-of-line comment. Here, multiple spaces are allowed, but not required.//
)两侧。这里多个空格也可以,但不是必须的。List<String> list
List<String> list
new int[] {5, 6}
and
new int[] { 5, 6 }
are both validnew int[] {5, 6}
和new int[] { 5, 6 }
都可以Note: this rule never requires or forbids additional space at the start or end of a line, only interior space.
注意:这些规则没有要求在行首或行尾添加多余的空格,仅行内的空格。
Terminology Note: Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
术语说明:水平对齐是通过在代码中添加多个空格,从而使上下行之间像诗一样整齐的实践。
This practice is permitted, but is never required by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.
这个实践是被允许的,但在Google风格中是永远不需要的。已经使用的地方,也不用维持原有的水平对齐。
Here is an example without alignment, then using alignment:
这里是一个不对齐的例子和一个对齐的例子:
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 aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a "blast radius." This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.
提示:对齐可以增加可读性,但给日后维护带来了问题。考虑一个未来的改变,需要改变的只有一行,这个改变可能导致原来良好的格式错位并且被允许。更常见的,它会提示程序员(可能是你)也要优化附近行的空格,可能出发一系列关联的重新格式化。一行的改变现在成为一个“爆炸辐射”。导致糟糕的结果,不仅做毫无疑义的无用功,还会让版本历史信息变糟,降低代码审查的速度和增加合并冲突。
Optional grouping parentheses are omitted only when author and reviewer agree that there is no reasonable chance the code will be misinterpreted without them, nor would they have made the code easier to read. It is not reasonable to assume that every reader has the entire Java operator precedence table memorized.
仅当程序员和代码审核员都同意没有括号分组时代码不会被误解、不会影响代码可读性时,括号分组才能被省略。 没有理由去假设每个代码阅读者都能记住完整的Java操作符优先级。
After each comma that follows an enum constant, a line-break is optional.
逗号后面跟着枚举常量的话,分行是可选的。
An enum class with no methods and no documentation on its constants may optionally be formatted as if it were an array initializer:
常量上不包含方法和文档的枚举类可以被格式成像数组的初始化:
private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }
Since enum classes are classes, all other rules for formatting classes apply.
自从枚举类成为类,所有其他格式化类的规则都应用于枚举类。
Every variable declaration (field or local) declares only one variable: declarations such as
int a, b;
are not used.
每个变量声明(字段或本地)只声明一个变量:不使用这种声明int a, b;
。
Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
本地变量不是习惯性地声明在内容块地或块状结构的顶部。代替的,本地变量被声明在最靠近它们第一次使用的地方(合理地),为了最小化它们的使用范围。本地变量声明通常伴随着初始化,或声明后马上被初始化。
Any array initializer may optionally be formatted as if it were a "block-like construct." For example, the following are all valid (not an exhaustive list):
任何数组初始化可以可选的被格式成“块状结构”。比如,下面都是可以的(不是一个详尽的列表):
new int[] { new int[] { 0, 1, 2, 3 0, } 1, 2, new int[] { 3, 0, 1, } 2, 3 } new int[] {0, 1, 2, 3}
The square brackets form a part of the type, not the variable:
String[] args
, not
String args[]
.
方括号是类型的一部分,不是变量的一部分:String[] args
,不是String args[]
。
Terminology Note: Inside the braces of a switch block are one or more
statement groups. Each statement group consists of one or more switch labels
(either case FOO:
or
default:
), followed by one or more statements.
术语说明:switch块的大括号内是一个或多个语句组。每个语句组由一个或多个switch标签
(case FOO:
或default:
) 组成,标签后跟着一条或多条语句。
As with any other block, the contents of a switch block are indented +2.
和其他代码块一样,switch块的内容缩进 +2。
After a switch label, a newline appears, and the indentation level is increased +2, exactly as if a block were being opened. The following switch label returns to the previous indentation level, as if a block had been closed.
在switch标签后的新行,缩进级别再+2,实际上就像新开始一个新代码块。下一个switch标签返回之前的缩进级别,就像一个代码块结束。
Within a switch block, each statement group either terminates abruptly (with a
break
,
continue
,
return
or thrown exception), or is marked with a comment
to indicate that execution will or might continue into the next statement group. Any
comment that communicates the idea of fall-through is sufficient (typically
// fall through
). This special comment is not required in
the last statement group of the switch block. Example:
在switch块中,每个语句组,包括立刻结束的(包含
break
,
continue
,
return
或者抛出异常),或被注释标记的,表明执行可能继续进入下个语句组。任何注释只要能说明代码执行会降到下一个case就行 (代表性地
// fall through
). 最后一个switch块可以省略这个特殊的注释。例如:
switch (input) { case 1: case 2: prepareOneOrTwo(); // fall through case 3: handleOneTwoOrThree(); break; default: handleLargeNumber(input); }
Each switch statement includes a default
statement
group, even if it contains no code.
每个switch语句包含一个default
语句组,就算里面没有代码。
Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). These line breaks do not constitute line-wrapping (Section 4.5, Line-wrapping), so the indentation level is not increased. Example:
类、方法或构造函数上的注解,应紧跟着文档注释,并且每个注解一行。这些行不用遵循分行规则 (段落4.5, 分行),所以不用增加缩进。例如:
@Override @Nullable public String getNameIfPresent() { ... }
Exception: a single parameterless annotation may instead appear together with the first line of the signature, for example:
除了:一个单独无参数的注解可以出现在签名的第一行,例如:
@Override public int hashCode() { ... }
Annotations applying to a field also appear immediately after the documentation block, but in this case, multiple annotations (possibly parameterized) may be listed on the same line; for example:
字段上的注解也应该紧跟在文档注释之后,但这个例子,多个注解(可能是参数化的)可以放在同一行。例如:
@Partial @Mock DataLoader loader;
There are no specific rules for formatting parameter and local variable annotations.
没有特殊规则适用于格式化参数和本地变量的注解。
Block comments are indented at the same level as the surrounding code. They may be in
/* ... */
style or
// ...
style. For multi-line
/* ... */
comments, subsequent lines must start with
*
aligned with the *
on the previous line.
注释块的缩进和它周围的代码一样。它们可以是
/* ... */
风格或
// ...
风格。多行
/* ... */
注释,附行必须以
*
开始并和之前行的 *
对其。
/* * This is // And so /* Or you can * okay. // is this. * even do this. */ */
Comments are not enclosed in boxes drawn with asterisks or other characters.
不要用星号或其他字符把注释画在框框里。
Tip: When writing multi-line comments, use the
/* ... */
style if you want automatic code formatters to
re-wrap the lines when necessary (paragraph-style). Most formatters don't re-wrap lines in
// ...
style comment blocks.
提示:当写多行注释时,如果你想在必要时自动调整列宽换行,用
/* ... */
风格(段落风格)。大多数格式化不会调整
// ...
风格的行。
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:
类或成员的修饰符按Java语言规范的顺序出现:
public protected private abstract static final transient volatile synchronized native strictfp
long
-valued integer literals use an uppercase L
suffix, never
lowercase (to avoid confusion with the digit 1
). For example, 3000000000L
rather than 3000000000l
.
long
-用大写后缀L
定义长整型,永远不要用小写 (避免和数字1
混淆)。例如:3000000000L
好于 3000000000l
。
Identifiers use only ASCII letters and digits, and in two cases noted below, underscores. Thus
each valid identifier name is matched by the regular expression \w+
.
标识符只用 ASCII字符、数字,和下面提到的两种情况下可以有下划线。因此每个有效的标识符名称应该能正确匹配正则表达式 \w+
。
In Google Style special prefixes or
suffixes, like those seen in the examples name_
,
mName
,
s_name
and
kName
, are not used.
在Google风格中,不要使用特殊的前缀和后缀,像这样的 name_
,
mName
,
s_name
和
kName
。
Package names are all lowercase, with consecutive words simply concatenated together (no
underscores). For example, com.example.deepspace
, not
com.example.deepSpace
or
com.example.deep_space
.
包名全部小写,由连续的单词简单的串联起来(没有下划线)。例如: com.example.deepspace
, 而不是
com.example.deepSpace
或
com.example.deep_space
。
Class names are written in UpperCamelCase.
类名写成大驼峰式命名.
Class names are typically nouns or noun phrases. For example,
Character
or
ImmutableList
. Interface names may also be nouns or
noun phrases (for example, List
), but may sometimes be
adjectives or adjective phrases instead (for example,
Readable
).
代表性地,类名是名词或名称短语。例如:
Character
或
ImmutableList
。接口名称也可以是名词或名词短语(例如:List
),但是有时可能是形容词或形容词短语(例如:Readable
)。
There are no specific rules or even well-established conventions for naming annotation types.
没有特殊规则或甚至已确认的惯例用来在名称中注解类型。
Test classes are named starting with the name of the class they are testing, and ending
with Test
. For example,
HashTest
or
HashIntegrationTest
.
被测试的类名,并在结尾加上Test
,来命名测试类。例如:
HashTest
或
HashIntegrationTest
。
Method names are written in lowerCamelCase.
方法名写成小驼峰式命名。
Method names are typically verbs or verb phrases. For example,
sendMessage
or
stop
.
代表性地,方法名是动词或动词短语。例如:
sendMessage
或
stop
。
Underscores may appear in JUnit test method names to separate logical components of the
name. One typical pattern is test<MethodUnderTest>_<state>
,
for example testPop_emptyStack
. There is no One Correct
Way to name test methods.
下划线可以出现在JUnit测试方法名中,用来分割名称中的逻辑单元。一种代表性的模式是
test<MethodUnderTest>_<state>
,
例如:testPop_emptyStack
。命名测试方法并没有唯一的正确方式。
Constant names use CONSTANT_CASE
: all uppercase
letters, with words separated by underscores. But what is a constant, exactly?
常量名用CONSTANT_CASE
: 全部字符大写,用下划线分割单词。但是,到底什么是真正的常量?
Every constant is a static final field, but not all static final fields are constants. Before choosing constant case, consider whether the field really feels like a constant. For example, if any of that instance's observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough. Examples:
每个常量都是 static final 字段,但不是所有 static final 字段都是常量。在选择常量模式前,考虑这个字段是否真的是常量。 例如:如果那个实例的状态可以改变,那它就一定不是常量。仅仅不打算改变这个对象一般是不够的。例子:
// 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 typically nouns or noun phrases. 代表性地,这些名字是名词或名词短语。
Non-constant field names (static or otherwise) are written in lowerCamelCase.
非常量字段名(静态或其他)参照 小驼峰式命名。
These names are typically nouns or noun phrases. For example,
computedValues
or
index
.
代表性地,这些名字式名词或名词短语。例如:
computedValues
或
index
。
Parameter names are written in lowerCamelCase.
参数名参照小驼峰式命名。
One-character parameter names should be avoided.
应避免单字符参数名。
Local variable names are written in lowerCamelCase, and can be abbreviated more liberally than other types of names.
本地变量名参照小驼峰式命名,可以比其他类型的命名更自由更简短。
However, one-character names should be avoided, except for temporary and looping variables.
然而,应避免但字符名称,除非是临时性变量或循环变量。
Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.
就算本地变量是 final 或不可变的,它也不被认为是常量,不应该像常量一样命名。
Each type variable is named in one of two styles:
范型变量名被命名成两种风格之一:
E
, T
,
X
, T2
)E
, T
,
X
, T2
)
T
(examples:
RequestT
, FooBarT
).
T
(例如:RequestT
,
FooBarT
)。Sometimes there is more than one reasonable way to convert an English phrase into camel case, such as when acronyms or unusual constructs like "IPv6" or "iOS" are present. To improve predictability, Google Style specifies the following (nearly) deterministic scheme.
有时,有超过一个合理的方式去转化一个英语短语到驼峰式,比如当出现首字母大写缩写或专用名词 "IPv6" 或 "iOS"时。为了提升预见性,Google风格制定了以下基本确定的格式。
Beginning with the prose form of the name: 从名称的正常格式开始:
Note that the casing of the original words is almost entirely disregarded. 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 * |
*Acceptable, but not recommended. * 可接受,但不推荐。
Note: Some words are ambiguously hyphenated in the English language: for example
"nonempty" and "non-empty" are both correct, so the method names
checkNonempty
and
checkNonEmpty
are likewise both correct.
注意:在英语中,有些单词间的连接符是可有可无的。如:
"nonempty" 和 "non-empty" 都是正确的,所以这些方法名
checkNonempty
和
checkNonEmpty
也都是正确的。
A method is marked with the @Override
annotation
whenever it is legal. This includes a class method overriding a superclass method, a class method
implementing an interface method, and an interface method respecifying a superinterface
method.
只要符合@Override
注解规范就加上它。这包括一个类方法重写超类方法,一个类方法实现接口方法和接口重新定义父接口方法。
Except as noted below, it is very rarely correct to do nothing in response to a caught
exception. (Typical responses are to log it, or if it is considered "impossible", rethrow it as an
AssertionError
.)
除了下面提及的,再捕获异常块中不做任何事是不对的。(代表性地是写日志说明,如果认为这种异常是不可能发生地,重新抛出
AssertionError
。)
When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.
当真地合理地在catch块中不用做任何动作,在注释中说明合适的理由。
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 tests, a caught exception may be ignored without comment if it is
named expected
. The following is a very common idiom
for ensuring that the method under test does throw an exception of the expected type, so
a comment is unnecessary here.
特殊情况:在测试中,如果捕获的异常被命名成expected
,就可以不写注释并且不做任何事。下面是一个很常见的语句,清楚表明测试里的方法会抛出一个期望的异常,所以注释在这里就不是必须的。
try { emptyStack.pop(); fail(); } catch (NoSuchElementException expected) { }
When a reference to a static class member must be qualified, it is qualified with that class's name, not with a reference or expression of that class's type.
当必须保留引用类的静态成员,就和类名一起保留,不要和那个类的引用变量或者表达式一起使用。
Foo aFoo = ...; Foo.aStaticMethod(); // good aFoo.aStaticMethod(); // bad somethingThatYieldsAFoo().aStaticMethod(); // very bad
It is extremely rare to override Object.finalize
.
重写Object.finalize
是非常罕见的。
Tip: Don't do it. If you absolutely must, first read and understand Effective Java Item 7, "Avoid Finalizers," very carefully, and then don't do it.
提示:不要这么做。如果你的的确确必须这么做,先非常仔细的阅读并理解 Effective Java Item 7, "避免 Finalizers,",然后不这么做。
The basic formatting of Javadoc blocks is as seen in this example:
Javadoc块的基本格式看起来像下面的例子:
/** * Multiple lines of Javadoc text are written here, * wrapped normally... */ public int method(String p1) { ... }
... or in this single-line example:
... 或者单行格式例子:
/** An especially short bit of Javadoc. */
The basic form is always acceptable. The single-line form may be substituted when there are no at-clauses present, and the entirety of the Javadoc block (including comment markers) can fit on a single line.
基本格式任何地方都可以用。单行格式可以在没有@子句出现,且整个Javadoc块(包括*号)可以被填入一行时用。
One blank line—that is, a line containing only the aligned leading asterisk
(*
)—appears between paragraphs, and before the group of "at-clauses" if
present. Each paragraph but the first has <p>
immediately before the first word,
with no space after.
一行空行—就是这行只有开始对齐的星号(*
)—出现在段落之间,且在@子句之前,除了第一个以外的每个段落的第一个单词前要有<p>
,且后面没有空格。
Any of the standard "at-clauses" that are used appear in the order @param
,
@return
, @throws
, @deprecated
, and these four types never
appear with an empty description. When an at-clause doesn't fit on a single line, continuation lines
are indented four (or more) spaces from the position of the @
.
任何标准的"@子句"按这种顺序出现:@param
,
@return
, @throws
, @deprecated
,且这4个子句禁止出现不带说明的情况。当一个@子句不能填入一行时,后续行以@
为标准锁进4个(或更多)空格。
The Javadoc for each class and member begins with a brief summary fragment. This fragment is very important: it is the only part of the text that appears in certain contexts such as class and method indexes.
这种Javadoc可以用来给每个类和成员加上一个简单的摘要片段。这种片段很重要:它是唯一的文字出现在上下文某处如类和方法的索引。
This is a fragment—a noun phrase or verb phrase, not a complete sentence. It does
not begin with A {@code Foo} is a...
, or
This method returns...
, nor does it form a complete imperative sentence
like Save the record.
. However, the fragment is capitalized and
punctuated as if it were a complete sentence.
这是一个片段——一个名字短语或者动词短语,不是一个完整的句子。它不以A {@code Foo} is a...
或
This method returns...
开头,也不是完整的句子,像
Save the record.
。然而,片段是要大写和加标点的,就好像一个完整的句子。
Tip: A common mistake is to write simple Javadoc in the form
/** @return the customer ID */
. This is
incorrect, and should be changed to
/** Returns the customer ID. */
.
提示:一种常见的错误是写这种格式的Javadoc
/** @return the customer ID */
。这是错误的,应改成
/** Returns the customer ID. */
。
At the minimum, Javadoc is present for every
public
class, and every
public
or
protected
member of such a class, with a few exceptions
noted below.
除了下面提高的一些情况,至少,Javadoc要出现在每个
public
类和每个
public
或
protected
类成员。
Javadoc is optional for "simple, obvious" methods like
getFoo
, in cases where there really and truly is
nothing else worthwhile to say but "Returns the foo".
“简单,清晰”的方法如
getFoo
,Javadoc是可选的,这个例子是真真切切除了"返回foo"外没有任何意思了。
The test methods of a unit test class are perhaps the most common example of this exemption. These methods can usually be named descriptively enough that no additional documentation is needed.
单元测试类的测试方法可能是最常见的例外。这些方法通常被命名成有足够的说明性,不需要额外的文档。
Tip: Important: it is not appropriate to cite this exception to justify
omitting relevant information that a typical reader might need to know. For example, for a method
named getCanonicalName
, don't omit its documentation
(with the rationale that it would say only /** Returns
the canonical name. */
) if a typical reader may have no idea what the term "canonical name"
means!
提示:重要:不应利用这种例外去省略读者需要知道的相关信息。例如,方法名
getCanonicalName
,如果读者可能不知道术语"canonical name"的意思,就不应省略它的文档
(名字仅说明了/** 返回canonical name. */
)!
Javadoc is not always present on a method that overrides a supertype method.
Javadoc不总是出现在一个重写超类方法的方法上。
Classes and members that are not visible outside their package still have Javadoc as needed. Whenever an implementation comment would be used to define the overall purpose or behavior of a class, method or field, that comment is written as Javadoc instead. (It's more uniform, and more tool-friendly.)
不被包外可见的类和成员已经有必须的Javadoc。无论何时一个代码注释被用来说明类、方法或字段的全部目的或行为,注释就应该被写成Javadoc。(这更统一,对工具更友好。)