From db0a26320f3e930c6ea7225ed53539b4fb31310c Mon Sep 17 00:00:00 2001 From: Stephen Hicks Date: Thu, 3 Nov 2016 16:38:46 -0700 Subject: [PATCH] Update Java and C++ style guides with various changes since the last update. --- cppguide.html | 432 +++++++++++++++++++++++-------------------------- javaguide.html | 120 +++++++++----- 2 files changed, 280 insertions(+), 272 deletions(-) diff --git a/cppguide.html b/cppguide.html index 3539e68..15eb6f3 100644 --- a/cppguide.html +++ b/cppguide.html @@ -5,6 +5,7 @@ Google C++ Style Guide +
@@ -181,7 +182,7 @@ pitfalls of using header files.

Header files should be self-contained (compile on their own) and end in .h. Non-header files that are meant for inclusion -should end in .inc.

+should end in .inc and be used sparingly.

@@ -191,25 +192,27 @@ header. Specifically, a header should have header guards and include all other headers it needs.

-

If a template or inline function is declared in a .h -file, that same header should provide its definition. The definitions -of these constructs must be included into every .cc file -that uses them, or the program may fail to link in some build -configurations. Do not move these definitions to separately included -header files (-inl.h); this practice was common in the -past, but is no longer allowed.

+

Prefer placing the definitions for template and inline functions in +the same file as their declarations. The definitions of these +constructs must be included into every .cc file that uses +them, or the program may fail to link in some build configurations. If +declarations and definitions are in different files, including the +former should transitively include the latter. Do not move these +definitions to separately included header files (-inl.h); +this practice was common in the past, but is no longer allowed.

As an exception, a template that is explicitly instantiated for all relevant sets of template arguments, or that is a private implementation detail of a class, is allowed to be defined in the one and only .cc file that instantiates the template.

-

There are rare cases where a file is not meant to be -self-contained, but it is meant to be included at a specific point in -the code. Examples are files that need to be included multiple times -or platform-specific implementation details that are essentially part -of other self-contained headers. Such files should use the file -extension .inc.

+

There are rare cases where a file designed to be included is not +self-contained. These are typically intended to be included at unusual +locations, such as the middle of another file. They might not +use header guards, and might not include +their prerequisites. Name such files with the .inc +extension. Use sparingly, and prefer self-contained headers when +possible.

@@ -509,11 +512,12 @@ system-specific code small and localized. Example:

With few exceptions, place code in a namespace. Namespaces should have unique names based on the project name, and possibly -its path. Unnamed namespaces in .cc files are -encouraged. Do not use using-directives (e.g. +its path. Do not use using-directives (e.g. using namespace foo). Do not use -inline namespaces.

-
+inline namespaces. For unnamed namespaces, see +Unnamed Namespaces and +Static Variables. +

@@ -544,8 +548,8 @@ example:

namespace X {
 inline namespace Y {
   void foo();
-}
-}
+}  // namespace Y
+}  // namespace X
 

The expressions X::Y::foo() and @@ -565,10 +569,6 @@ because names aren't actually restricted to the namespace where they are declared. They are only useful as part of some larger versioning policy.

-

Use of unnamed namespaces in header files can easily -cause violations of the C++ One Definition Rule -(ODR).

-

In some contexts, it's necessary to repeatedly refer to symbols by their fully-qualified names. For deeply-nested namespaces, this can add a lot of clutter.

@@ -576,46 +576,12 @@ namespaces, this can add a lot of clutter.

-

Use namespaces according to the policy described -below. Terminate namespaces with comments as shown in the -given examples. See also the rules on -Namespace Names.

-
-
- -

Unnamed Namespaces

+

Namespaces should be used as follows:

- -

Named Namespaces

- -

Named namespaces should be used as follows:

- - + + + +

Unnamed Namespaces and Static +Variables

+ +
+

When definitions in a .cc file do not need to be +referenced outside that file, place them in an unnamed +namespace or declare them static. Do not use either +of these constructs in .h files. +

+ +
+ +
+

All declarations can be given internal linkage by placing them in +unnamed namespaces, and functions and variables can be given internal linkage by +declaring them static. This means that anything you're declaring +can't be accessed from another file. If a different file declares something +with the same name, then the two entities are completely independent.

+
+ +
+ +

Use of internal linkage in .cc files is encouraged +for all code that does not need to be referenced elsewhere. +Do not use internal linkage in .h files.

+ +

Format unnamed namespaces like named namespaces. In the + terminating comment, leave the namespace name empty:

+ +
namespace {
+...
+}  // namespace
+
+
+

Nonmember, Static Member, and Global Functions

@@ -747,8 +751,8 @@ functions which do not share static data, use namespace foo_bar { void Function1(); void Function2(); -} -} +} // namespace foo_bar +} // namespace myproject

instead of

namespace myproject {
@@ -757,14 +761,13 @@ class FooBar {
   static void Function1();
   static void Function2();
 };
-}
+}  // namespace myproject
 

If you define a nonmember function and it is only -needed in its .cc file, use an unnamed -namespace or -static linkage (eg static int Foo() -{...}) to limit its scope.

+needed in its .cc file, use +internal linkage to limit +its scope.

@@ -793,12 +796,12 @@ i = f(); // Bad -- initialization separate from declaration.
int j = g();  // Good -- declaration has initialization.
 
-
vector<int> v;
+
std::vector<int> v;
 v.push_back(1);  // Prefer initializing using brace initialization.
 v.push_back(2);
 
-
vector<int> v = {1, 2};  // Good -- v starts initialized.
+
std::vector<int> v = {1, 2};  // Good -- v starts initialized.
 

Variables needed for if, while @@ -855,7 +858,7 @@ for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, -we do not allow namespace-scope static variables to be initialized +we do not allow non-local static variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals. However, a static POD variable within @@ -895,7 +898,7 @@ both places.)

As a result we only allow static variables to contain POD data. This rule completely disallows -vector (use C arrays instead), or +std::vector (use C arrays instead), or string (use const char []).

@@ -947,8 +950,6 @@ of the constructor.

-

The problems with doing work in constructors are:

-
  • If the work calls virtual functions, these calls will not get dispatched to the subclass @@ -1011,11 +1012,8 @@ class definition of the source or destination type. An implicit conversion in the source type is defined by a type conversion operator named after the destination type (e.g. operator bool()). An implicit conversion in the destination -type is defined by a converting constructor, which -is a constructor that can take the source type as its only -argument. Note that a multi-parameter constructor can still -be a converting constructor, if all but the first parameter -have default values.

    +type is defined by a constructor that can take the source type as +its only argument (or only argument with no default value).

    The explicit keyword can be applied to a constructor or (since C++11) a conversion operator, to ensure that it can only be @@ -1160,7 +1158,7 @@ objects tied to a specific scope (Cleanup), or closely coupled to object identity (Mutex) cannot be copied meaningfully. Copy operations for base class types that are to be used polymorphically are hazardous, because use of them can lead to -object slicing. +object slicing. Defaulted or carelessly-implemented copy operations can be incorrect, and the resulting bugs can be confusing and difficult to diagnose.

    @@ -1207,7 +1205,14 @@ can use to implement it.

    If you do not want to support copy/move operations on your type, explicitly disable them using = delete in -the public: section.

    +the public: section:

    + +
    // MyClass is neither copyable nor movable.
    +MyClass(const MyClass&) = delete;
    +MyClass& operator=(const MyClass&) = delete;
    +
    + +

@@ -1594,50 +1599,30 @@ reasons, we allow data members of a test fixture class to be protected when using -Google +Google Test).

Declaration Order

-

Use the specified order of declarations within a class: -public: before private:, methods -before data members (variables), etc.

+

Group similar declarations together, placing public parts +earlier.

-

Your class definition should start with its -public: section, followed by its -protected: section and then its -private: section. If any of these sections -are empty, omit them.

+

A class definition should usually start with a +public: section, followed by +protected:, then private:. Omit +sections that would be empty.

-

Within each section, the declarations generally should -be in the following order:

- -
    -
  • Using-declarations, Typedefs and Enums
  • - -
  • Constants (static const data - members)
  • - -
  • Constructors and assignment operators
  • - -
  • Destructor
  • - -
  • Methods, including static methods
  • - -
  • Data Members (except static const data - members)
  • -
- -

If copying and assignment are disabled with a macro such as -DISALLOW_COPY_AND_ASSIGN, it should be -at the end of the private: section, and should be -the last thing in the class. See -Copyable and Movable Types.

+

Within each section, generally prefer grouping similar +kinds of declarations together, and generally prefer the +following order: types (including typedef, +using, and nested structs and classes), +constants, factory functions, constructors, assignment +operators, destructor, all other methods, data members.

Do not put large method definitions inline in the class definition. Usually, only trivial or @@ -1661,7 +1646,7 @@ outputs.

function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will -be non-const pointers. When ordering +be pointers to non-const. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they @@ -1821,7 +1806,7 @@ the name with some information about the arguments, e.g., rather than just Append(). If you are overloading a function to support variable number of arguments of the same type, consider making it take a -vector so that the user can use an +std::vector so that the user can use an initializer list to specify the arguments.

@@ -2091,9 +2076,7 @@ underlying object is immutable (i.e. do use shared ownership, prefer to use std::shared_ptr.

-

Do not use scoped_ptr in new code unless -you need to be compatible with older versions of C++. -Never use std::auto_ptr. Instead, use +

Never use std::auto_ptr. Instead, use std::unique_ptr.

@@ -2155,7 +2138,7 @@ rvalue reference to a string.

  • Defining a move constructor (a constructor taking an rvalue reference to the class type) makes it possible to move a value instead of copying it. If - v1 is a vector<string>, + v1 is a std::vector<string>, for example, then auto v2(std::move(v1)) will probably just result in some simple pointer manipulation instead of copying a large amount of data. @@ -2200,40 +2183,6 @@ moving a value from one object to another rather than copying it.

    -

    - Variable-Length Arrays and alloca()

    - -
    -

    We do not allow variable-length arrays or -alloca().

    -
    - -
    - -
    -

    Variable-length arrays have natural-looking syntax. Both -variable-length arrays and alloca() are very -efficient.

    -
    - -
    -

    Variable-length arrays and alloca are not part of -Standard C++. More importantly, they allocate a -data-dependent amount of stack space that can trigger -difficult-to-find memory overwriting bugs: "It ran fine -on my machine, but dies mysteriously in production".

    -
    - -
    - - -

    Use a safe allocator instead, such as -vector or -std::unique_ptr<T[]>.

    -
    - -
    -

    Friends

    @@ -3130,9 +3079,10 @@ uint64_t my_mask = 3ULL << 48;

    Preprocessor Macros

    -

    Be very cautious with macros. Prefer inline functions, -enums, and const variables to macros. Don't -use macros to define pieces of a C++ API.

    +

    Avoid defining macros, especially in headers; prefer +inline functions, enums, and const variables. +Name macros with a project-specific prefix. Do not use +macros to define pieces of a C++ API.

    @@ -3206,6 +3156,13 @@ possible:

    function/class/variable names.
  • +

    Exporting macros from headers (i.e. defining them in a header +without #undefing them before the end of the header) +is extremely strongly discouraged. If you do export a macro from a +header, it must have a globally unique name. To achieve this, it +must be named with a prefix consisting of your project's namespace +name (but upper case).

    +

    0 and nullptr/NULL

    @@ -3278,8 +3235,7 @@ memset(&data, 0, sizeof(data));

    Use auto to avoid type names that are noisy, obvious, or unimportant - cases where the type doesn't aid in clarity for the reader. Continue to use manifest type declarations when it helps -readability, and never use auto for anything but local -variables.

    +readability.

    @@ -3295,7 +3251,6 @@ small code region, the repetition may not be aiding readability. the initialization expression, since that avoids the possibility of unintended copies or type conversions. -

    @@ -3308,7 +3263,7 @@ like:

    auto i = y.Find(key);
    -

    It may not be obvious what the resulting types are if the type +

    it may not be obvious what the resulting types are if the type of y isn't very well known, or if y was declared many lines earlier.

    @@ -3325,10 +3280,8 @@ than intended.

    -

    auto is permitted, for local variables only, when it -increases readability, particularly as described below. Do not -use auto for file-scope or namespace-scope variables, or -for class members. Never initialize an auto-typed +

    auto is permitted when it increases readability, +particularly as described below. Never initialize an auto-typed variable with a braced initializer list.

    Specific cases where auto is allowed or encouraged: @@ -3348,8 +3301,8 @@ nearby. anything other than equality comparison.

  • (Encouraged) When iterating over a map with a range-based loop (because it is often assumed that the correct type -is pair<KeyType,ValueType> whereas it is actually -pair<const KeyType,ValueType>). This is +is std::pair<KeyType, ValueType> whereas it is actually +std::pair<const KeyType, ValueType>). This is particularly well paired with local key and value aliases for .first and .second (often const-ref). @@ -3364,7 +3317,6 @@ and .second (often const-ref).
  • -

    @@ -3378,8 +3330,7 @@ and .second (often const-ref).

    In C++03, aggregate types (arrays and structs with no -constructor) could be initialized with braced initializer lists. -

    +constructor) could be initialized with braced initializer lists.

    struct Point { int x; int y; };
     Point p = {1, 2};
    @@ -3391,26 +3342,26 @@ be created with a braced initializer list, known as a
     of its use.

    // Vector takes a braced-init-list of elements.
    -vector<string> v{"foo", "bar"};
    +std::vector<string> v{"foo", "bar"};
     
     // Basically the same, ignoring some small technicalities.
     // You may choose to use either form.
    -vector<string> v = {"foo", "bar"};
    +std::vector<string> v = {"foo", "bar"};
     
     // Usable with 'new' expressions.
     auto p = new vector<string>{"foo", "bar"};
     
     // A map can take a list of pairs. Nested braced-init-lists work.
    -map<int, string> m = {{1, "one"}, {2, "2"}};
    +std::map<int, string> m = {{1, "one"}, {2, "2"}};
     
     // A braced-init-list can be implicitly converted to a return type.
    -vector<int> test_function() { return {1, 2, 3}; }
    +std::vector<int> test_function() { return {1, 2, 3}; }
     
     // Iterate over a braced-init-list.
     for (int i : {-1, -2, -3}) {}
     
     // Call a function using a braced-init-list.
    -void TestFunction2(vector<int> v) {}
    +void TestFunction2(std::vector<int> v) {}
     TestFunction2({1, 2, 3});
     
    @@ -3550,7 +3501,6 @@ wrapper std::function. hand; very long nested anonymous functions can make code harder to understand. -
    @@ -3599,6 +3549,7 @@ use a named function instead of a lambda.
  • Specify the return type of the lambda explicitly if that will make it more obvious to readers, as with auto.
  • + @@ -3759,19 +3710,28 @@ Currently, the following libraries are permitted:

    Statistical Distributions and Functions from boost/math/distributions +
  • + Special Functions from boost/math/special_functions
  • +
  • Multi-index from boost/multi_index
  • Heap from boost/heap
  • -
  • The flat containers from - Container: +
  • The flat containers from + Container: boost/container/flat_map, and boost/container/flat_set
  • -
  • - Intrusive from boost/intrusive.
  • +
  • Intrusive + from boost/intrusive.
  • + +
  • The + boost/sort library.
  • + +
  • Preprocessor + from boost/preprocessor.
  • We are actively considering adding other Boost @@ -3977,8 +3937,8 @@ guide, the following C++11 features may not be used:

    as __builtin_prefetch, designated initializers (e.g. Foo f = {.field = 3}), inline assembly, __COUNTER__, __PRETTY_FUNCTION__, compound statement expressions (e.g. - foo = ({ int x; Bar(&x); x }), and the a?:b - syntax.

    + foo = ({ int x; Bar(&x); x }), variable-length arrays and + alloca(), and the a?:b syntax.

    @@ -4146,7 +4106,17 @@ int pc_reader; // Lots of things can be abbreviated "pc". int cstmr_id; // Deletes internal letters.
    - +

    Note that certain universally-known abbreviations are OK, such as +i for an iteration variable and T for a +template parameter.

    + +

    Template parameters should follow the naming style for their +category: type template parameters should follow the rules for +type names, and non-type template +parameters should follow the rules for +variable names. + +

    File Names

    @@ -4226,9 +4196,9 @@ enum UrlTableErrors { ...

    Variable Names

    -

    The names of variables and data members are all lowercase, with -underscores between words. Data members of classes (but not structs) -additionally have trailing underscores. For instance: +

    The names of variables (including function parameters) and data members are +all lowercase, with underscores between words. Data members of classes (but not +structs) additionally have trailing underscores. For instance: a_local_variable, a_struct_data_member, a_class_data_member_.

    @@ -4305,16 +4275,18 @@ versus a class.

    Function Names

    -

    Regular functions have mixed case; "cheap" functions may -use lower case with underscores.

    +

    Regular functions have mixed case; accessors and mutators may be named +like variables.

    -

    Ordinarily, functions should start with a capital letter and have -a capital letter for each new word (a.k.a. "upper camel case" or "Pascal case"). -Such names should not have underscores. Prefer to capitalize acronyms as -single words (i.e. StartRpc(), not StartRPC()).

    +

    Ordinarily, functions should start with a capital letter and have a +capital letter for each new word +(a.k.a. "Camel +Case" or "Pascal case"). Such names should not have +underscores. Prefer to capitalize acronyms as single words +(i.e. StartRpc(), not StartRPC()).

    AddTableEntry()
     DeleteUrl()
    @@ -4326,22 +4298,11 @@ constants that are exposed as part of an API and that are intended to look
     like functions, because the fact that they're
     objects rather than functions is an unimportant implementation detail.)

    -

    Functions that are very cheap to call may instead follow the style -for variable names (all lower-case, with underscores between words). -The rule of thumb is that such a function should be so cheap that you -normally wouldn't bother caching its return value when calling it in -a loop. A canonical example is an inline method that just returns one -of the class's member variables.

    +

    Accessors and mutators (get and set functions) may be named like +variables. These often correspond to actual member variables, but this is +not required. For example, int count() and void +set_count(int count).

    -
    class MyClass {
    - public:
    -  ...
    -  bool is_empty() const { return num_entries_ == 0; }
    -
    - private:
    -  int num_entries_;
    -};
    -

    Namespace Names

    @@ -4668,7 +4629,7 @@ bool IsTableFull();

    When documenting function overrides, focus on the specifics of the override itself, rather than repeating -the comment from the overriden function. In many of these +the comment from the overridden function. In many of these cases, the override needs no additional documentation and thus no comment is required.

    @@ -4793,7 +4754,8 @@ DoSomethingElseThatIsLonger(); // Two spaces between the code and the comment. // thus the comment lines up with the following comments and code. DoSomethingElse(); // Two spaces before line comments normally. } -vector<string> list{// Comments in braced lists describe the next element .. +std::vector<string> list{ + // Comments in braced lists describe the next element... "First item", // .. and should be aligned appropriately. "Second item"}; @@ -5134,7 +5096,7 @@ hit the tab key.

    Return type on the same line as function name, parameters on the same line if they fit. Wrap parameter lists which do not fit on a single line as you would wrap arguments in a -function call.

    +function call.

    @@ -5258,11 +5220,11 @@ lists like other comma-separated lists.

    For by-reference captures, do not leave a space between the ampersand (&) and the variable name.

    int x = 0;
    -auto add_to_x = [&x](int n) { x += n; };
    +auto x_plus_n = [&x](int n) -> int { return x + n; }
     

    Short lambdas may be written inline as function arguments.

    -
    set<int> blacklist = {7, 8, 9};
    -vector<int> digits = {3, 9, 1, 8, 4, 7, 1};
    +
    std::set<int> blacklist = {7, 8, 9};
    +std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1};
     digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) {
                    return blacklist.find(i) != blacklist.end();
                  }),
    @@ -5366,7 +5328,7 @@ is no name, assume a zero-length name.

    // Examples of braced init list on a single line.
     return {foo, bar};
     functioncall({foo, bar});
    -pair<int, int> p{foo, bar};
    +std::pair<int, int> p{foo, bar};
     
     // When you have to wrap.
     SomeFunction(
    @@ -5513,7 +5475,7 @@ if (condition) {
     

    Switch statements may use braces for blocks. Annotate non-trivial fall-through between cases. Braces are optional for single-statement loops. -Empty loop bodies should use {} or continue.

    +Empty loop bodies should use empty braces or continue.

    @@ -5564,13 +5526,13 @@ for (int i = 0; i < kSomeNumber; ++i) { -

    Empty loop bodies should use {} or -continue, but not a single semicolon.

    +

    Empty loop bodies should use an empty pair of braces or continue, +but not a single semicolon.

    while (condition) {
       // Repeat test until it returns false.
     }
    -for (int i = 0; i < kSomeNumber; ++i) {}  // Good - empty body.
    +for (int i = 0; i < kSomeNumber; ++i) {}  // Good - one newline is also OK.
     while (condition) continue;  // Good - continue indicates no logic.
     
    @@ -5616,11 +5578,18 @@ char *c; const string &str; // These are fine, space following. -char* c; // but remember to do "char* c, *d, *e, ...;"! +char* c; const string& str; -
    char * c;  // Bad - spaces on both sides of *
    +It is allowed (if unusual) to declare multiple variables in the same
    +declaration, but it is disallowed if any of those have pointer or
    +reference decorations. Such declarations are easily misread.
    +
    // Fine if helpful for readability.
    +int x, y;
    +
    +
    int x, *y;  // Disallowed - no & or * in multiple declaration
    +char * c;  // Bad - spaces on both sides of *
     const string & str;  // Bad - spaces on both sides of &
     
    @@ -5722,8 +5691,8 @@ will call a default constructor if available. To force the non-std::initializer_list constructor, use parentheses instead of braces.

    -
    vector<int> v(100, 1);  // A vector of 100 1s.
    -vector<int> v{100, 1};  // A vector of 100, 1.
    +
    std::vector<int> v(100, 1);  // A vector of 100 1s.
    +std::vector<int> v{100, 1};  // A vector of 100, 1.
     

    Also, the brace form prevents narrowing of integral @@ -6004,16 +5973,11 @@ if (x && !y)

    // No spaces inside the angle brackets (< and >), before
     // <, or between >( in a cast
    -vector<string> x;
    +std::vector<string> x;
     y = static_cast<char*>(x);
     
     // Spaces between type and pointer are OK, but be consistent.
    -vector<char *> x;
    -set<list<string>> x;        // Permitted in C++11 code.
    -set<list<string> > x;       // C++03 required a space in > >.
    -
    -// You may optionally use symmetric spacing in < <.
    -set< list<string> > x;
    +std::vector<char *> x;
     
    @@ -6201,6 +6165,6 @@ more interesting. Have fun!


    - + diff --git a/javaguide.html b/javaguide.html index 5ef0dc8..789bdf4 100644 --- a/javaguide.html +++ b/javaguide.html @@ -3,10 +3,11 @@ Google Java Style Guide - + - - + + +

    Google Java Style Guide

    @@ -36,7 +37,11 @@ avoids giving advice that isn't clearly enforceable (whether by human o
  • The term class is used inclusively to mean an "ordinary" class, enum class, interface or annotation type (@interface).
  • -
  • The term comment always refers to implementation comments. We do not +
  • The term member (of a class) is used inclusively to mean a nested class, field, + method, or constructor; that is, all top-level contents of a class except initializers + and comments. + +
  • The term comment always refers to implementation comments. We do not use the phrase "documentation comments", instead using the common term "Javadoc."
  • @@ -202,6 +207,11 @@ sorts before ';'.)

    +

    3.3.4 No static import for classes

    + +

    Static import is not used for static nested classes. They are imported with +normal imports.

    +

    3.4 Class declaration

    @@ -209,16 +219,17 @@ sorts before ';'.)

    Each top-level class resides in a source file of its own.

    -

    3.4.2 Class member ordering

    + +

    3.4.2 Ordering of class contents

    -

    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.

    +

    The order you choose for the members and initializers of your class can have a great effect on +learnability. However, there's no single correct recipe for how to do it; different classes may +order their contents in different ways.

    -

    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.

    +

    What is important is that each class uses 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.

    @@ -226,8 +237,7 @@ added" ordering, which is not a logical ordering.

    3.4.2.1 Overloads: never split

    When a class has multiple constructors, or multiple methods with the same name, these appear -sequentially, with no intervening members (not even private ones).

    - +sequentially, with no other code in between (not even private members).

    4 Formatting

    @@ -299,16 +309,27 @@ return new MyClass() {

    4.1.3 Empty blocks: may be concise

    -

    An empty block or block-like construct may be closed immediately after it is -opened, with no characters or line break in between +

    An empty block or block-like construct may be in K & R style (as described in +Section 4.1.2). Alternatively, it 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 +if/else or try/catch/finally).

    -

    Example:

    +

    Examples:

    -
      void doNothing() {}
    +
      // This is acceptable
    +  void doNothing() {}
    +
    +  // This is equally acceptable
    +  void doNothingElse() {
    +  }
    +
    +
      // This is not acceptable: No concise empty blocks in a multi-block statement
    +  try {
    +    doSomething();
    +  } catch (Exception e) {}
     

    4.2 Block indentation: +2 spaces

    @@ -370,12 +391,17 @@ without the need to line-wrap.

    the symbol. (Note that this is not the same practice used in Google style for other languages, such as C++ and JavaScript.)
      -
    • This also applies to the following "operator-like" symbols: the dot separator - (.), the two colons of a method reference - (::), the ampersand in type bounds - (<T extends Foo & Bar>), and the pipe in - catch blocks - (catch (FooException | BarException e)).
    • +
    • This also applies to the following "operator-like" symbols: +
        +
      • the dot separator (.)
      • +
      • the two colons of a method reference + (::)
      • +
      • an ampersand in a type bound + (<T extends Foo & Bar>)
      • +
      • a pipe in a catch block + (catch (FooException | BarException e)).
      • +
      +
    @@ -392,6 +418,19 @@ without the need to line-wrap.

  • A comma (,) stays attached to the token that precedes it.
  • + +
  • A line is never broken adjacent to the arrow in a lambda, except that a + break may come immediately after the arrow if the body of the lambda consists + of a single unbraced expression. Examples: +
    MyLambda<String, Long, Object> lambda =
    +    (String label, Long value, Object obj) -> {
    +        ...
    +    };
    +
    +Predicate<String> predicate = str ->
    +    longExpressionInvolving(str);
    +
    +
  • Note: The primary goal for line wrapping is to have clear @@ -418,8 +457,8 @@ previous lines.

    A single blank line appears:

      -
    1. Between consecutive members (or initializers) of a class: fields, constructors, - methods, nested classes, static initializers, instance initializers. +
    2. Between consecutive members or initializers of a class: fields, constructors, + methods, nested classes, static initializers, and instance initializers.
      • Exception: A blank line between two consecutive fields (having no other code between them) is optional. Such blank lines are used as needed to @@ -431,8 +470,8 @@ previous lines.

      • Between statements, as needed to organize the code into logical subsections. -
      • Optionally before the first member or after the last member of the class (neither - encouraged nor discouraged).
      • +
      • Optionally before the first member or initializer, or after the last member or + initializer of the class (neither encouraged nor discouraged).
      • As required by other sections of this document (such as Section 3, Source file structure, and Section 3.3, @@ -490,7 +529,7 @@ Javadoc, a single ASCII space also appears in the following places only<
      • the two colons (::) of a method reference, which is written like Object::toString
      • the dot separator (.), which is written like - object.toString()
      • + object.toString()
    3. @@ -629,8 +668,8 @@ one or more switch labels (either c

      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 -if a block were being opened. The following switch label returns to the previous indentation +

      After a switch label, there is a line break, 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.

      @@ -702,6 +741,9 @@ for example:

      This section addresses implementation comments. Javadoc is addressed separately in Section 7, Javadoc.

      +

      Any line break may be preceded by arbitrary whitespace followed by an implementation comment. +Such a comment renders the line non-blank.

      +
      4.8.6.1 Block comment style

      Block comments are indented at the same level as the surrounding code. They may be in @@ -802,15 +844,15 @@ Way to name test methods.

      Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores. But what is a constant, exactly?

      -

      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:

      +

      Constants are static final fields whose contents are deeply immutable and whose methods have no +detectable side effects. This includes primitives, Strings, immutable types, and immutable +collections of immutable types. If any of the instance's observable state can change, it is not a +constant. Merely intending to never mutate the object is not enough. Examples:

      // Constants
       static final int NUMBER = 5;
       static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
      +static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
       static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
       static final SomeMutableType[] EMPTY_ARRAY = {};
       enum SomeEnum { ENUM_CONSTANT }
      @@ -820,6 +862,8 @@ 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 ImmutableMap<String, SomeMutableType> mutableValues =
      +    ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
       static final Logger logger = Logger.getLogger(MyClass.getName());
       static final String[] nonEmptyArray = {"these", "can", "change"};
       
      @@ -1058,7 +1102,7 @@ are indented four (or more) spaces from the position of the @.

      7.2 The summary fragment

      -

      The Javadoc for each class and member begins with a brief summary fragment. This +

      Each Javadoc block 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.