Update C++ style guide to 3.231:

- Clarify that sentence-like non-sentence comments are permitted.
 - Note that older code with incorrect #include ordering should be fixed.
 - Revamp the section on default function arguments.
 - Avoid explicitly recommending Init() methods.
 - C++11: permit "auto".
 - C++11: permit ">>" in place of "> >".
 - C++11: permit range-based "for".
 - C++11: permit variadic macros (already permitted as a C++03 extension).
 - C++11: permit "LL" and "ULL" literal suffixes (already permitted as a C++03
   extension).
 - Reflect the revised copyright and author line policy: copyright notices are
   not required, but license boilerplate may still be used (and generally
   contains a copyright notice). Author lines are not required.
 - C++11: permit new features in <algorithm> and the portion of <numeric> that
   does not require initializer lists.
 - Revise rules on forward declarations: explicitly forbid forward-declared
   functions, do not mandate forward declarations, discourage forward-declared
   templates.
 - Remove the rule requiring "const" qualifiers for member functions to be
   on the same line as the closing parenthesis of the parameter list.
 - Fix typo: "unnamed namespaces."
 - C++11: permit local types as template parameters.
 - Fix typo: "unfamiliar."
 - Relax RTTI rules to permit its use, but warn about its abuse.
 - C++11: permit nullptr and nullptr_t. Revise text referring to NULL to refer
   more generically to null pointers.
 - Remove the "don't go crazy with const" rule.
 - Fix typo: "dir/foo2" should bee "dir2/foo2."
 - Remove reference to a specific GCC version.

Update Objective-C style guide to 2.48:
 - Revise method declaration and invocation formatting rules for long names.
 - Reflect the revised copyright and author line policy: copyright notices are
   not required, but license boilerplate may still be used (and generally
   contains a copyright notice). Author lines are not required. Top-of-file
   comments are not required.
 - Fix dead link in the "nil Checks" section.
 - Cover ARC.
 - Specify that @private is only required for instance variables in header
   files.
 - Permit NSNumber literals.
 - Change the naming convention for instance variables from trailing underscore
   to leading underscore, allowing a wide exception for existing code and
   projects.
 - Fix description of BOOL with respect to its signedness.

Update Python style guide to 2.45:
 - Recommend "pylint: disable" over "pylint: disable-msg."
 - Fix case-sensitive anchor.
 - Provide a better explanation of the problems with catch-all "except:."
 - Permit "map" and "filter" in absence of inlined lambdas.

Update JavaScript style guide to 2.64:
 - Clarify rules for requiring and providing inner dependencies on classes.
 - Clarify semicolons for functions.
 - Note proper namespace and filename casing.
 - Fix typos: "@extends."
 - Permit parentheses to be omitted on unions.
 - Don't require method descriptions when obvious.
 - "in" is a keyword, put it in <code>.
 - New "Aliasing with goog.scope" section.
 - Rewrite the "Constants" section.
 - Remove the recommendation to use join() to build strings.
 - Add the "@expose" annotation.
 - Fix the "@suppress" example.
 - Remove reference alternate cast syntax.
 - Reflect the revised copyright and author line policy: copyright notices are
   not required, but license boilerplate may still be used (and generally
   contains a copyright notice). Author lines are not required.
 - Say that "use strict" is not required.
 - Fix links to "optional" section.
 - Rewrite "JavaScript Types" section.
 - Fix typos: "parameterizes," "converted."
 - Prefer in-constructor field initialization.
 - Add a section on "delete" and null-assignment.
 - Add a note about optional JSDoc comments on enum values.
 - State explicitly that dot operators belong at the ends of lines.
 - Add "@dict" and "@struct" annotations.
 - Add links to the JavaScript Types section.
 - Require (rather than encourage) compiling.

Update HTML/CSS style guide to 2.19:
 - Rephrased quotation guidelines.
 - Updated W3C I18N article reference.
 - Fixed revision number.

Update styleguide.xsl to 1.34:
 - Fix error in RefreshVisibilityFromHashParam when a URL fragment points to a
   named anchor within a section, as used by the JavaScript style guide.
This commit is contained in:
mark@chromium.org 2012-11-28 20:26:27 +00:00
parent 1407ba71db
commit c8c76a2389
6 changed files with 1209 additions and 647 deletions

View File

@ -4,7 +4,7 @@
<p align="right">
Revision 3.199
Revision 3.231
</p>
@ -145,80 +145,71 @@ Tashana Landray
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Header File Dependencies">
<STYLEPOINT title="Forward Declarations">
<SUMMARY>
Don't use an <code>#include</code> when a forward declaration
would suffice.
You may forward declare ordinary classes in order to avoid
unnecessary <code>#include</code>s.
</SUMMARY>
<BODY>
<p>
When you include a header file you introduce a dependency that
will cause your code to be recompiled whenever the header file
changes. If your header file includes other header files, any
change to those files will cause any code that includes your
header to be recompiled. Therefore, we prefer to minimize
includes, particularly includes of header files in other
header files.
</p>
<p>
You can significantly reduce the number of header files you
need to include in your own header files by using forward
declarations. For example, if your header file uses the
<code>File</code> class in ways that do not require access to
the declaration of the <code>File</code> class, your header
file can just forward declare <code>class File;</code> instead
of having to <code>#include "file/base/file.h"</code>.
</p>
<p>
How can we use a class <code>Foo</code> in a header file
without access to its definition?
</p>
<ul>
<li> We can declare data members of type <code>Foo*</code> or
<code>Foo&amp;</code>.
</li>
<li> We can declare (but not define) functions with arguments,
and/or return values, of type <code>Foo</code>. (One
exception is if an argument <code>Foo</code>
or <code>const Foo&amp;</code> has a
non-<code>explicit</code>, one-argument constructor,
in which case we need the full definition to support
automatic type conversion.)
</li>
<li> We can declare static data members of type
<code>Foo</code>. This is because static data members
are defined outside the class definition.
</li>
</ul>
<p>
On the other hand, you must include the header file for
<code>Foo</code> if your class subclasses <code>Foo</code> or
has a data member of type <code>Foo</code>.
</p>
<p>
Sometimes it makes sense to have pointer (or better,
<code>scoped_ptr</code>)
members instead of object members. However, this complicates code
readability and imposes a performance penalty, so avoid doing
this transformation if the only purpose is to minimize includes
in header files.
</p>
<p>
Of course, <code>.cc</code> files typically do require the
definitions of the classes they use, and usually have to
include several header files.
</p>
<SUBSECTION title="Note:">
If you use a symbol <code>Foo</code> in your source file, you
should bring in a definition for <code>Foo</code> yourself,
either via an #include or via a forward declaration. Do not
depend on the symbol being brought in transitively via headers
not directly included. One exception is if <code>Foo</code>
is used in <code>myfile.cc</code>, it's ok to #include (or
forward-declare) <code>Foo</code> in <code>myfile.h</code>,
instead of <code>myfile.cc</code>.
</SUBSECTION>
<DEFINITION>
A "forward declaration" is a declaration of a class, function,
or template without an associated definition. <code>#include</code>
lines can often be replaced with forward declarations of whatever
symbols are actually used by the client code.
</DEFINITION>
<PROS>
<ul>
<li>Unnecessary <code>#include</code>s force the compiler to open
more files and process more input.</li>
<li>They can also force your code to be recompiled more often, due
to changes in the header.</li>
</ul>
</PROS>
<CONS>
<ul>
<li>It can be difficult to determine the correct form of a
forward declaration in the presence of features like templates,
typedefs, default parameters, and using declarations.</li>
<li>It can be difficult to determine whether a forward declaration
or a full <code>#include</code> is needed for a given piece of code,
particularly when implicit conversion operations are involved. In
extreme cases, replacing an <code>#include</code> with a forward
declaration can silently change the meaning of code.</li>
<li>Forward declaring multiple symbols from a header can be more
verbose than simply <code>#include</code>ing the header.</li>
<li>Forward declarations of functions and templates can prevent
the header owners from making otherwise-compatible changes to
their APIs; for example, widening a parameter type, or adding
a template parameter with a default value.</li>
<li>Forward declaring symbols from namespace <code>std::</code>
usually yields undefined behavior.</li>
<li>Structuring code to enable forward declarations (e.g.
using pointer members instead of object members) can make the
code slower and more complex.</li>
<li>The practical efficiency benefits of forward declarations are
unproven.</li>
</ul>
</CONS>
<DECISION>
<ul>
<li>When using a function declared in a header file, always
<code>#include</code> that header.</li>
<li>When using a class template, prefer to <code>#include</code> its
header file.</li>
<li>When using an ordinary class, relying on a forward declaration
is OK, but be wary of situations where a forward declaration may
be insufficient or incorrect; when in doubt, just
<code>#include</code> the appropriate header.</li>
<li>Do not replace data members with pointers just to avoid an
<code>#include</code>.</li>
</ul>
Always <code>#include</code> the file that actually provides the
declarations/definitions you need; do not rely on the symbol being
brought in transitively via headers not directly included. One
exception is that <code>myfile.cc</code> may rely on
<code>#include</code>s and forward declarations from its corresponding
header file <code>myfile.h</code>.
</DECISION>
</BODY>
</STYLEPOINT>
@ -367,7 +358,7 @@ Tashana Landray
</CODE_SNIPPET>
<p>
In <code><var>dir/foo</var>.cc</code> or <code><var>dir/foo_test</var>.cc</code>,
whose main purpose is to implement or test the stuff in
whose main purpose is to implement or test the stuff in
<code><var>dir2/foo2</var>.h</code>, order your includes as
follows:
</p>
@ -382,7 +373,7 @@ Tashana Landray
<code>.h</code> files.</li>
</ol>
<p>
With the preferred ordering, if <code><var>dir/foo2</var>.h</code>
With the preferred ordering, if <code><var>dir2/foo2</var>.h</code>
omits any necessary includes, the build of
<code><var>dir/foo</var>.cc</code> or
<code><var>dir/foo</var>_test.cc</code> will break.
@ -399,8 +390,9 @@ Tashana Landray
</p>
<p>
Within each section it is nice to order the includes
alphabetically.
Within each section the includes should be ordered alphabetically.
Note that older code might not conform to this rule and should be
fixed when convenient.
</p>
<p>
For example, the includes in
@ -461,7 +453,7 @@ Tashana Landray
(also hierarchical) name axis provided by classes.
</p>
<p>
Use of unnamed spaces in header files can easily cause
Use of unnamed namespaces in header files can easily cause
violations of the C++ One Definition Rule (ODR).
</p>
</CONS>
@ -840,9 +832,8 @@ Tashana Landray
<STYLEPOINT title="Doing Work in Constructors">
<SUMMARY>
In general, constructors should merely set member variables to their
initial values. Any complex initialization should go in an explicit
<code>Init()</code> method.
Avoid doing complex initialization in constructors (in particular,
initialization that can fail or that requires virtual method calls).
</SUMMARY>
<BODY>
<DEFINITION>
@ -882,10 +873,9 @@ Tashana Landray
</ul>
</CONS>
<DECISION>
If your object requires non-trivial initialization, consider
having an explicit <code>Init()</code> method. In particular,
constructors should not call virtual functions, attempt to raise
errors, access potentially uninitialized global variables, etc.
Constructors should never call virtual functions or attempt to raise
non-fatal failures. If your object requires non-trivial
initialization, consider using a factory function or <code>Init()</code> method.
</DECISION>
</BODY>
</STYLEPOINT>
@ -1551,7 +1541,7 @@ Tashana Landray
Defining a parameter as reference avoids ugly code like
<code>(*pval)++</code>. Necessary for some applications like
copy constructors. Makes it clear, unlike with pointers, that
<code>NULL</code> is not a possible value.
a null pointer is not a possible value.
</PROS>
<CONS>
References can be confusing, as they have value syntax but
@ -1577,10 +1567,10 @@ Tashana Landray
However, there are some instances where using <code>const T*</code>
is preferable to <code>const T&amp;</code> for input parameters. For
example:
You want to pass in NULL.
The function saves a pointer or reference to the input.
<ul>
<li>You want to pass in a null pointer.</li>
<li>The function saves a pointer or reference to the input.</li>
</ul>
Remember that most of the time input parameters are going to be
@ -1643,35 +1633,47 @@ Tashana Landray
<STYLEPOINT title="Default Arguments">
<SUMMARY>
We do not allow default function parameters, except in
a few uncommon situations explained below.
We do not allow default function parameters, except in limited
situations as explained below. Simulate them with function
overloading instead, if appropriate.
</SUMMARY>
<BODY>
<PROS>
Often you have a function that uses lots of default values,
but occasionally you want to override the defaults. Default
Often you have a function that uses default values, but
occasionally you want to override the defaults. Default
parameters allow an easy way to do this without having to
define many functions for the rare exceptions.
define many functions for the rare exceptions. Compared to
overloading the function, default arguments have a cleaner
syntax, with less boilerplate and a clearer distinction
between 'required' and 'optional' arguments.
</PROS>
<CONS>
People often figure out how to use an
API by looking at existing code that uses it.
Default parameters are more difficult to maintain because
copy-and-paste from previous code may not reveal all the
parameters. Copy-and-pasting of code segments can cause major
problems when the default arguments are not appropriate for
the new code.
Function pointers are confusing in the presence of default
arguments, since the function signature often doesn't match
the call signature. Adding a default argument to an existing
function changes its type, which can cause problems with code
taking its address. Adding function overloads avoids these
problems. In addition, default parameters may result in
bulkier code since they are replicated at every call-site --
as opposed to overloaded functions, where "the default"
appears only in the function definition.
</CONS>
<DECISION>
<p>
Except as described below, we require all arguments to be
explicitly specified, to force programmers to consider the API
and the values they are passing for each argument rather than
silently accepting defaults they may not be aware of.
While the cons above are not that onerous, they still
outweigh the (small) benefits of default arguments over
function overloading. So except as described below, we
require all arguments to be explicitly specified.
</p>
<p>
One specific exception is when default arguments are used to
simulate variable-length argument lists.
One specific exception is when the function is a static
function (or in an unnamed namespace) in a .cc file. In
this case, the cons don't apply since the function's use is
so localized.
</p>
<p>
Another specific exception is when default arguments are
used to simulate variable-length argument lists.
</p>
<CODE_SNIPPET>
// Support up to 4 params by using a default empty AlphaNum.
@ -1851,57 +1853,107 @@ Tashana Landray
<STYLEPOINT title="Run-Time Type Information (RTTI)">
<SUMMARY>
We do not use Run Time Type Information (RTTI).
Avoid using Run Time Type Information (RTTI).
</SUMMARY>
<BODY>
<DEFINITION>
RTTI allows a programmer to query the C++ class of an
object at run time.
object at run time. This is done by use of <code>typeid</code> or
<code>dynamic_cast</code>.
</DEFINITION>
<CONS>
<p>
Querying the type of an object at run-time frequently means a
design problem. Needing to know the type of an
object at runtime is often an indication that
the design of your class hierarchy is flawed.
</p>
<p>
Undisciplined use of RTTI makes code hard to maintain. It can
lead to type-based decision trees or switch statements scattered
throughout the code, all of which must be examined when making
further changes.
</p>
</CONS>
<PROS>
<p>
It is useful in some unittests. For example, it is useful in
tests of factory classes where the test has to verify that a
newly created object has the expected dynamic type.
The standard alternatives to RTTI (described below) require
modification or redesign of the class hierarchy in question.
Sometimes such modifications are infeasible or undesirable,
particularly in widely-used or mature code.
</p>
<p>
In rare circumstances, it is useful even outside of
tests.
RTTI can be useful in some unit tests. For example, it is useful in
tests of factory classes where the test has to verify that a
newly created object has the expected dynamic type. It is also
useful in managing the relationship between objects and their mocks.
</p>
<p>
RTTI is useful when considering multiple abstract objects. Consider
<CODE_SNIPPET>
bool Base::Equal(Base* other) = 0;
bool Derived::Equal(Base* other) {
Derived* that = dynamic_cast&lt;Derived*&gt;(other);
if (that == NULL)
return false;
...
}
</CODE_SNIPPET>
</p>
</PROS>
<CONS>
A query of type during run-time typically means a
design problem. If you need to know the type of an
object at runtime, that is often an indication that
you should reconsider the design of your class.
</CONS>
<DECISION>
<p>
Do not use RTTI, except in unittests. If you find yourself
in need of writing code that behaves differently based on
the class of an object, consider one of the alternatives to
querying the type.
RTTI has legitimate uses but is prone to abuse, so you must
be careful when using it. You may use it freely
in unittests, but avoid it when possible in other code.
In particular, think twice before using RTTI in new code.
If you find yourself needing to write code that behaves differently
based on the class of an object, consider one of the following
alternatives to querying the type:
<ul>
<li>
Virtual methods are the preferred way of executing different
code paths depending on a specific subclass type. This puts
the work within the object itself.
</li>
<li>
If the work belongs outside the object and instead in some
processing code, consider a double-dispatch solution, such
as the Visitor design pattern. This allows a facility
outside the object itself to determine the type of class
using the built-in type system.
</li>
</ul>
</p>
<p>
Virtual methods are the preferred way of executing different
code paths depending on a specific subclass type. This puts
the work within the object itself.
</p>
<p>
If the work belongs outside the object and instead in some
processing code, consider a double-dispatch solution, such
as the Visitor design pattern. This allows a facility
outside the object itself to determine the type of class
using the built-in type system.
</p>
<p>
If you think you truly cannot use those ideas,
When the logic of a program guarantees that a given instance
of a base class is in fact an instance of a particular derived class,
then a <code>dynamic_cast</code> may be used freely on the object.
you may use RTTI. But think twice
about it. :-) Then think twice again.
Usually one can use a
<code>static_cast</code> as an alternative in such situations.
</p>
<p>
Decision trees based on type are a strong indication that your
code is on the wrong track.
<BAD_CODE_SNIPPET>
if (typeid(*data) == typeid(D1)) {
...
} else if (typeid(*data) == typeid(D2)) {
...
} else if (typeid(*data) == typeid(D3)) {
...
</BAD_CODE_SNIPPET>
Code such as this usually breaks when additional subclasses are
added to the class hierarchy. Moreover, when properties of a subclass
change, it is difficult to find and modify all the affected code segments.
</p>
<p>
Do not hand-implement an RTTI-like workaround. The arguments
against RTTI apply just as much to workarounds like class
hierarchies with type tags.
hierarchies with type tags. Moreover, workarounds disguise your
true intent.
</p>
</DECISION>
</BODY>
@ -1951,13 +2003,11 @@ Tashana Landray
other pointer types. Use this only if you know what you are
doing and you understand the aliasing issues.
</li>
<li> Do not use <code>dynamic_cast</code> except in test code.
If you need to know type information at runtime in this way
outside of a unittest, you probably have a <A HREF="#Run-Time_Type_Information__RTTI_">design
flaw</A>.
</li>
</ul>
<p> See the <a href="#Run-Time_Type_Information__RTTI_">RTTI section</a>
for guidance on the use of <code>dynamic_cast</code>.
</p>
</DECISION>
</BODY>
</STYLEPOINT>
@ -2108,8 +2158,7 @@ Tashana Landray
<STYLEPOINT title="Use of const">
<SUMMARY>
We strongly recommend that you use <code>const</code> whenever
it makes sense to do so.
Use <code>const</code> whenever it makes sense.
</SUMMARY>
<BODY>
<DEFINITION>
@ -2163,13 +2212,6 @@ Tashana Landray
construction.
</li>
</ul>
<p>
However, do not go crazy with <code>const</code>. Something like
<code>const int * const * const x;</code> is likely
overkill, even if it accurately describes how const x is.
Focus on what's really useful to know: in this case,
<code>const int** x</code> is probably sufficient.
</p>
<p>
The <code>mutable</code> keyword is allowed but is unsafe
when used with threads, so thread safety should be carefully
@ -2183,9 +2225,11 @@ Tashana Landray
readable because it's more consistent: it keeps the rule
that <code>const</code> always follows the object it's
describing. However, this consistency argument doesn't
apply in this case, because the "don't go crazy" dictum
eliminates most of the uses you'd have to be consistent with.
apply in codebases with few deeply-nested pointer
expressions since most <code>const</code> expressions have
only one <code>const</code>, and it applies to the
underlying value. In such cases, there's no consistency to
maintain.
Putting the <code>const</code> first is arguably more readable,
since it follows English in putting the "adjective"
(<code>const</code>) before the "noun" (<code>int</code>).
@ -2494,10 +2538,11 @@ Tashana Landray
</BODY>
</STYLEPOINT>
<STYLEPOINT title="0 and NULL">
<STYLEPOINT title="0 and nullptr/NULL">
<SUMMARY>
Use <code>0</code> for integers, <code>0.0</code> for reals,
<code>NULL</code> for pointers, and <code>'\0'</code> for chars.
<code>nullptr</code> (or <code>NULL</code>) for pointers,
and <code>'\0'</code> for chars.
</SUMMARY>
<BODY>
<p>
@ -2505,13 +2550,17 @@ Tashana Landray
This is not controversial.
</p>
<p>
For pointers (address values), there is a choice between <code>0</code>
and <code>NULL</code>. Bjarne Stroustrup prefers an unadorned
<code>0</code>. We prefer <code>NULL</code> because it looks like a
pointer. In fact, some C++ compilers, such as gcc 4.1.0, provide special
definitions of <code>NULL</code> which enable them to give useful
warnings, particularly in situations where <code>sizeof(NULL)</code>
is not equal to <code>sizeof(0)</code>.
and <code>NULL</code> (and, for C++11, <code>nullptr</code>).
For projects that allow C++11 features, use <code>nullptr</code>.
For C++03 projects, we prefer <code>NULL</code> because it looks like a
pointer. In fact, some C++ compilers provide special definitions of
<code>NULL</code> which enable them to give useful warnings,
particularly in situations where <code>sizeof(NULL)</code> is not equal
to <code>sizeof(0)</code>.
</p>
<p>
Use <code>'\0'</code> for chars.
@ -2545,6 +2594,102 @@ Tashana Landray
</BODY>
</STYLEPOINT>
<STYLEPOINT title="auto">
<SUMMARY>
Use <code>auto</code> to avoid type names that are just clutter.
Continue to use manifest type declarations when it helps readability,
and never use <code>auto</code> for anything but local variables.
</SUMMARY>
<BODY>
<DEFINITION>
In C++11, a variable whose type is given as <code>auto</code> will be given
a type that matches that of the expression used to initialize
it. You can use <code>auto</code> either to initialize a
variable by copying, or to bind a reference.
<CODE_SNIPPET>
vector&lt;string&gt; v;
...
auto s1 = v[0]; // Makes a copy of v[0].
const auto&amp; s2 = v[0]; // s2 is a reference to v[0].
</CODE_SNIPPET>
</DEFINITION>
<PROS>
<p>
C++ type names can sometimes be long and cumbersome,
especially when they involve templates or namespaces. In a statement like
<CODE_SNIPPET>
sparse_hash_map&lt;string, int&gt;::iterator iter = m.find(val);
</CODE_SNIPPET>
the return type is hard to read, and obscures the primary
purpose of the statement. Changing it to
<CODE_SNIPPET>
auto iter = m.find(val);
</CODE_SNIPPET>
makes it more readable.
</p>
<p>
Without <code>auto</code> we are sometimes forced to write a
type name twice in the same expression, adding no value
for the reader, as in
<CODE_SNIPPET>
diagnostics::ErrorStatus* status = new diagnostics::ErrorStatus("xyz");
</CODE_SNIPPET>
</p>
<p>
Using <code>auto</code> makes it easier to use intermediate
variables when appropriate, by reducing the burden of writing
their types explicitly.
</p>
</PROS>
<CONS>
<p>Sometimes code is clearer when types are manifest, especially when
a variable's initialization depends on things that were declared
far away. In an expression like
<CODE_SNIPPET>
auto i = x.Lookup(key);
</CODE_SNIPPET>
it may not be obvious what <code>i</code>'s type is, if <code>x</code>
was declared hundreds of lines earlier.
</p>
<p>Programmers have to understand the difference between <code>auto</code>
and <code>const auto&amp;</code> or they'll get copies when
they didn't mean to.
</p>
<p>The interaction between <code>auto</code> and C++11
brace-initialization can be confusing. (C++11 brace-initialization
isn't an approved feature, but this may become relevant when and
if it is permitted.) The declarations
<CODE_SNIPPET>
auto x(3); // Note: parentheses.
auto y{3}; // Note: curly braces.
</CODE_SNIPPET>
mean different things &#8212; <code>x</code> is
an <code>int</code>, while <code>y</code> is
an <code>initializer_list</code>. The same applies to other
normally-invisible proxy types.
</p>
<p>If an <code>auto</code> variable is used as part of an
interface, e.g. as a constant in a header, then a programmer
might change its type while only intending to change its
value, leading to a more radical API change than intended.</p>
</CONS>
<DECISION>
<p><code>auto</code> is permitted, for local variables only.
Do not use <code>auto</code> for file-scope or namespace-scope
variables, or for class members.</p>
<p>The <code>auto</code> keyword is also used in an unrelated
C++11 feature: it's part of the syntax for a new kind of
function declaration with a trailing return type. Function
declarations with trailing return types are not permitted.</p>
</DECISION>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Boost">
<SUMMARY>
Use only approved libraries from the Boost library collection.
@ -2615,11 +2760,15 @@ Tashana Landray
</BODY>
</STYLEPOINT>
<STYLEPOINT title="C++11">
<SUMMARY>
Use only approved libraries and language extensions from C++11 (formerly
known as C++0x).
Currently, none are approved.
Consider portability to other environments before
using C++11 features in your project.
</SUMMARY>
<BODY>
<DEFINITION>
@ -2639,7 +2788,7 @@ Tashana Landray
<p>
The C++11 standard is substantially more complex than its predecessor
(1,300 pages versus 800 pages), and is
unfamilar to many developers. The long-term effects of some
unfamiliar to many developers. The long-term effects of some
features on code readability and maintenance are unknown. We cannot
predict when its various features will be implemented uniformly by
tools that may be of interest (gcc, icc, clang, Eclipse, etc.).
@ -2656,8 +2805,33 @@ Tashana Landray
</CONS>
<DECISION>
Use only C++11 libraries and language features that have been approved
for use. Currently, no such features are approved.
Features will be approved individually as appropriate.
for use.
Currently only the following C++11 features are approved:
<ul>
<li><code>auto</code> (for local variables only).</li>
<li>Use of <code>&gt;&gt;</code> with no intervening space to
close multiple levels of template arguments, as in
<code>set&lt;list&lt;string&gt;&gt;</code>,
where C++03 required a space as in
<code>set&lt;list&lt;string&gt; &gt;</code>.
</li>
<li>Range-based
<code>for</code> loops.</li>
<li>Use of the <code>LL</code> and <code>ULL</code> suffixes on
numeric literals to guarantee that their type is at least 64 bits
wide.</li>
<li>Variadic macros (but note
that use of macros is discouraged).</li>
<li>All of the new STL algorithms in the
<a href="http://en.cppreference.com/w/cpp/algorithm">&lt;algorithm&gt;</a>
and <a href="http://en.cppreference.com/w/cpp/numeric">&lt;numeric&gt;</a>
headers, except for the versions of
<code>min</code>, <code>max</code>, and <code>minmax</code>
whose signatures contain initializer lists.</li>
<li>Use of local types as template parameters.</li>
<li><code>nullptr</code> and <code>nullptr_t</code>.</li>
</ul>
Other features will be approved individually as appropriate.
Avoid writing code that is incompatible with C++11 (even though it
works in C++03).
@ -3097,8 +3271,6 @@ Tashana Landray
one may be you!
</p>
<STYLEPOINT title="Comment Style">
<SUMMARY>
Use either the <code>//</code> or <code>/* */</code> syntax, as long
@ -3115,40 +3287,26 @@ Tashana Landray
<STYLEPOINT title="File Comments">
<SUMMARY>
Start each file with a copyright notice, followed by a
description of the contents of the file.
Start each file with license boilerplate,
followed by a description of its contents.
</SUMMARY>
<BODY>
<SUBSECTION title="Legal Notice and Author Line">
<p>
Every file should contain the following items, in order:
<ul>
<li>a copyright statement (for example,
<code>Copyright 2008 Google Inc.</code>)</li>
<li>a license boilerplate. Choose the appropriate boilerplate
for the license used by the project (for example,
Apache 2.0, BSD, LGPL, GPL)</li>
<li>an author line to identify the original author of the
file</li>
</ul>
Every file should contain license boilerplate.
Choose the appropriate boilerplate for the license used by the project
(for example, Apache 2.0, BSD, LGPL, GPL).
</p>
<p>
If you make significant changes to a file that someone else
originally wrote, add yourself to the author line. This can
be very helpful when another
contributor
has questions about the file and needs to know whom to contact
about it.
If you make significant changes to a file with an author line,
consider deleting the author line.
</p>
</SUBSECTION>
<SUBSECTION title="File Contents">
<p>
Every file should have a comment at the top, below the copyright
notice and author line, that describes the contents of the file.
Every file should have a comment at the top describing its contents.
</p>
<p>
Generally a <code>.h</code> file will describe the classes
@ -3234,7 +3392,7 @@ Tashana Landray
<li> If the function allocates memory that the caller
must free.
</li>
<li> Whether any of the arguments can be <code>NULL</code>.
<li> Whether any of the arguments can be a null pointer.
</li>
<li> If there are any performance implications of how a
function is used.
@ -3318,7 +3476,7 @@ Tashana Landray
Each class data member (also called an instance variable or
member variable) should have a comment describing what it is
used for. If the variable can take sentinel values with
special meanings, such as <code>NULL</code> or -1, document this.
special meanings, such as a null pointer or -1, document this.
For example:
</p>
<CODE_SNIPPET>
@ -3396,9 +3554,9 @@ Tashana Landray
}
</CODE_SNIPPET>
</SUBSECTION>
<SUBSECTION title="NULL, true/false, 1, 2, 3...">
<SUBSECTION title="nullptr/NULL, true/false, 1, 2, 3...">
<p>
When you pass in <code>NULL</code>, boolean, or literal integer
When you pass in a null pointer, boolean, or literal integer
values to functions, you should consider adding a comment about
what they are, or make your code self-documenting by using
constants. For example, compare:
@ -3455,13 +3613,11 @@ Tashana Landray
</SUMMARY>
<BODY>
<p>
Comments should usually be written as complete
sentences with proper capitalization and periods at the end.
Shorter comments, such as comments at the end of a line of
code, can sometimes be less formal, but you should be
consistent with your style. Complete sentences are more
readable, and they provide some assurance that the comment is
complete and not an unfinished thought.
Comments should be as readable as narrative text, with proper
capitalization and punctuation. In many cases, complete sentences are
more readable than sentence fragments. Shorter comments, such as
comments at the end of a line of code, can sometimes be less formal, but
you should be consistent with your style.
</p>
<p>
Although it can be frustrating to have a code reviewer point
@ -3739,23 +3895,6 @@ Tashana Landray
<li> Wrapped parameters have a 4 space indent.
</li>
</ul>
<p>
If your function is <code>const</code>, the <code>const</code>
keyword should be on the same line as the last parameter:
</p>
<CODE_SNIPPET>
// Everything in this function signature fits on a single line
ReturnType FunctionName(Type par) const {
...
}
// This function signature requires multiple lines, but
// the const keyword is on the line with the last parameter.
ReturnType ReallyLongFunctionName(Type par1,
Type par2) const {
...
}
</CODE_SNIPPET>
<p>
If some parameters are unused, comment out the variable name in the
function definition:
@ -4349,6 +4488,9 @@ Tashana Landray
for ( ; i &lt; 5 ; ++i) { // For loops always have a space after the
... // semicolon, and may have a space before the
// semicolon.
for (auto x : counts) { // Range-based for loops always have a
... // space before and after the colon.
}
switch (i) {
case 1: // No space before colon in a switch case.
...
@ -4375,7 +4517,8 @@ Tashana Landray
// &lt;, or between &gt;( in a cast.
vector&lt;char *&gt; x; // Spaces between type and pointer are
// okay, but be consistent.
set&lt;list&lt;string&gt; &gt; x; // C++ requires a space in &gt; &gt;.
set&lt;list&lt;string&gt;&gt; x; // Permitted in C++11 code.
set&lt;list&lt;string&gt; &gt; x; // C++03 required a space in &gt; &gt;.
set&lt; list&lt;string&gt; &gt; x; // You may optionally use
// symmetric spacing in &lt; &lt;.
</CODE_SNIPPET>
@ -4565,7 +4708,7 @@ Tashana Landray
<HR/>
<p align="right">
Revision 3.199
Revision 3.231
</p>

View File

@ -3,7 +3,7 @@
<GUIDE title="Google HTML/CSS Style Guide">
<p class="revision">
Revision 2.2
Revision 2.19
</p>
<OVERVIEW>
@ -13,12 +13,12 @@
This style guide contains many details that are initially
hidden from view. They are marked by the triangle icon, which you
see here on your left. Click it now.
You should see “Hooray” appear below.
You should see &#8220;Hooray&#8221; appear below.
</SUMMARY>
<BODY>
<p>
Hooray! Now you know you can expand points to get more
details. Alternatively, theres a “toggle all” at the
details. Alternatively, there&#8217;s a &#8220;toggle all&#8221; at the
top of this document.
</p>
</BODY>
@ -52,8 +52,8 @@
files are not available over both protocols.
</p>
<p>
Omitting the protocolwhich makes the URL
relativeprevents mixed content issues and results in
Omitting the protocol&#8212;which makes the URL
relative&#8212;prevents mixed content issues and results in
minor file size savings.
</p>
<BAD_CODE_SNIPPET>
@ -88,7 +88,7 @@
</SUMMARY>
<BODY>
<p>
Dont use tabs or mix tabs and spaces for indentation.
Don&#8217;t use tabs or mix tabs and spaces for indentation.
</p>
<CODE_SNIPPET>
&lt;ul&gt;
@ -162,8 +162,8 @@
</p>
<p>
(More on encodings and when and how to specify them can be
found in <a href="http://www.w3.org/International/tutorials/tutorial-char-enc/en/all.html">Character
Sets &amp; Encodings in XHTML, HTML and CSS</a>.)
found in <a href="http://www.w3.org/International/tutorials/tutorial-char-enc/">Handling
character encodings in HTML and CSS</a>.)
</p>
</BODY>
</STYLEPOINT>
@ -181,7 +181,7 @@
(This item is optional as it is not deemed a realistic
expectation to always demand fully documented code. Mileage
may vary heavily for HTML and CSS code and depends on the
projects complexity.)
project&#8217;s complexity.)
</p>
</BODY>
</STYLEPOINT>
@ -230,7 +230,7 @@
<code>&lt;!DOCTYPE html&gt;</code>.
</p>
<p>
(Its recommended to use HTML, as <code>text/html</code>. Do not use
(It&#8217;s recommended to use HTML, as <code>text/html</code>. Do not use
XHTML. XHTML, as <a href="http://hixie.ch/advocacy/xhtml"><code>application/xhtml+xml</code></a>,
lacks both browser and infrastructure support and offers
less room for optimization than HTML.)
@ -252,7 +252,8 @@
</p>
<p>
Use tools such as the <a href="http://validator.w3.org/nu/">W3C
Use tools such as the
<a href="http://validator.w3.org/nu/">W3C
HTML validator</a> to test.
</p>
<p>
@ -280,7 +281,7 @@
</SUMMARY>
<BODY>
<p>
Use elements (sometimes incorrectly called “tags”) for what
Use elements (sometimes incorrectly called &#8220;tags&#8221;) for what
they have been created for. For example, use heading
elements for headings, <code>p</code> elements for
paragraphs, <code>a</code> elements for anchors, etc.
@ -373,9 +374,9 @@
&lt;link rel="stylesheet" href="grid.css" media="screen"&gt;
&lt;link rel="stylesheet" href="print.css" media="print"&gt;
&lt;h1 style="font-size: 1em;"&gt;HTML sucks&lt;/h1&gt;
&lt;p&gt;Ive read about this on a few sites but now Im sure:
&lt;p&gt;I&#8217;ve read about this on a few sites but now I&#8217;m sure:
&lt;u&gt;HTML is stupid!!1&lt;/u&gt;
&lt;center&gt;I cant believe theres no way to control the styling of
&lt;center&gt;I can&#8217;t believe there&#8217;s no way to control the styling of
my website without doing everything all over again!&lt;/center&gt;
</BAD_CODE_SNIPPET>
<CODE_SNIPPET>
@ -384,10 +385,10 @@
&lt;title&gt;My first CSS-only redesign&lt;/title&gt;
&lt;link rel="stylesheet" href="default.css"&gt;
&lt;h1&gt;My first CSS-only redesign&lt;/h1&gt;
&lt;p&gt;Ive read about this on a few sites but today Im actually
&lt;p&gt;I&#8217;ve read about this on a few sites but today I&#8217;m actually
doing it: separating concerns and avoiding anything in the HTML of
my website that is presentational.
&lt;p&gt;Its awesome!
&lt;p&gt;It&#8217;s awesome!
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
@ -406,7 +407,7 @@
<p>
The only exceptions apply to characters with special meaning
in HTML (like <code>&lt;</code> and <code>&amp;</code>) as
well as control or “invisible” characters (like no-break
well as control or &#8220;invisible&#8221; characters (like no-break
spaces).
</p>
<BAD_CODE_SNIPPET>
@ -415,7 +416,7 @@
</BAD_CODE_SNIPPET>
<CODE_SNIPPET>
&lt;!-- Recommended --&gt;
The currency symbol for the Euro is “€”.
The currency symbol for the Euro is &#8220;&#8364;&#8221;.
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
@ -432,9 +433,9 @@
</p>
<p>
(This approach may require a grace period to be established
as a wider guideline as its significantly different
as a wider guideline as it&#8217;s significantly different
from what web developers are typically taught. For
consistency and simplicity reasons its best served
consistency and simplicity reasons it&#8217;s best served
omitting all optional tags, not just a selection.)
</p>
<BAD_CODE_SNIPPET>
@ -516,7 +517,7 @@
</p>
<p>
(If you run into issues around whitespace between list items
its acceptable to put all <code>li</code> elements in one
it&#8217;s acceptable to put all <code>li</code> elements in one
line. A linter is encouraged to throw a warning instead of
an error.)
</p>
@ -548,12 +549,12 @@
</STYLEPOINT>
<STYLEPOINT title="HTML quotation marks">
<SUMMARY>
Use double quotation marks for attribute values where necessary.
When quoting attributes values, use double quotation marks.
</SUMMARY>
<BODY>
<p>
When quoting attribute values, use double (<code>""</code>) rather
than single quotation marks (<code>''</code>).
Use double (<code>""</code>) rather than single quotation marks
(<code>''</code>) around attribute values.
</p>
<BAD_CODE_SNIPPET>
&lt;!-- Not recommended --&gt;
@ -580,8 +581,8 @@
<p>
Use tools such as the
<a href="http://jigsaw.w3.org/css-validator/">W3C CSS validator</a> to
test.
<a href="http://jigsaw.w3.org/css-validator/">W3C
CSS validator</a> to test.
</p>
<p>
Using valid CSS is a measurable baseline quality attribute
@ -608,7 +609,7 @@
<p>
Generic names are simply a fallback for elements that have no
particular or no meaning different from their siblings. They are
typically needed as “helpers.”
typically needed as &#8220;helpers.&#8221;
</p>
<p>
Using functional or generic names reduces the probability of
@ -723,7 +724,7 @@
</STYLEPOINT>
<STYLEPOINT title="0 and units">
<SUMMARY>
Omit unit specification after “0” values.
Omit unit specification after &#8220;0&#8221; values.
</SUMMARY>
<BODY>
<p>
@ -738,7 +739,7 @@
</STYLEPOINT>
<STYLEPOINT title="Leading 0s">
<SUMMARY>
Omit leading “0”s in values.
Omit leading &#8220;0&#8221;s in values.
</SUMMARY>
<BODY>
<p>
@ -804,7 +805,7 @@
in order to improve understanding and scannability.
</p>
<BAD_CODE_SNIPPET>
/* Not recommended: does not separate the words “demo” and “image” */
/* Not recommended: does not separate the words &#8220;demo&#8221; and &#8220;image&#8221; */
.demoimage {}
/* Not recommended: uses underscore instead of hyphen */
@ -819,12 +820,12 @@
</STYLEPOINT>
<STYLEPOINT title="Hacks">
<SUMMARY>
Avoid user agent detection as well as CSS “hacks”—try a different
Avoid user agent detection as well as CSS &#8220;hacks&#8221;&#8212;try a different
approach first.
</SUMMARY>
<BODY>
<p>
Its tempting to address styling differences over user
It&#8217;s tempting to address styling differences over user
agent detection or special CSS filters, workarounds, and
hacks. Both approaches should be considered last resort in
order to achieve and maintain an efficient and manageable
@ -832,7 +833,7 @@
free pass will hurt projects in the long run as projects
tend to take the way of least resistance. That is, allowing
and making it easy to use detection and hacks means using
detection and hacks more frequentlyand more frequently
detection and hacks more frequently&#8212;and more frequently
is too frequently.
</p>
@ -918,7 +919,7 @@
</STYLEPOINT>
<STYLEPOINT title="Property name stops">
<SUMMARY>
Use a space after a property names colon.
Use a space after a property name&#8217;s colon.
</SUMMARY>
<BODY>
<p>
@ -986,14 +987,18 @@
</STYLEPOINT>
<STYLEPOINT title="CSS quotation marks">
<SUMMARY>
Use single quotation marks for attribute selectors and property values
where necessary.
Use single quotation marks for attribute selectors and property values.
</SUMMARY>
<BODY>
<p>
When quoting attribute selectors and property values, use single
(<code>''</code>) rather than double (<code>""</code>) quotation
marks. Do not use quotation marks in URI values (<code>url()</code>).
Use single (<code>''</code>) rather than double (<code>""</code>)
quotation marks for attribute selectors or property values. Do not
use quotation marks in URI values (<code>url()</code>).
</p>
<p>
Exception: If you do need to use the <code>@charset</code> rule,
use double quotation marks&#8212;<a href="http://www.w3.org/TR/CSS21/syndata.html#charset">single
quotation marks are not permitted</a>.
</p>
<BAD_CODE_SNIPPET>
/* Not recommended */
@ -1048,7 +1053,7 @@
<em>Be consistent.</em>
</p>
<p>
If youre editing code, take a few minutes to look at the code
If you&#8217;re editing code, take a few minutes to look at the code
around you and determine its style. If they use spaces around
all their arithmetic operators, you should too. If their
comments have little boxes of hash marks around them, make your
@ -1056,8 +1061,8 @@
</p>
<p>
The point of having style guidelines is to have a common vocabulary
of coding so people can concentrate on what youre saying rather
than on how youre saying it. We present global style rules here so
of coding so people can concentrate on what you&#8217;re saying rather
than on how you&#8217;re saying it. We present global style rules here so
people know the vocabulary, but local style is also important. If
code you add to a file looks drastically different from the existing
code around it, it throws readers out of their rhythm when they go to
@ -1066,7 +1071,7 @@
</PARTING_WORDS>
<p align="right">
Revision 2.2
Revision 2.19
</p>
</GUIDE>

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@
<p align="right">
Revision 2.36
Revision 2.48
</p>
@ -129,13 +129,6 @@ Revision 2.36
</p>
<CODE_SNIPPET>
// Foo.h
// AwesomeProject
//
// Created by Greg Miller on 6/13/08.
// Copyright 2008 Google, Inc. All rights reserved.
//
#import &lt;Foundation/Foundation.h&gt;
// A sample class demonstrating good Objective-C style. All interfaces,
@ -146,8 +139,8 @@ Revision 2.36
// (no blank line between this comment and the interface)
@interface Foo : NSObject {
@private
NSString *bar_;
NSString *bam_;
NSString *_bar;
NSString *_bam;
}
// Returns an autoreleased instance of Foo. See -initWithBar: for details
@ -158,7 +151,7 @@ Revision 2.36
// does a thing.
- (id)initWithBar:(NSString *)bar;
// Gets and sets |bar_|.
// Gets and sets |_bar|.
- (NSString *)bar;
- (void)setBar:(NSString *)bar;
@ -177,14 +170,6 @@ Revision 2.36
</p>
<CODE_SNIPPET>
//
// Foo.m
// AwesomeProject
//
// Created by Greg Miller on 6/13/08.
// Copyright 2008 Google, Inc. All rights reserved.
//
#import "Foo.h"
@ -201,25 +186,25 @@ Revision 2.36
- (id)initWithBar:(NSString *)bar {
if ((self = [super init])) {
bar_ = [bar copy];
bam_ = [[NSString alloc] initWithFormat:@"hi %d", 3];
_bar = [bar copy];
_bam = [[NSString alloc] initWithFormat:@"hi %d", 3];
}
return self;
}
- (void)dealloc {
[bar_ release];
[bam_ release];
[_bar release];
[_bam release];
[super dealloc];
}
- (NSString *)bar {
return bar_;
return _bar;
}
- (void)setBar:(NSString *)bar {
[bar_ autorelease];
bar_ = [bar copy];
[_bar autorelease];
_bar = [bar copy];
}
- (BOOL)doWorkWithBlah:(NSString *)blah {
@ -321,13 +306,13 @@ Revision 2.36
</CODE_SNIPPET>
<p>
When the first keyword is shorter than the others, indent the later
lines by at least four spaces. You can do this by making keywords
line up vertically, not aligning colons:
lines by at least four spaces, maintaining colon alignment:
</p>
<CODE_SNIPPET>
- (void)short:(GTMFoo *)theFoo
longKeyword:(NSRect)theRect
evenLongerKeyword:(float)theInterval {
longKeyword:(NSRect)theRect
evenLongerKeyword:(float)theInterval
error:(NSError **)theError {
...
}
</CODE_SNIPPET>
@ -371,15 +356,15 @@ Revision 2.36
</BAD_CODE_SNIPPET>
<p>
As with declarations and definitions, when the keyword lengths make
it impossible to align colons and still have four leading
spaces, indent later lines by four spaces and align keywords after the
first one, instead of aligning the colons.
As with declarations and definitions, when the first keyword is shorter
than the others, indent the later lines by at least four spaces,
maintaining colon alignment:
</p>
<CODE_SNIPPET>
[myObj short:arg1
longKeyword:arg2
evenLongerKeyword:arg3];
longKeyword:arg2
evenLongerKeyword:arg3
error:arg4];
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
@ -446,7 +431,7 @@ Revision 2.36
<CODE_SNIPPET>
@interface MyProtocoledClass : NSObject&lt;NSWindowDelegate&gt; {
@private
id&lt;MyFancyDelegate&gt; delegate_;
id&lt;MyFancyDelegate&gt; _delegate;
}
- (void)setDelegate:(id&lt;MyFancyDelegate&gt;)aDelegate;
@end
@ -500,7 +485,7 @@ Revision 2.36
// Using a block with a C API follows the same alignment and spacing
// rules as with Objective-C.
dispatch_async(fileIOQueue_, ^{
dispatch_async(_fileIOQueue, ^{
NSString* path = [self sessionFilePath];
if (path) {
// ...
@ -535,7 +520,7 @@ Revision 2.36
void (^largeBlock)(void) = ^{
// ...
};
[operationQueue_ addOperationWithBlock:largeBlock];
[_operationQueue addOperationWithBlock:largeBlock];
</CODE_SNIPPET>
</BODY>
</STYLEPOINT>
@ -579,7 +564,7 @@ Revision 2.36
<STYLEPOINT title="File Names">
<SUMMARY>
File names should reflect the name of the class implementation that
they contain -- including case. Follow the convention that your
they contain&#8212;including case. Follow the convention that your
project
uses.
@ -648,16 +633,16 @@ Revision 2.36
// A typical Objective-C class, using Objective-C naming.
@interface MyDelegate : NSObject {
@private
int instanceVar_;
CrossPlatformAPI* backEndObject_;
int _instanceVar;
CrossPlatformAPI* _backEndObject;
}
- (void)respondToSomething:(id)something;
@end
@implementation MyDelegate
- (void)respondToSomething:(id)something {
// bridge from Cocoa through our C++ backend
instanceVar_ = backEndObject-&gt;DoSomethingPlatformSpecific();
NSString* tempString = [NSString stringWithInt:instanceVar_];
_instanceVar = _backEndObject-&gt;DoSomethingPlatformSpecific();
NSString* tempString = [NSString stringWithInt:_instanceVar];
NSLog(@"%@", tempString);
}
@end
@ -752,11 +737,8 @@ Revision 2.36
<STYLEPOINT title="Variable Names">
<SUMMARY>
Variables names start with a lowercase and use mixed case to delimit
words. Class member variables have trailing underscores. For example:
<var>myLocalVariable</var>, <var>myInstanceVariable_</var>. Members
used for KVO/KVC bindings may begin with a leading underscore
<i>iff</i> use of Objective-C 2.0's <code>@property</code> isn't
allowed.
words. Instance variables have leading underscores. For example:
<var>myLocalVariable</var>, <var>_myInstanceVariable</var>.
</SUMMARY>
<BODY>
<SUBSECTION title="Common Variable Names">
@ -786,15 +768,13 @@ Revision 2.36
<SUBSECTION title="Instance Variables">
<p>
Instance variables are mixed case and should be suffixed with a
trailing underscore, e.g. <var>usernameTextField_</var>. However,
we permit an exception when binding to a member variable using
KVO/KVC and Objective-C 2.0 cannot be used (due to OS release
constraints). In this case, it is acceptable to prefix the variable
with an underscore, per Apple's accepted practices for key/value
naming. If Objective-C 2.0 can be used, <code>@property</code> and
<code>@synthesize</code> provide a solution that conforms to the
naming guidelines.
Instance variables are mixed case and should be prefixed with an
underscore e.g. <var>_usernameTextField</var>. Note that historically
the convention was to put the underscore at the end of the name, and
projects may opt to continue using trailing underscores in new code
in order to maintain consistency within their codebase (see the
Historical Notes section). It is recommended you leave old
code as-is, unless doing so would create inconsistency within a class.
</p>
</SUBSECTION>
@ -825,7 +805,7 @@ Revision 2.36
When writing your comments, write for your audience: the next
contributor
who will need to understand your code. Be generous &#8212; the next
who will need to understand your code. Be generous&#8212;the next
one may be you!
</p>
<p>
@ -835,36 +815,24 @@ Revision 2.36
<STYLEPOINT title="File Comments">
<SUMMARY>
Start each file with a basic description of the contents of the file,
followed by an author, and then followed by a copyright notice and/or
license boilerplate.
A file may optionally start with a description of its contents.
</SUMMARY>
<BODY>
<SUBSECTION title="Legal Notice and Author Line">
<p>
Every file should contain the following items, in order:
<ul>
<li>a basic description of the contents of the file</li>
<li>an author line</li>
<li>a copyright statement (for example,
<code>Copyright 2008 Google Inc.</code>)</li>
<li>license boilerplate if neccessary. Choose the appropriate
boilerplate for the license used by the project (e.g.
Apache 2.0, BSD, LGPL, GPL)</li>
</ul>
</p>
<p>
If you make significant changes to a file that someone else
originally wrote, add yourself to the author line. This can
be very helpful when another
contributor
has questions about the file and needs to know whom to contact
about it.
</p>
</SUBSECTION>
<p>
Every file should contain the following items, in order:
<ul>
<li>license boilerplate if neccessary. Choose the appropriate
boilerplate for the license used by the project (e.g.
Apache 2.0, BSD, LGPL, GPL).</li>
<li>a basic description of the contents of the file if necessary.</li>
</ul>
</p>
<p>
If you make significant changes to a file with an author line,
consider deleting the author line since revision history already
provides a more detailed and accurate record of authorship.
</p>
</BODY>
</STYLEPOINT>
@ -932,48 +900,57 @@ Revision 2.36
outside the most common Objective-C usage idioms.
</SUMMARY>
<BODY>
<p>
Instance variables which are pointers to objects derived from NSObject
are presumed to be retained, and should be either commented as weak or
declared with the <b>__weak</b> lifetime qualifier when applicable.
Similarly, declared properties must specify a <b>weak</b> or
<b>assign</b> property attribute if they are not retained by the
class. An exception is instance variables labeled as IBOutlets in Mac
software, which are presumed to not be retained.
</p>
<p>
Where instance variables are pointers to CoreFoundation, C++, and
other non-Objective-C objects, they should always be declared with
the __strong and __weak type modifiers to indicate which pointers are
and are not retained. CoreFoundation and other non-Objective-C object
pointers require explicit memory management, even when building for
automatic reference counting or garbage collection. When the __weak
type modifier is not allowed (e.g. C++ member variables when compiled
under clang), a comment should be used instead.
</p>
<p>
Be mindful that support for automatic C++ objects encapsulated in
Objective-C objects is disabled by default, as described <a href="http://chanson.livejournal.com/154253.html">here</a>.
</p>
<p>
Examples of strong and weak declarations:
<CODE_SNIPPET>
@interface MyDelegate : NSObject {
@private
IBOutlet NSButton *okButton_; // normal NSControl; implicitly weak on Mac only
<SUBSECTION title="Manual Reference Counting">
<p>
Instance variables which are pointers to objects derived from NSObject
are presumed to be retained, and should be either commented as weak or
declared with the <b>__weak</b> lifetime qualifier when applicable.
Similarly, declared properties must specify an <b>assign</b> property
attribute if they are not retained by the class. An exception is
instance variables labeled as IBOutlets in desktop Mac software,
which are presumed to not be retained.
</p>
<p>
Where instance variables are pointers to Core Foundation, C++, and
other non-Objective-C objects, they should always be declared with
the __strong or __weak type modifiers to indicate which pointers are
and are not retained. Core Foundation and other non-Objective-C object
pointers require explicit memory management, even when building for
automatic reference counting or garbage collection. When the __weak
type modifier is not allowed (e.g. C++ member variables when compiled
under clang), a comment should be used instead.
</p>
<p>
Be mindful that support for automatic C++ objects encapsulated in
Objective-C objects is disabled by default, as described <a href="http://chanson.livejournal.com/154253.html">
here</a>.
</p>
<p>
Examples of strong and weak declarations:
<CODE_SNIPPET>
@interface MyDelegate : NSObject {
@private
IBOutlet NSButton *_okButton; // normal NSControl; implicitly weak on Mac only
AnObjcObject* doohickey_; // my doohickey
__weak MyObjcParent *parent_; // so we can send msgs back (owns me)
AnObjcObject* _doohickey; // my doohickey
__weak MyObjcParent *_parent; // so we can send msgs back (owns me)
// non-NSObject pointers...
__strong CWackyCPPClass *wacky_; // some cross-platform object
__strong CFDictionaryRef *dict_;
}
@property(strong, nonatomic) NSString *doohickey;
@property(weak, nonatomic) NSString *parent;
@end
</CODE_SNIPPET>
</p>
// non-NSObject pointers...
__strong CWackyCPPClass *_wacky; // some cross-platform object
__strong CFDictionaryRef *_dict;
}
@property(strong, nonatomic) NSString *doohickey;
@property(weak, nonatomic) NSString *parent;
@end
</CODE_SNIPPET>
</p>
</SUBSECTION>
<SUBSECTION title="Automatic Reference Counting">
<p>
Object ownership and lifetime are explicit when using ARC, so no
additional comments are required.
</p>
</SUBSECTION>
</BODY>
</STYLEPOINT>
@ -981,15 +958,16 @@ Revision 2.36
<CATEGORY title="Cocoa and Objective-C Features">
<STYLEPOINT title="Member Variables Should Be @private">
<STYLEPOINT title="Instance Variables In Headers Should Be @private">
<SUMMARY>
Member variables should be declared <code>@private</code>.
Instance variables should be marked <code>@private</code> when they are
declared in a header file.
</SUMMARY>
<BODY>
<CODE_SNIPPET>
@interface MyClass : NSObject {
@private
id myInstanceVariable_;
id _myInstanceVariable;
}
// public accessors, setter takes ownership
- (id)myInstanceVariable;
@ -1083,7 +1061,7 @@ Revision 2.36
<BODY>
<p>
Unlike C++, Objective-C doesn't have a way to differentiate between
public and private methods &#8212; everything is public. As a result,
public and private methods&#8212;everything is public. As a result,
avoid placing methods in the public API unless they are actually
expected to be used by a consumer of the class. This helps reduce the
likelihood they'll be called when you're not expecting it. This includes
@ -1092,7 +1070,6 @@ Revision 2.36
file as opposed to adding them to the public header.
</p>
<CODE_SNIPPET>
// GTMFoo.m
#import "GTMFoo.h"
@interface GTMFoo (PrivateDelegateHandling)
@ -1263,8 +1240,8 @@ Revision 2.36
</p>
<CODE_SNIPPET>
- (void)setFoo:(GMFoo *)aFoo {
[foo_ autorelease]; // Won't dealloc if |foo_| == |aFoo|
foo_ = [aFoo retain];
[_foo autorelease]; // Won't dealloc if |_foo| == |aFoo|
_foo = [aFoo retain];
}
</CODE_SNIPPET>
</BODY>
@ -1288,13 +1265,13 @@ Revision 2.36
- (id)init {
self = [super init];
if (self) {
bar_ = [[NSMutableString alloc] init]; // good
_bar = [[NSMutableString alloc] init]; // good
}
return self;
}
- (void)dealloc {
[bar_ release]; // good
[_bar release]; // good
[super dealloc];
}
</CODE_SNIPPET>
@ -1352,8 +1329,8 @@ Revision 2.36
</p>
<CODE_SNIPPET>
- (void)setFoo:(NSString *)aFoo {
[foo_ autorelease];
foo_ = [aFoo copy];
[_foo autorelease];
_foo = [aFoo copy];
}
</CODE_SNIPPET>
</BODY>
@ -1444,7 +1421,7 @@ Revision 2.36
handled by the Objective-C runtime. If the method has no return
result, you're good to go. However if there is one, there may be
differences based on runtime architecture, return size, and OS X
version (see <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_2_section_3.html#//apple_ref/doc/uid/TP30001163-CH11-SW7">Apple's
version (see <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-SW7">Apple's
documentation</a> for specifics).
</p>
<p>
@ -1463,16 +1440,16 @@ Revision 2.36
</SUMMARY>
<BODY>
<p>
<code>BOOL</code> is defined as an unsigned char in Objective-C which
means that it can have values other than <code>YES</code> (1) and
<code>BOOL</code> is defined as a signed char in Objective-C which means
that it can have values other than <code>YES</code> (1) and
<code>NO</code> (0). Do not cast or convert general integral values
directly to <code>BOOL</code>. Common mistakes include casting or
converting an array's size, a pointer value, or the result of a bitwise
logic operation to a <code>BOOL</code> which, depending on the value of
the last byte of the integral result, could still result in a
<code>NO</code> value. When converting a general integral value to a
<code>BOOL</code> use ternery operators to return a <code>YES</code>
or <code>NO</code> value.
<code>BOOL</code> use ternery operators to return a <code>YES</code> or
<code>NO</code> value.
</p>
<p>
You can safely interchange and convert <code>BOOL</code>,
@ -1529,58 +1506,54 @@ Revision 2.36
<STYLEPOINT title="Properties">
<SUMMARY>
Properties in general are allowed with the following caveat: properties
are an Objective-C 2.0 feature which will limit your code to running
on the iPhone and Mac OS X 10.5 (Leopard) and higher. Dot notation
Use of the @property directive is preferred, with the following caveat:
properties are an Objective-C 2.0 feature which will limit your code to
running on the iPhone and Mac OS X 10.5 (Leopard) and higher. Dot notation
is allowed only for access to a declared <code>@property</code>.
</SUMMARY>
<BODY>
<SUBSECTION title="Naming">
<p>
A property's associated instance variable's name must conform to the
trailing _ requirement. The property's name should be the same as its
associated instance variable without the trailing _. The optional
space between the <code>@property</code> and the opening parenthesis
leading _ requirement. The property's name should be the same as its
associated instance variable without the leading _. The optional space
between the <code>@property</code> and the opening parenthesis
should be omitted, as seen in the examples.
</p>
<p>
Use the @synthesize directive to rename the property correctly.
</p>
<CODE_SNIPPET>
@interface MyClass : NSObject {
@private
NSString *name_;
}
@interface MyClass : NSObject
@property(copy, nonatomic) NSString *name;
@end
@implementation MyClass
@synthesize name = name_;
// No code required for auto-synthesis, else use:
// @synthesize name = _name;
@end
</CODE_SNIPPET>
</SUBSECTION>
<SUBSECTION title="Location">
<p>
A property's declaration must come immediately after the instance
variable block of a class interface. A property's definition must
come immediately after the <code>@implementation</code> block in a
class definition. They are indented at the same level as the
<code>@interface</code> or <code>@implementation</code> statements
that they are enclosed in.
variable block of a class interface. A property's definition (if
not using automatic synthesis) must come immediately after the
<code>@implementation</code> block in a class definition. They are
indented at the same level as the <code>@interface</code> or
<code>@implementation</code> statements that they are enclosed in.
</p>
<CODE_SNIPPET>
@interface MyClass : NSObject {
@private
NSString *name_;
NSString *_name;
}
@property(copy, nonatomic) NSString *name;
@end
@implementation MyClass
@synthesize name = name_;
@synthesize name = _name;
- (id)init {
...
...
}
@end
</CODE_SNIPPET>
@ -1649,19 +1622,20 @@ Revision 2.36
<STYLEPOINT title="Automatically Synthesized Instance Variables">
<SUMMARY>
<p>
For code that will run on iOS only, use of automatically synthesized
instance variables is preferred.
</p>
<p>
When synthesizing the instance variable, use
<code>@synthesize var = var_;</code> as this prevents accidentally calling
<code>var = blah;</code> when <code>self.var = blah;</code> is intended.
Use of automatically synthesized instance variables is preferred. Code
that must support earlier versions of the compiler toolchain (Xcode 4.3
or earlier or when compiling with GCC) or is using properties inherited
from a protocol should prefer the @synthesize directive.
</p>
</SUMMARY>
<BODY>
<CODE_SNIPPET>
// Header file
@interface Foo : NSObject
@protocol Thingy
@property(nonatomic, copy) NSString *widgetName;
@end
@interface Foo : NSObject&lt;Thingy&gt;
// A guy walks into a bar.
@property(nonatomic, copy) NSString *bar;
@end
@ -1672,10 +1646,89 @@ Revision 2.36
@end
@implementation Foo
@synthesize bar = bar_;
@synthesize baz = baz_;
@synthesize widgetName = _widgetName;
@end
</CODE_SNIPPET>
<p>
Automatically synthesized instance variables take the form of the
property's name prefixed with an underscore and so typically conform to
the required variable naming style. If your property name is unusual,
or you are otherwise unable to use automatically synthesized instance
variables, use of the @synthesize directive is preferred, with the
instance variable name specified explicitly (as @synthesize does not add
a leading underscore by default).
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Automatic Reference Counting (ARC)">
<SUMMARY>
<p>
For projects that use Xcode 4.2 or later and will run only on 64-bit
Mac OS X 10.7 and iOS 5.0 and later, ARC is preferred. Use manual
reference counting when supporting earlier environments where zeroing
weak pointers are not available.
</p>
<p>
Classes that require ARC should include a preprocessor directive to
prevent compilation using manual reference counting.
</p>
<p>
Ownership qualifiers like <code>__unsafe_unretained</code> and
<code>__weak</code> should precede variable names. Specifying
<code>__strong</code> for variables is not required since it is
the default. Properties, on the other hand, should always specify the
<code>strong</code> keyword rather than relying on the compiler default.
</p>
</SUMMARY>
<BODY>
<p>
Example of an implementation file enforcing ARC style. Note that
declaring instance variables in the @implementation is permitted when
using ARC.
<CODE_SNIPPET>
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
#import "Foo.h"
@implementation Foo {
@private
Bar * __weak _bar;
Baz * __unsafe_unretained _baz;
}
// ...
@end
</CODE_SNIPPET>
</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="NSNumber Literals">
<SUMMARY>
<p>
For projects that use Xcode 4.4 or later with clang, the use of
<a href="http://clang.llvm.org/docs/ObjectiveCLiterals.html">NSNumber literals</a>
is allowed. Note however that this will limit the portability of your
code to other toolchains.
</p>
</SUMMARY>
<BODY>
<p>
NSNumber literals are used just like Objective C string literals.
Boxing is used when necessary. Code using NSNumber literals can be
deployed on any iOS/MacOS system.
<CODE_SNIPPET>
NSNumber *fortyTwo = @42;
NSNumber *piOverTwo = @(M_PI / 2);
enum {
kMyEnum = 2;
};
NSNumber *myEnum = @(kMyEnum);
</CODE_SNIPPET>
</p>
</BODY>
</STYLEPOINT>
</CATEGORY>
@ -1692,7 +1745,7 @@ Revision 2.36
A class that implements the delegate pattern should:
<ol>
<li>
Have an instance variable named <var>delegate_</var> to reference
Have an instance variable named <var>_delegate</var> to reference
the delegate.
</li>
<li>
@ -1700,7 +1753,7 @@ Revision 2.36
and <code>setDelegate:</code>.
</li>
<li>
The <var>delegate_</var> object should <b>not</b> be retained.
The <var>_delegate</var> object should <b>not</b> be retained.
</li>
</ol>
</p>
@ -1743,10 +1796,33 @@ Revision 2.36
</CATEGORY>
<CATEGORY title="Historical Notes">
<STYLEPOINT title="Trailing vs Leading Underscores">
<SUMMARY>
Trailing underscores were once preferred for instance variable names.
</SUMMARY>
<BODY>
<p>
Our style guide used to have a rule saying that instance variables
should be named with a trailing underscore, similar to the naming of
member variables in C++. This was changed to leading underscores to
be consistent with the broader Objective-C community, to better follow
Apple's official guidelines, and to allow for use of new compiler
features like automatic instance variable synthesis. New projects are
strongly encouraged to use leading underscores. Existing projects may
continue to use trailing underscores in new code to maintain
consistency with the rest of their codebase.
</p>
</BODY>
</STYLEPOINT>
</CATEGORY>
<HR/>
<p align="right">
Revision 2.36
Revision 2.48
</p>

View File

@ -95,11 +95,11 @@
var matched = id && EndsWith(id, suffix);
if (matched) {
var len = id.length - suffix.length;
ShowByName(matched.substring(0, len));
ShowByName(id.substring(0, len));
if (anchor.scrollIntoView) {
anchor.scrollIntoView();
}
return;
}
node = node.parentNode;
@ -136,7 +136,7 @@
<H1>Google Python Style Guide</H1>
<p align="right">
Revision 2.39
Revision 2.45
</p>
<address>
@ -424,8 +424,9 @@ from sound.effects import echo
unless you are re-raising the exception or in the outermost
block in your thread (and printing an error message). Python
is very tolerant in this regard and <code>except:</code> will
really catch everything including Python syntax errors. It is
easy to hide real bugs using <code>except:</code>.</li>
really catch everything including misspelled names, sys.exit()
calls, Ctrl+C interrupts, unittest failures and all kinds of
other exceptions that you simply don't want to catch.</li>
<li>Minimize the amount of code in a
<code>try</code>/<code>except</code> block. The larger the
body of the <code>try</code>, the more likely that an
@ -988,8 +989,10 @@ from sound.effects import echo
Use string methods instead of the <code>string</code> module
where possible. Use function call syntax instead
of <code>apply</code>. Use list comprehensions
and <code>for</code> loops instead of <code>filter</code>,
<code>map</code>, and <code>reduce</code>.
and <code>for</code> loops instead of <code>filter</code> and
<code>map</code> when the function argument would have been an
inlined lambda anyway. Use <code>for</code> loops instead of
<code>reduce</code>.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Deprecated_Language_Features__body" id="Deprecated_Language_Features__body" style="display: none">
<P class="">
@ -1006,6 +1009,8 @@ from sound.effects import echo
<span class="external"></span>[x[1] for x in my_list if x[2] == 5]
<span class="external"></span>map(math.sqrt, data) # Ok. No inlined lambda expression.
<span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
@ -1279,7 +1284,7 @@ from sound.effects import echo
<p>
Make note of the indentation of the elements in the line
continuation examples above; see the
<a HREF="#indentation">indentation</a>
<a HREF="#Indentation">indentation</a>
section for explanation.
</p>
</DIV></DIV>
@ -1458,7 +1463,7 @@ from sound.effects import echo
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Shebang_Line')" name="Shebang_Line__button" id="Shebang_Line__button"></SPAN>
<DIV style="display:inline;" class="">
Most <code>.py</code> files do not need to start with a
<code>#!</code> line. Start the main file of a binary with
<code>#!</code> line. Start the main file of a program with
<code>#!/usr/bin/python</code>.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Shebang_Line__body" id="Shebang_Line__body" style="display: none">
@ -2218,7 +2223,7 @@ Don'<span class="external"></span>t do this.
<p align="right">
Revision 2.39
Revision 2.45
</p>

View File

@ -119,11 +119,11 @@ xmlns:fn="http://www.w3.org/2005/xpath-functions">
var matched = id &amp;&amp; EndsWith(id, suffix);
if (matched) {
var len = id.length - suffix.length;
ShowByName(matched.substring(0, len));
ShowByName(id.substring(0, len));
if (anchor.scrollIntoView) {
anchor.scrollIntoView();
}
return;
}
node = node.parentNode;