diff --git a/javaguide.css b/javaguide.css index c15c9fa..c42ba83 100644 --- a/javaguide.css +++ b/javaguide.css @@ -128,6 +128,10 @@ body { margin-bottom:1em; } +em { + font-style: italic +} + h1, h2, h3, @@ -402,7 +406,7 @@ ul.nolist { code, kbd, pre { - color:#007000; + color:#009900; } kbd { @@ -426,10 +430,10 @@ pre.prettyprint { } code.bad, code.badcode { - background-color:#fcc; + color: magenta; } pre.bad, pre.badcode { - background-color:#fcc; + background-color:#ffe6d8; border-top:1px inset #a03; border-left:1px inset #a03; } diff --git a/javaguide.html b/javaguide.html index 610c7ce..74bfbad 100644 --- a/javaguide.html +++ b/javaguide.html @@ -2,7 +2,7 @@
- @@ -10,7 +10,7 @@
@@ -241,14 +241,11 @@
|
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 @@ -289,18 +286,18 @@ anywhere in a source file. This implies that:
\'
and
\\
), that sequence
is used rather than the corresponding octal
-(e.g. \012
) or Unicode
-(e.g. \u000a
) escape.
+(e.g. \012
) or Unicode
+(e.g. \u000a
) escape.
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.
Tip: in the Unicode escape case, and occasionally even when actual Unicode characters -are used, an explanatory comment can be very helpful.
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.
+makes the code easier to read and understand.Tip: In the Unicode escape case, and occasionally even when actual +Unicode characters are used, an explanatory comment can be very helpful.
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.
A source file consists of, in order:
Exactly one blank line separates each section that is present.
Terminology Note: block-like construct refers to the body of a class, method or -constructor. Note that, by Section 4.8.3.1 on +
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.
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 +
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.
+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:
A single blank line appears:
Multiple consecutive blank lines are permitted, but never required (or encouraged).
List<String> list
new int[] {5, 6}
and
- new int[] { 5, 6 }
are both validNote: this rule never requires or forbids additional space at the start or end of a -line, only interior space.
+new int[] { 5, 6 }
are both validNote: 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 +
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.
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.
+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 @@ -490,14 +488,15 @@ operator precedence table memorized.
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:
+as if it were an array initializer (see Section 4.8.3.1 on +array initializers).private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }Since enum classes are classes, all other rules for formatting classes apply.
4.8.2 Variable declarations
4.8.2.1 One variable per declaration
Every variable declaration (field or local) declares only one variable: declarations such as -
+int a, b;
are not used.int a, b;
are not used.4.8.2.2 Declared when needed, initialized as soon as possible
Local variables are not habitually declared at the start of their containing @@ -523,11 +522,11 @@ new int[] { 3,
4.8.3.2 No C-style array declarations
The square brackets form a part of the type, not the variable:
+String[] args
, not -String args[]
.String args[]
.4.8.4 Switch statements
-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 +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:
ordefault:
), followed by one or more statements.4.8.4.1 Indentation
As with any other block, the contents of a switch block are indented +2.
After a switch label, a newline appears, and the indentation level is increased +2, exactly as @@ -566,8 +565,8 @@ increased. Example:
@Override @Nullable public String getNameIfPresent() { ... } -Exception: a single parameterless annotation may instead appear -together with the first line of the signature, for example:
+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; @@ -586,7 +585,7 @@ for example:
* 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 +
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.
3000000000l
.5.1 Rules common to all identifiers
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+
.
In Google Style special prefixes or
-suffixes, like those seen in the examples name_
,
-mName
,
-s_name
and
-kName
, are not used.
name_
,
+mName
, s_name
and
+kName
, are not used.
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 +
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.
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.
Exception:@Override
may be omitted when the parent method is
+@Deprecated
.
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 @@ -710,10 +709,10 @@ try { // 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.
+
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.
try {
emptyStack.pop();
fail();
@@ -729,7 +728,7 @@ Foo.aStaticMethod(); // good
somethingThatYieldsAFoo().aStaticMethod(); // very bad
It is extremely rare to override Object.finalize
.
Tip: Don't do it. If you absolutely must, first read and understand +
It is extremely rare to override 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.
This is a fragment—a noun phrase or verb phras
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.
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. */
.
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. */
.
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.
Other classes and members 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 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".
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 +nothing else worthwhile to say but "Returns the foo".
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!
/** Returns the canonical name. */
) if a typical reader may have no idea
+what the term "canonical name" means!
Javadoc is not always present on a method that overrides a supertype method. -
-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.)