From e33361fcd369c2009d7db0e30413c3ee5f50f4ce Mon Sep 17 00:00:00 2001 From: "mark@chromium.org" Date: Fri, 4 Nov 2011 16:55:22 +0000 Subject: [PATCH] Update C++ style guide to 3.199: - Update an example to omit the blank line between C and C++ #includes. - Rewrite the paragraph about #include ordering. - Clarify namespace closing comments. - Discourage const references for input arguments which are aliased beyond the scope of the function call. - Replace all '&' with '&'. - Clarify that interfaces must have virtual destructors. - Add an explicit example for |else if|. - C++11 updates. Update Objective-C style guide to 2.36: - Remove requirement to list @dynamic implementations. - Remove requirement to never synthesize CFType properties, since they may be retained on 10.6. - Use __weak and __strong type declaration modifiers rather than comments. - Make the copyright/license information consistent. - An example initializer comment revealed too much about the implementation. - Correct spelling mistakes. - Fix names that didn't follow Cocoa conventions. - Fix examples to conform to style. - Add a section about no braces for empty interfaces. - Add a section about automatically synthesized instance variables. - Codify avoidance of accessors in -init and -dealloc methods. - Changes for the 80-column rule. - Weaken the language around object ownership type qualifiers. - Document the rules for formatting blocks. Update JavaScript style guide to 2.27: - Introduce EcmaScript 5 Strict verbiage. - Add a note about private constructors. - Simplify explanations about JSDoc comments. - Sort the JSDoc tags. - Remove the sections about type-checking now that the JSDoc tags and JS types are no longer one table. - Convert to , because the XSL processor eats . - Add @suppress. - Mark @inheritDoc deprecated in favor of @override. - Add a section about inner classes and enums being defined in the same file as the top-level class they are defined on. Update Python style guide to 2.28: - Change "Naming" summary to match body. - Make the prohibition against backslash line continuation explicit. - Update the TODO section to match the C++ style guide. - Declare Python code without a shebang line to be stylish. - Clarify rules on function docstrings. - Fix spelling errors. - Update with styleguide.xsl 1.33. Update styleguide.xsl to 1.33: - Clean up style guide JS. - Links to anchor tags auto-expand. --- cppguide.xml | 83 ++- javascriptguide.xml | 1649 +++++++++++++++++++++---------------------- objcguide.xml | 435 ++++++++---- pyguide.html | 357 ++++++---- styleguide.xsl | 120 ++-- 5 files changed, 1432 insertions(+), 1212 deletions(-) diff --git a/cppguide.xml b/cppguide.xml index a3e45c2..480876c 100644 --- a/cppguide.xml +++ b/cppguide.xml @@ -4,7 +4,7 @@

-Revision 3.188 +Revision 3.199

@@ -209,7 +209,6 @@ Tashana Landray definitions of the classes they use, and usually have to include several header files.

- If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, @@ -383,11 +382,13 @@ Tashana Landray .h files.

- The preferred ordering reduces hidden dependencies. We want - every header file to be compilable on its own. The easiest - way to achieve this is to make sure that every one of them is - the first .h file #included in some - .cc. + With the preferred ordering, if dir/foo2.h + omits any necessary includes, the build of + dir/foo.cc or + dir/foo_test.cc will break. + Thus, this rule ensures that build breaks show up first + for the people working on these files, not for innocent people + in other packages.

dir/foo.cc and @@ -412,7 +413,6 @@ Tashana Landray #include <sys/types.h> #include <unistd.h> - #include <hash_map> #include <vector> @@ -468,6 +468,7 @@ Tashana Landray

Use namespaces according to the policy described below. + Terminate namespaces with comments as shown in the given examples.

@@ -490,9 +491,7 @@ Tashana Landray associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of - an unnamed namespace. Terminate the unnamed - namespace as shown, with a comment // - namespace. + an unnamed namespace.

  • Do not use unnamed namespaces in .h @@ -1239,7 +1238,7 @@ Tashana Landray An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed - correctly, they must also declare a virtual destructor (in + correctly, the interface must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details. @@ -1574,14 +1573,24 @@ Tashana Landray non-const reference parameters.

    - One case when you might want an input parameter to be a - const pointer is if you want to emphasize that the - argument is not copied, so it must exist for the lifetime of the - object; it is usually best to document this in comments as - well. STL adapters such as bind2nd and - mem_fun do not permit reference parameters, so - you must declare functions with pointer parameters in these - cases, too. + + However, there are some instances where using const T* + is preferable to const T& for input parameters. For + example: + + You want to pass in NULL. + + The function saves a pointer or reference to the input. + + + Remember that most of the time input parameters are going to be + specified as const T&. Using const T* + instead communicates to the reader that the input is somehow treated + differently. So if you choose const T* rather than + const T&, do so for a concrete reason; otherwise it + will likely confuse readers by making them look for an explanation + that doesn't exist. +

    @@ -2606,28 +2615,29 @@ Tashana Landray - + - Use only approved libraries and language extensions from C++0x. + Use only approved libraries and language extensions from C++11 (formerly + known as C++0x). Currently, none are approved. - C++0x is the next ISO C++ standard, currently in - final - committee draft form. It contains - significant + C++11 is the latest ISO C++ standard. + It contains + significant changes both to the language and libraries. + - We expect that C++0x will become the next standard, and eventually will + C++11 has become the official standard, and eventually will be supported by most C++ compilers. It standardizes some common C++ extensions that we use already, allows shorthands for some operations, - and has some safety improvements. + and has some performance and safety improvements.

    - The C++0x standard is substantialy more complex than its predecessor + 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 features on code readability and maintenance are unknown. We cannot @@ -2635,7 +2645,7 @@ Tashana Landray tools that may be of interest (gcc, icc, clang, Eclipse, etc.).

    - As with Boost, some C++0x extensions encourage + As with Boost, some C++11 extensions encourage coding practices that hamper readability—for example by removing checked redundancy (such as type names) that may be helpful to readers, or by encouraging template metaprogramming. Other extensions @@ -2645,9 +2655,12 @@ Tashana Landray

    - Use only C++0x libraries and language features that have been approved + 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. + Avoid writing code that is incompatible with C++11 (even though it + works in C++03). +
    @@ -3845,7 +3858,9 @@ Tashana Landray if (condition) { // no spaces inside parentheses ... // 2 space indent. - } else { // The else goes on the same line as the closing brace. + } else if (...) { // The else goes on the same line as the closing brace. + ... + } else { ... } @@ -4069,7 +4084,7 @@ Tashana Landray the && logical AND operators are at the end of the line. This is more common in Google code, though wrapping all operators at the beginning of the line is also - allowed. Feel free to insert extra parentheses judiciously, + allowed. Feel free to insert extra parentheses judiciously because they can be very helpful in increasing readability when used appropriately. Also note that you should always use the punctuation operators, such as && and @@ -4550,7 +4565,7 @@ Tashana Landray

    -Revision 3.188 +Revision 3.199

    diff --git a/javascriptguide.xml b/javascriptguide.xml index 61e0a24..0816973 100644 --- a/javascriptguide.xml +++ b/javascriptguide.xml @@ -3,7 +3,7 @@

    - Revision 2.20 + Revision 2.27

    @@ -49,6 +49,8 @@ + + Declarations with var: Always @@ -637,11 +639,25 @@ -

    Getters and setters for properties are not required. However, if - they are used, then getters must be named getFoo() and - setters must be named setFoo(value). (For boolean - getters, isFoo() is also acceptable, and often sounds - more natural.)

    +

    EcmaScript 5 getters and setters for properties are discouraged. + However, if they are used, then getters must not change observable + state.

    + + /** + * WRONG -- Do NOT do this. + */ + var foo = { get next() { return this.nextId++; } }; + }; + +
    + + +

    Getters and setters methods for properties are not required. + However, if they are used, then getters must be named + getFoo() and setters must be named + setFoo(value). (For boolean getters, + isFoo() is also acceptable, and often sounds more + natural.)

    @@ -1182,6 +1198,12 @@ return this.protectedProp; }; + +

    Notice that in JavaScript, there is no distinction between a type + (like AA_PrivateClass_) and the constructor for that + type. There is no way to express both that a type is public and its + constructor is private (because the constructor could easily be aliased + in a way that would defeat the privacy check).

    @@ -1203,6 +1225,7 @@ compiler still supports old syntaxes for types, but those syntaxes are deprecated.

    +

    @@ -1674,7 +1697,7 @@ - +
    SomeClassSomeClass /** @constructor */ @@ -1759,6 +1782,19 @@
    + +

    In cases where type-checking doesn't accurately infer the type of + an expression, it is possible to add a type cast comment by adding a + type annotation comment and enclosing the expression in + parentheses. The parentheses are required, and may surround the type + annotation comment as well.

    + + + /** @type {number} */ (x) + (/** @type {number} */ x) + +
    +

    Because JavaScript is a loosely-typed language, it is very @@ -1861,46 +1897,179 @@ }; + + + +

    Sometimes types can get complicated. A function that accepts + content for an Element might look like:

    + + + /** + * @param {string} tagName + * @param {(string|Element|Text|Array.<Element>|Array.<Text>)} contents + * @return {!Element} + */ + goog.createElement = function(tagName, contents) { + ... + }; + + +

    You can define commonly used type expressions with a + @typedef tag. For example,

    + + + /** @typedef {(string|Element|Text|Array.<Element>|Array.<Text>)} */ + goog.ElementContent; + + /** + * @param {string} tagName + * @param {goog.ElementContent} contents + * @return {!Element} + */ + goog.createElement = function(tagName, contents) { + ... + }; + +
    + + + +

    The compiler has limited support for template types. It can only + infer the type of this inside an anonymous function + literal from the type of the this argument and whether the + this argument is missing.

    + + + /** + * @param {function(this:T, ...)} fn + * @param {T} thisObj + * @param {...*} var_args + * @template T + */ + goog.bind = function(fn, thisObj, var_args) { + ... + }; + // Possibly generates a missing property warning. + goog.bind(function() { this.someProperty; }, new SomeClass()); + // Generates an undefined this warning. + goog.bind(function() { this.someProperty; }); + + Use JSDoc -

    We use - - JSDoc - - comments to document files, classes, methods and properties. Inline - comments should be of the // variety. Additionally, we follow the +

    + We follow the C++ style for comments - in spirit. This means you should have: + in spirit.

    -
      -
    • copyright and authorship notice,
    • -
    • a top-level (file-level) comment designed to orient readers - unfamiliar with the code to what's in this file (e.g., a - one-paragraph summary of what the major pieces are, how they fit - together, and with what they interact),
    • -
    • class, function, variable, and implementation comments as - necessary,
    • -
    • an indication of the browsers in which the code is expected to - work (if applicable), and
    • -
    • proper capitalization, punctuation, and spelling.
    • -
    -

    Avoid sentence fragments. Start sentences with a properly - capitalized word, and end them with punctuation.

    +

    All files, classes, methods and properties should be documented with + JSDoc + comments.

    -

    Pretend there's some novice programmer that's going to come along and - have to maintain the code after you. There very well just might - be!

    +

    Inline comments should be of the // variety.

    -

    There are now many compiler passes that extract type information from - JSDoc, in order to provide better code validation, removal, and - compression. It is, therefore, very important that you use full and - correct JSDoc.

    +

    Avoid sentence fragments. Start sentences with a properly + capitalized word, and end them with punctuation.

    + + +

    The JSDoc syntax is based on + + JavaDoc + . Many tools extract metadata from JSDoc comments to perform + code validation and optimizations. These comments must be + well-formed.

    + + + /** + * A JSDoc comment should begin with a slash and 2 asterisks. + * Inline tags should be enclosed in braces like {@code this}. + * @desc Block tags should always start on their own line. + */ + +
    + + +

    If you have to line break a block tag, you should treat this as + breaking a code statement and indent it four spaces.

    + + + /** + * Illustrates line wrapping for long param/return descriptions. + * @param {string} foo This is a param with a description too long to fit in + * one line. + * @return {number} This returns something that has a description too long to + * fit in one line. + */ + project.MyClass.prototype.method = function(foo) { + return 5; + }; + + +

    You should not indent the @fileoverview command.

    + +

    Even though it is not preferred, it is also acceptable to line up + the description.

    + + + /** + * This is NOT the preferred indentation method. + * @param {string} foo This is a param with a description too long to fit in + * one line. + * @return {number} This returns something that has a description too long to + * fit in one line. + */ + project.MyClass.prototype.method = function(foo) { + return 5; + }; + +
    + + +

    Like JavaDoc, JSDoc supports many HTML tags, like <code>, + <pre>, <tt>, <strong>, <ul>, <ol>, + <li>, <a>, and others.

    + +

    This means that plaintext formatting is not respected. So, don't + rely on whitespace to format JSDoc:

    + + + /** + * Computes weight based on three factors: + * items sent + * items received + * last timestamp + */ + + +

    It'll come out like this:

    + + + Computes weight based on three factors: items sent items received items received + + +

    Instead, do this:

    + + + /** + * Computes weight based on three factors: + * <ul> + * <li>items sent + * <li>items received + * <li>last timestamp + * </ul> + */ + + + The + JavaDoc style guide is a useful resource on how to write + well-formed doc comments. +

    @@ -1925,12 +2094,8 @@ -

    Classes must be documented with a description and usage. - The constructor parameters must also be documented. - If the class inherits from another class, - that should be documented with an @extends tag. - If the class implements an interface, - that should be documented with an @implements tag. +

    Classes must be documented with a description, and appropriate + type tags.

    @@ -1949,20 +2114,10 @@
    -

    A description must be provided along with parameters. - When appropriate or necessary, use full sentences. Method +

    A description must be provided along with parameters. Method descriptions should start with a sentence written in the third person declarative voice.

    - /** - * Converts text to some completely different text. - * @param {string} arg1 An argument that makes this more interesting. - * @return {string} Some return value. - */ - project.MyClass.prototype.someMethod = function(arg1) { - // ... - }; - /** * Operates on an instance of MyClass and returns something. * @param {project.MyClass} obj Instance of MyClass which leads to a long @@ -1974,22 +2129,11 @@ } -

    For simple getters that take no parameters, the description can be - omitted.

    - - - /** - * @return {Element} The element for the component. - */ - goog.ui.Component.prototype.getElement = function() { - return this.element_; - }; - +

    For simple getters that take no parameters and have no + side effects, the description can be omitted.

    -

    It is also nice to have comments for properties.

    - /** * Maximum number of things per pane. @@ -1999,217 +2143,24 @@
    - -

    In cases where type-checking doesn't accurately infer the type of - an expression, it is possible to add a type cast comment by adding a - type annotation comment and enclosing the expression in - parenthesis. The parentheses are required, and may surround the type - annotation comment as well.

    - - - /** @type {number} */ (x) - (/** @type {number} */ x) - -
    - - -

    If you have to line break a @param, - @return, @supported, @this or - @deprecated you should treat this as breaking a code - statement and indent it four spaces.

    - - - /** - * Illustrates line wrapping for long param/return descriptions. - * @param {string} foo This is a param with a description too long to fit in - * one line. - * @return {number} This returns something that has a description too long to - * fit in one line. - */ - project.MyClass.prototype.method = function(foo) { - return 5; - }; - - -

    You should not indent the @fileoverview command.

    - -

    Even though it is not preferred, it is also acceptable to line up - the description. This has the side effect that you will have to - realign the text every time you change a variable name so this will - soon get your code out of sync.

    - - - /** - * This is NOT the preferred indentation method. - * @param {string} foo This is a param with a description too long to fit in - * one line. - * @return {number} This returns something that has a description too long to - * fit in one line. - */ - project.MyClass.prototype.method = function(foo) { - return 5; - }; - -
    - - - - - /** - * Enum for tri-state values. - * @enum {number} - */ - project.TriState = { - TRUE: 1, - FALSE: -1, - MAYBE: 0 - }; - - -

    Note that enums are also valid types - and thus can be used as parameter types, etc.

    - - - /** - * Sets project state. - * @param {project.TriState} state New project state. - */ - project.setState = function(state) { - // ... - }; - -
    - - -

    Sometimes types can get complicated. A function that accepts - content for an Element might look like:

    - - - /** - * @param {string} tagName - * @param {(string|Element|Text|Array.<Element>|Array.<Text>)} contents - * @return {Element} - */ - goog.createElement = function(tagName, contents) { - ... - }; - - -

    You can define commonly used type expressions with a - @typedef tag. For example,

    - - - /** @typedef {(string|Element|Text|Array.<Element>|Array.<Text>)} */ - goog.ElementContent; - - /** - * @param {string} tagName - * @param {goog.ElementContent} contents - * @return {Element} - */ - goog.createElement = function(tagName, contents) { - ... - }; - -
    - - - -

    The compiler has limited support for template types. It can only - infer the type of this inside an anonymous function - literal from the type of the this argument and whether the - this argument is missing.

    - - - /** - * @param {function(this:T, ...)} fn - * @param {T} thisObj - * @param {...*} var_args - * @template T - */ - goog.bind = function(fn, thisObj, var_args) { - ... - }; - // Possibly generates a missing property warning. - goog.bind(function() { this.someProperty; }, new SomeClass()); - // Generates an undefined this warning. - goog.bind(function() { this.someProperty; }); - -
    - +

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + - /** @param {goog.NumberLike} x A number or a string. */ - goog.readNumber = function(x) { - ... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + + + + + + + + + + + -
    Tag Template & Examples DescriptionType-Checking Support
    @param - @param {Type} varname Description -

    For example:

    - - /** - * Queries a Baz for items. - * @param {number} groupNum Subgroup id to query. - * @param {string|number|null} term An itemName, - * or itemId, or null to search everything. - */ - goog.Baz.prototype.query = function(groupNum, term) { - // ... - }; - -
    - Used with method, function and constructor calls to document - the arguments of a function.

    - - Type names must be enclosed in curly braces. If the type - is omitted, the compiler will not type-check the parameter. -

    Fully supported.
    @return - @return {Type} Description -

    For example:

    - - /** - * @return {string} The hex ID of the last item. - */ - goog.Baz.prototype.getLastId = function() { - // ... - return id; - }; - -
    - Used with method and function calls to document the return - type. When writing descriptions for boolean parameters, - prefer "Whether the component is visible" to "True if the - component is visible, false otherwise". If there is no return - value, do not use an @return tag.

    - - Type names must be enclosed in curly braces. If the type - is omitted, the compiler will not type-check the return value. -

    Fully supported.
    @author - @author username@google.com (first last) + @author username@google.com (first last)

    For example:

    /** @@ -2223,407 +2174,14 @@ generally only used in the @fileoverview comment.
    Unrelated to type checking.
    @see - @see Link -

    For example:

    - - /** - * Adds a single item, recklessly. - * @see #addSafely - * @see goog.Collect - * @see goog.RecklessAdder#add - ... - -
    Reference a lookup to another class function or method.Unrelated to type checking.
    @fileoverview - @fileoverview Description -

    For example:

    - - /** - * @fileoverview Utilities for doing things that require this very long - * but not indented comment. - * @author kuth@google.com (Uthur Pendragon) - */ - -
    Makes the comment block provide file level information.Unrelated to type checking.
    @constructor - @constructor -

    For example:

    - - /** - * A rectangle. - * @constructor - */ - function GM_Rect() { - ... - } - -
    - Used in a class's documentation to indicate the constructor. - - Yes. If omitted the compiler will prohibit instantiation. -
    @interface - @interface -

    For example:

    - - /** - * A shape. - * @interface - */ - function Shape() {}; - Shape.prototype.draw = function() {}; - - /** - * A polygon. - * @interface - * @extends {Shape} - */ - function Polygon() {}; - Polygon.prototype.getSides = function() {}; - -
    Used to indicate that the function defines an inteface. - Yes. The compiler will warn about instantiating an interface. -
    @type - - @type Type
    - @type {Type} -
    -

    For example:

    - - /** - * The message hex ID. - * @type {string} - */ - var hexId = hexId; - -
    - Identifies the type of a variable, property, or expression. - Curly braces are not required around most types, but some - projects mandate them for all types, for consistency. - Yes
    @extends - - @extends Type
    - @extends {Type} -
    -

    For example:

    - - /** - * Immutable empty node list. - * @constructor - * @extends goog.ds.BasicNodeList - */ - goog.ds.EmptyNodeList = function() { - ... - }; - -
    - Used with @constructor to indicate that a class inherits from - another class. Curly braces around the type are optional. - Yes
    @implements - - @implements Type
    - @implements {Type} -
    -

    For example:

    - - /** - * A shape. - * @interface - */ - function Shape() {}; - Shape.prototype.draw = function() {}; - - /** - * @constructor - * @implements {Shape} - */ - function Square() {}; - Square.prototype.draw = function() { - ... - }; - -
    - Used with @constructor to indicate that a class implements an - interface. Curly braces around the type are optional. - - Yes. The compiler will warn about incomplete implementations - of interfaces. -
    @lends - @lends objectName
    - @lends {objectName} -

    For example:

    - - goog.object.extend( - Button.prototype, - /** @lends {Button.prototype} */ { - isButton: function() { return true; } - }); - -
    - Indicates that the keys of an object literal should - be treated as properties of some other object. This annotation - should only appear on object literals.

    - - Notice that the name in braces is not a type name like - in other annotations. It's an object name. It names - the object on which the properties are "lent". - For example, @type {Foo} means "an instance of Foo", - but @lends {Foo} means "the constructor Foo".

    - - The - JSDoc Toolkit docs have more information on this - annotation. -

    Yes
    @private - @private -

    For example:

    - - /** - * Handlers that are listening to this logger. - * @type Array.<Function> - * @private - */ - this.handlers_ = []; - -
    - Used in conjunction with a trailing underscore on the method - or property name to indicate that the member is - private. - Trailing underscores may eventually be deprecated as tools are - updated to enforce @private. - Enforced with a flag.
    @protected - @protected -

    For example:

    - - /** - * Sets the component's root element to the given element. Considered - * protected and final. - * @param {Element} element Root element for the component. - * @protected - */ - goog.ui.Component.prototype.setElementInternal = function(element) { - // ... - }; - -
    - Used to indicate that the member or property is - protected. - Should be used in conjunction with names with no trailing - underscore. - Enforced with a flag.
    @this - - @this Type
    - @this {Type} -
    -

    For example:

    - - pinto.chat.RosterWidget.extern('getRosterElement', - /** - * Returns the roster widget element. - * @this pinto.chat.RosterWidget - * @return {Element} - */ - function() { - return this.getWrappedComponent_().getElement(); - }); - -
    - The type of the object in whose context a particular method is - called. Required when the this keyword is referenced - from a function that is not a prototype method. - Yes
    @supported - @supported Description -

    For example:

    - - /** - * @fileoverview Event Manager - * Provides an abstracted interface to the - * browsers' event systems. - * @supported So far tested in IE6 and FF1.5 - */ - -
    - Used in a fileoverview to indicate what browsers are supported - by the file. - Unrelated to type checking.
    @enum - @enum {Type} -

    For example:

    - - /** - * Enum for tri-state values. - * @enum {number} - */ - project.TriState = { - TRUE: 1, - FALSE: -1, - MAYBE: 0 - }; - -
    Used for documenting enum types.Fully supported. If Type is omitted, number assumed.
    @deprecated - @deprecated Description -

    For example:

    - - /** - * Determines whether a node is a field. - * @return {boolean} True if the contents of - * the element are editable, but the element - * itself is not. - * @deprecated Use isField(). - */ - BN_EditUtil.isTopEditableField = function(node) { - // ... - }; - -
    - Used to tell that a function, method or property should not be - used any more. Always provide instructions on what callers - should use instead. - Unrelated to type checking
    @override - @override -

    For example:

    - - /** - * @return {string} Human-readable representation of project.SubClass. - * @override - */ - project.SubClass.prototype.toString() { - // ... - }; - -
    - Indicates that a method or property of a subclass - intentionally hides a method or property of the superclass. If - no other documentation is included, the method or property - also inherits documentation from its superclass. - Yes
    @inheritDoc - @inheritDoc -

    For example:

    - - /** @inheritDoc */ - project.SubClass.prototype.toString() { - // ... - }; - -
    - Indicates that a method or property of a subclass - intentionally hides a method or property of the superclass, - and has exactly the same documentation. Notice that - @inheritDoc implies @override. - Yes
    @code - {@code ...} + {@code ...}

    For example:

    /** @@ -2641,114 +2199,12 @@ Indicates that a term in a JSDoc description is code so it may be correctly formatted in generated documentation.
    Not applicable.
    @license or - @preserve - @license Description -

    For example:

    - - /** - * @preserve Copyright 2009 SomeThirdParty. - * Here is the full license text and copyright - * notice for this file. Note that the notice can span several - * lines and is only terminated by the closing star and slash: - */ - -
    - Anything marked by @license or @preserve will be retained by - the compiler and output at the top of the compiled code for - that file. This annotation allows important notices (such as - legal licenses or copyright text) to survive compilation - unchanged. Line breaks are preserved. - Unrelated to type checking.
    @noalias - @noalias -

    For example:

    - - /** @noalias */ - function Range() {} - -
    - Used in an externs file to indicate to the compiler that the - variable or function should not be aliased as part of the - alias externals pass of the compiler. - Unrelated to type checking.
    @define - @define {Type} description -

    For example:

    - - /** @define {boolean} */ - var TR_FLAGS_ENABLE_DEBUG = true; - - /** @define {boolean} */ - goog.userAgent.ASSUME_IE = false; - -
    - Indicates a constant that can be overridden by the compiler at - compile-time. In the example, the compiler flag - --define='goog.userAgent.ASSUME_IE=true' - could be specified in the BUILD file to indicate that the - constant goog.userAgent.ASSUME_IE should be replaced - with true. - Unrelated to type checking.
    @export - @export -

    For example:

    - - /** @export */ - foo.MyPublicClass.prototype.myPublicMethod = function() { - // ... - }; - -
    -

    Given the code on the left, when the compiler is run with - the --generate_exports flag, it will generate the - code:

    - - goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod', - foo.MyPublicClass.prototype.myPublicMethod); - -

    which will export the symbols to uncompiled code. - Code that uses the @export annotation must either

    -
      -
    1. include //javascript/closure/base.js, or
    2. -
    3. define both goog.exportSymbol and - goog.exportProperty with the same method - signature in their own codebase.
    4. -
    -
    Unrelated to type checking.
    @const - @const + @const

    For example:

    /** @const */ var MY_BEER = 'stout'; @@ -2777,13 +2233,348 @@ clearly inferred. If present, it must be on its own line. An additional comment about the variable is optional.

    Supported by type checking.
    @constructor + @constructor +

    For example:

    + + /** + * A rectangle. + * @constructor + */ + function GM_Rect() { + ... + } + +
    + Used in a class's documentation to indicate the constructor. +
    @define + @define {Type} description +

    For example:

    + + /** @define {boolean} */ + var TR_FLAGS_ENABLE_DEBUG = true; + + /** @define {boolean} */ + goog.userAgent.ASSUME_IE = false; + +
    + Indicates a constant that can be overridden by the compiler at + compile-time. In the example, the compiler flag + --define='goog.userAgent.ASSUME_IE=true' + could be specified in the BUILD file to indicate that the + constant goog.userAgent.ASSUME_IE should be replaced + with true. +
    @deprecated + @deprecated Description +

    For example:

    + + /** + * Determines whether a node is a field. + * @return {boolean} True if the contents of + * the element are editable, but the element + * itself is not. + * @deprecated Use isField(). + */ + BN_EditUtil.isTopEditableField = function(node) { + // ... + }; + +
    + Used to tell that a function, method or property should not be + used any more. Always provide instructions on what callers + should use instead. +
    @enum + @enum {Type} +

    For example:

    + + /** + * Enum for tri-state values. + * @enum {number} + */ + project.TriState = { + TRUE: 1, + FALSE: -1, + MAYBE: 0 + }; + +
    @export + @export +

    For example:

    + + /** @export */ + foo.MyPublicClass.prototype.myPublicMethod = function() { + // ... + }; + +
    +

    Given the code on the left, when the compiler is run with + the --generate_exports flag, it will generate the + code:

    + + goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod', + foo.MyPublicClass.prototype.myPublicMethod); + +

    which will export the symbols to uncompiled code. + Code that uses the @export annotation must either

    +
      +
    1. include //javascript/closure/base.js, or
    2. +
    3. define both goog.exportSymbol and + goog.exportProperty with the same method + signature in their own codebase.
    4. +
    +
    @extends + + @extends Type
    + @extends {Type} +
    +

    For example:

    + + /** + * Immutable empty node list. + * @constructor + * @extends goog.ds.BasicNodeList + */ + goog.ds.EmptyNodeList = function() { + ... + }; + +
    + Used with @constructor to indicate that a class inherits from + another class. Curly braces around the type are optional. +
    @externs + @externs +

    For example:

    + + /** + * @fileoverview This is an externs file. + * @externs + */ + + var document; + +
    +

    + Declares an + + externs file. +

    + + +
    @fileoverview + @fileoverview Description +

    For example:

    + + /** + * @fileoverview Utilities for doing things that require this very long + * but not indented comment. + * @author kuth@google.com (Uthur Pendragon) + */ + +
    Makes the comment block provide file level information.
    @implements + + @implements Type
    + @implements {Type} +
    +

    For example:

    + + /** + * A shape. + * @interface + */ + function Shape() {}; + Shape.prototype.draw = function() {}; + + /** + * @constructor + * @implements {Shape} + */ + function Square() {}; + Square.prototype.draw = function() { + ... + }; + +
    + Used with @constructor to indicate that a class implements an + interface. Curly braces around the type are optional. +
    @inheritDoc + @inheritDoc +

    For example:

    + + /** @inheritDoc */ + project.SubClass.prototype.toString() { + // ... + }; + +
    +

    Deprecated. Use @override + instead.

    + + Indicates that a method or property of a subclass + intentionally hides a method or property of the superclass, + and has exactly the same documentation. Notice that + @inheritDoc implies @override. +
    @interface + @interface +

    For example:

    + + /** + * A shape. + * @interface + */ + function Shape() {}; + Shape.prototype.draw = function() {}; + + /** + * A polygon. + * @interface + * @extends {Shape} + */ + function Polygon() {}; + Polygon.prototype.getSides = function() {}; + +
    Used to indicate that the function defines an inteface.
    @lends + @lends objectName
    + @lends {objectName} +

    For example:

    + + goog.object.extend( + Button.prototype, + /** @lends {Button.prototype} */ { + isButton: function() { return true; } + }); + +
    + Indicates that the keys of an object literal should + be treated as properties of some other object. This annotation + should only appear on object literals.

    + + Notice that the name in braces is not a type name like + in other annotations. It's an object name. It names + the object on which the properties are "lent". + For example, @type {Foo} means "an instance of Foo", + but @lends {Foo} means "the constructor Foo".

    + + The + JSDoc Toolkit docs have more information on this + annotation. +

    @license or + @preserve + @license Description +

    For example:

    + + /** + * @preserve Copyright 2009 SomeThirdParty. + * Here is the full license text and copyright + * notice for this file. Note that the notice can span several + * lines and is only terminated by the closing star and slash: + */ + +
    + Anything marked by @license or @preserve will be retained by + the compiler and output at the top of the compiled code for + that file. This annotation allows important notices (such as + legal licenses or copyright text) to survive compilation + unchanged. Line breaks are preserved. +
    @noalias + @noalias +

    For example:

    + + /** @noalias */ + function Range() {} + +
    + Used in an externs file to indicate to the compiler that the + variable or function should not be aliased as part of the + alias externals pass of the compiler. +
    @nosideeffects - @nosideeffects + @nosideeffects

    For example:

    /** @nosideeffects */ @@ -2809,35 +2600,195 @@ allows the compiler to remove calls to these functions if the return value is not used.
    Unrelated to type checking.
    @typedef@override - @typedef + @override

    For example:

    - /** @typedef {(string|number)} */ - goog.NumberLike; + /** + * @return {string} Human-readable representation of project.SubClass. + * @override + */ + project.SubClass.prototype.toString() { + // ... + }; + +
    + Indicates that a method or property of a subclass + intentionally hides a method or property of the superclass. If + no other documentation is included, the method or property + also inherits documentation from its superclass. +
    @param + @param {Type} varname Description +

    For example:

    + + /** + * Queries a Baz for items. + * @param {number} groupNum Subgroup id to query. + * @param {string|number|null} term An itemName, + * or itemId, or null to search everything. + */ + goog.Baz.prototype.query = function(groupNum, term) { + // ... + }; + +
    + Used with method, function and constructor calls to document + the arguments of a function.

    + + Type names must be enclosed in curly braces. If the type + is omitted, the compiler will not type-check the parameter. +

    @private + @private +

    For example:

    + + /** + * Handlers that are listening to this logger. + * @type Array.<Function> + * @private + */ + this.handlers_ = []; + +
    + Used in conjunction with a trailing underscore on the method + or property name to indicate that the member is + private. + Trailing underscores may eventually be deprecated as tools are + updated to enforce @private. +
    @protected + @protected +

    For example:

    + + /** + * Sets the component's root element to the given element. Considered + * protected and final. + * @param {Element} element Root element for the component. + * @protected + */ + goog.ui.Component.prototype.setElementInternal = function(element) { + // ... + }; + +
    + Used to indicate that the member or property is + protected. + Should be used in conjunction with names with no trailing + underscore. +
    @return + @return {Type} Description +

    For example:

    + + /** + * @return {string} The hex ID of the last item. + */ + goog.Baz.prototype.getLastId = function() { + // ... + return id; + }; + +
    + Used with method and function calls to document the return + type. When writing descriptions for boolean parameters, + prefer "Whether the component is visible" to "True if the + component is visible, false otherwise". If there is no return + value, do not use an @return tag.

    + + Type names must be enclosed in curly braces. If the type + is omitted, the compiler will not type-check the return value. +

    @see + @see Link +

    For example:

    + + /** + * Adds a single item, recklessly. + * @see #addSafely + * @see goog.Collect + * @see goog.RecklessAdder#add + ... + +
    Reference a lookup to another class function or method.
    @supported + @supported Description +

    For example:

    + + /** + * @fileoverview Event Manager + * Provides an abstracted interface to the + * browsers' event systems. + * @supported So far tested in IE6 and FF1.5 + */ + +
    + Used in a fileoverview to indicate what browsers are supported + by the file. +
    @suppress + + @suppress {warning1|warning2} + +

    For example:

    + + /** + * @suppress {deprecation} + */ + function f() { + deprecatedVersionOfF(); }
    - This annotation can be used to declare an alias of a more - complex type. + Suppresses warnings from tools. Warning categories are + separated by |. Yes
    @template - @template + @template

    For example:

    /** @@ -2852,35 +2803,80 @@
    - This annotation can be used to declare a template typename. + This annotation can be used to declare a + template typename. Yes with limitations.
    @externs@this - @externs + + @this Type
    + @this {Type} +

    For example:

    + pinto.chat.RosterWidget.extern('getRosterElement', /** - * @fileoverview This is an externs file. - * @externs + * Returns the roster widget element. + * @this pinto.chat.RosterWidget + * @return {Element} */ - - var document; + function() { + return this.getWrappedComponent_().getElement(); + });
    -

    - Declares an - - externs file. -

    - - + The type of the object in whose context a particular method is + called. Required when the this keyword is referenced + from a function that is not a prototype method. +
    @type + + @type Type
    + @type {Type} +
    +

    For example:

    + + /** + * The message hex ID. + * @type {string} + */ + var hexId = hexId; + +
    + Identifies the type of a variable, property, or expression. + Curly braces are not required around most types, but some + projects mandate them for all types, for consistency. +
    @typedef + @typedef +

    For example:

    + + /** @typedef {(string|number)} */ + goog.NumberLike; + + /** @param {goog.NumberLike} x A number or a string. */ + goog.readNumber = function(x) { + ... + } + +
    + This annotation can be used to declare an alias of a more + complex type. No
    @@ -2921,72 +2917,17 @@

    + + - -

    Like JavaDoc, JSDoc supports many HTML tags, like <code>, - <pre>, <tt>, <strong>, <ul>, <ol>, - <li>, <a>, and others.

    - -

    This means that plaintext formatting is not respected. So, don't - rely on whitespace to format JSDoc:

    - - - /** - * Computes weight based on three factors: - * items sent - * items received - * last timestamp - */ - - -

    It'll come out like this:

    - - Computes weight based on three factors: items sent items received items received - -

    Instead, do this:

    - - - /** - * Computes weight based on three factors: - * <ul> - * <li>items sent - * <li>items received - * <li>last timestamp - * </ul> - */ - - -

    Also, don't include HTML or HTML-like tags unless you want them to - be interpreted as HTML.

    - - - /** - * Changes <b> tags to <span> tags. - */ - - -

    It'll come out like this:

    - - Changes tags to tags. - -

    On the other hand, people need to be able to read this in its - plaintext form too, so don't go overboard with the HTML:

    - - - /** - * Changes &lt;b&gt; tags to &lt;span&gt; tags. - */ - - -

    People will know what you're talking about if you leave the - angle-brackets out, so do this:

    - - - /** - * Changes 'b' tags to 'span' tags. - */ - -
    + + + Should be defined in the same file as the top level class. + + + Inner classes and enums defined on another class should be defined in + the same file as the top level class. goog.provide + statements are only necessary for the top level class. @@ -3253,7 +3194,7 @@

    - Revision 2.20 + Revision 2.27

    diff --git a/objcguide.xml b/objcguide.xml index 8f4de87..06abacf 100644 --- a/objcguide.xml +++ b/objcguide.xml @@ -4,7 +4,7 @@

    -Revision 2.24 +Revision 2.36

    @@ -16,7 +16,7 @@ Revision 2.24 Dave MacLachlan
    - + @@ -102,7 +102,7 @@ Revision 2.24 Code meant to be shared across different projects is a good candidate to be included in this repository.

    - +

    @@ -117,7 +117,7 @@ Revision 2.24 - +

    They say an example is worth a thousand words so let's start off with an example that should give you a feel for the style, spacing, naming, etc. @@ -129,110 +129,111 @@ Revision 2.24

    - // GTMFoo.h - // FooProject + // Foo.h + // AwesomeProject // // Created by Greg Miller on 6/13/08. // Copyright 2008 Google, Inc. All rights reserved. // - + #import <Foundation/Foundation.h> - + // A sample class demonstrating good Objective-C style. All interfaces, // categories, and protocols (read: all top-level declarations in a header) // MUST be commented. Comments must also be adjacent to the object they're // documenting. // // (no blank line between this comment and the interface) - @interface GTMFoo : NSObject { + @interface Foo : NSObject { @private - NSString *foo_; NSString *bar_; + NSString *bam_; } - - // Returns an autoreleased instance of GMFoo. See -initWithString: for details - // about the argument. - + (id)fooWithString:(NSString *)string; - - // Designated initializer. |string| will be copied and assigned to |foo_|. - - (id)initWithString:(NSString *)string; - - // Gets and sets the string for |foo_|. - - (NSString *)foo; - - (void)setFoo:(NSString *)newFoo; - - // Does some work on |blah| and returns YES if the work was completed - // successfuly, and NO otherwise. - - (BOOL)doWorkWithString:(NSString *)blah; - + + // Returns an autoreleased instance of Foo. See -initWithBar: for details + // about |bar|. + + (id)fooWithBar:(NSString *)bar; + + // Designated initializer. |bar| is a thing that represents a thing that + // does a thing. + - (id)initWithBar:(NSString *)bar; + + // Gets and sets |bar_|. + - (NSString *)bar; + - (void)setBar:(NSString *)bar; + + // Does some work with |blah| and returns YES if the work was completed + // successfully, and NO otherwise. + - (BOOL)doWorkWithBlah:(NSString *)blah; + @end - +

    An example source file, demonstrating the correct commenting and spacing for the @implementation of an interface. It also includes the reference implementations for important methods like getters and setters, init, and dealloc.

    - + // - // GTMFoo.m - // FooProject + // Foo.m + // AwesomeProject // // Created by Greg Miller on 6/13/08. // Copyright 2008 Google, Inc. All rights reserved. // - - #import "GTMFoo.h" - - - @implementation GTMFoo - - + (id)fooWithString:(NSString *)string { - return [[[self alloc] initWithString:string] autorelease]; + + #import "Foo.h" + + + @implementation Foo + + + (id)fooWithBar:(NSString *)bar { + return [[[self alloc] initWithBar:bar] autorelease]; } - + // Must always override super's designated initializer. - (id)init { - return [self initWithString:nil]; + return [self initWithBar:nil]; } - - - (id)initWithString:(NSString *)string { + + - (id)initWithBar:(NSString *)bar { if ((self = [super init])) { - foo_ = [string copy]; - bar_ = [[NSString alloc] initWithFormat:@"hi %d", 3]; + bar_ = [bar copy]; + bam_ = [[NSString alloc] initWithFormat:@"hi %d", 3]; } - return self; + return self; } - + - (void)dealloc { - [foo_ release]; [bar_ release]; + [bam_ release]; [super dealloc]; } - - - (NSString *)foo { - return foo_; + + - (NSString *)bar { + return bar_; } - - - (void)setFoo:(NSString *)newFoo { - [foo_ autorelease]; - foo_ = [newFoo copy]; + + - (void)setBar:(NSString *)bar { + [bar_ autorelease]; + bar_ = [bar copy]; } - - - (BOOL)doWorkWithString:(NSString *)blah { + + - (BOOL)doWorkWithBlah:(NSString *)blah { // ... return NO; } - + @end

    Blank lines before and after @interface, @implementation, and @end are optional. If your - @interface declares instance variables, as most do, any blank + @interface declares instance variables, a blank line should come after the closing brace (}).

    @@ -260,14 +261,19 @@ Revision 2.24 - Each line of text in your code should be at most 80 characters long. + Each line of text in your code should try to be at most 80 characters + long.

    - Even though Objective-C tends to be a more verbose language than C++, - to aid in the interoperability with that guide, we have decided - to keep the limit at 80 columns as well. It's easier to live with - than you might expect. + Strive to keep your code within 80 columns. We realize that Objective C + is a verbose language and in some cases it may be more readable to + extend slightly beyond 80 columns, but this should definitely be the + exception and not commonplace. +

    +

    + If a reviewer asks that you reformat a line because they feel it can be + fit in 80 columns and still be readable, you should do so.

    @@ -435,7 +441,7 @@ Revision 2.24

    This applies to class declarations, instance variables, and method - delcarations. For example: + declarations. For example:

    @interface MyProtocoledClass : NSObject<NSWindowDelegate> { @@ -448,6 +454,92 @@ Revision 2.24
    + + + Blocks are preferred to the target-selector pattern when creating + callbacks, as it makes code easier to read. Code inside blocks should be + indented four spaces. + + +

    + There are several appropriate style rules, depending on how long the + block is: +

    +
      +
    • If the block can fit on one line, no wrapping is necessary.
    • +
    • + If it has to wrap, the closing brace should line up with the first + character of the line on which the block is declared. +
    • +
    • Code within the block should be indented four spaces.
    • +
    • + If the block is large, e.g. more than 20 lines, it is recommended to + move it out-of-line into a local variable. +
    • +
    • + If the block takes no parameters, there are no spaces between the + characters ^{. If the block takes parameters, there is no + space between the ^( characters, but there is one space + between the ) { characters. +
    • +
    • + Two space indents inside blocks are also allowed, but should only + be used when it's consistent with the rest of the project's code. +
    • +
    + + // The entire block fits on one line. + [operation setCompletionBlock:^{ [self onOperationDone]; }]; + + // The block can be put on a new line, indented four spaces, with the + // closing brace aligned with the first character of the line on which + // block was declared. + [operation setCompletionBlock:^{ + [self.delegate newDataAvailable]; + }]; + + // Using a block with a C API follows the same alignment and spacing + // rules as with Objective-C. + dispatch_async(fileIOQueue_, ^{ + NSString* path = [self sessionFilePath]; + if (path) { + // ... + } + }); + + // An example where the parameter wraps and the block declaration fits + // on the same line. Note the spacing of |^(SessionWindow *window) {| + // compared to |^{| above. + [[SessionService sharedService] + loadWindowWithCompletionBlock:^(SessionWindow *window) { + if (window) { + [self windowDidLoad:window]; + } else { + [self errorLoadingWindow]; + } + }]; + + // An example where the parameter wraps and the block declaration does + // not fit on the same line as the name. + [[SessionService sharedService] + loadWindowWithCompletionBlock: + ^(SessionWindow *window) { + if (window) { + [self windowDidLoad:window]; + } else { + [self errorLoadingWindow]; + } + }]; + + // Large blocks can be declared out-of-line. + void (^largeBlock)(void) = ^{ + // ... + }; + [operationQueue_ addOperationWithBlock:largeBlock]; + + +
    +
    @@ -743,8 +835,9 @@ Revision 2.24 - Start each file with a copyright notice, followed by a - description of the contents of the file. + 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. @@ -753,10 +846,12 @@ Revision 2.24

    Every file should contain the following items, in order:

      +
    • a basic description of the contents of the file
    • +
    • an author line
    • a copyright statement (for example, Copyright 2008 Google Inc.)
    • -
    • a license boilerplate. Choose the appropriate boilerplate - for the license used by the project (for example, +
    • license boilerplate if neccessary. Choose the appropriate + boilerplate for the license used by the project (e.g. Apache 2.0, BSD, LGPL, GPL)

    @@ -838,42 +933,46 @@ Revision 2.24

    - Instance variable pointers to objects derived from NSObject are - presumed to be retained, and should be documented as weak if - they are not retained by the class. However, instance variables which - are labeled as IBOutlets are presumed to not be retained by the class, - and should be documented as strong if the class does retain - them. + 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 __weak lifetime qualifier when applicable. + Similarly, declared properties must specify a weak or + assign 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.

    Where instance variables are pointers to CoreFoundation, C++, and - other non-Objective-C objects, they should always be documented in - comments as strong or weak. Be mindful that support for automatic C++ - objects encapsulated in Objective-C objects is disabled by default, as - described here. + 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.

    - Examples of strong and weak documentation: + Be mindful that support for automatic C++ objects encapsulated in + Objective-C objects is disabled by default, as described here. +

    +

    + Examples of strong and weak declarations: @interface MyDelegate : NSObject { @private - IBOutlet NSButton* okButton_; // normal NSControl - IBOutlet NSMenu* myContextMenu_; // manually-loaded menu (strong) + IBOutlet NSButton *okButton_; // normal NSControl; implicitly weak on Mac only AnObjcObject* doohickey_; // my doohickey - MyController* controller_; // so we can send msgs back (weak, owns me) + __weak MyObjcParent *parent_; // so we can send msgs back (owns me) // non-NSObject pointers... - CWackyCPPClass* wacky_; // some cross-platform object (strong) - CFDictionaryRef* dict_; // (strong) + __strong CWackyCPPClass *wacky_; // some cross-platform object + __strong CFDictionaryRef *dict_; } + @property(strong, nonatomic) NSString *doohickey; + @property(weak, nonatomic) NSString *parent; @end -

    -
    strong
    The object will be retain'd by this class
    -
    weak
    The object will be not be retain'd by this class - (e.g. a delegate).
    -

    @@ -1171,7 +1270,52 @@ Revision 2.24 - + + + Instance subclasses may be in an inconsistent state during + init and dealloc method execution, so code in + those methods should avoid invoking accessors. + + +

    + Subclasses have not yet been initialized or have already deallocated + when init and dealloc methods execute, making + accessor methods potentially unreliable. Whenever practical, directly + assign to and release ivars in those methods rather than rely on + accessors. +

    + + - (id)init { + self = [super init]; + if (self) { + bar_ = [[NSMutableString alloc] init]; // good + } + return self; + } + + - (void)dealloc { + [bar_ release]; // good + [super dealloc]; + } + + + - (id)init { + self = [super init]; + if (self) { + self.bar = [NSMutableString string]; // avoid + } + return self; + } + + - (void)dealloc { + self.bar = nil; // avoid + [super dealloc]; + } + + +
    + + dealloc should process instance variables in the same order the @interface declares them, so it is easier for a reviewer @@ -1452,60 +1596,6 @@ Revision 2.24 retain.

    - -

    - CFTypes should always have the @dynamic implementation - directive. -

    -

    - Since CFTypes can't have the retain property - attribute, the developer must handle retaining and releasing the - value themselves. In the rare case that you do actually want - assignment it is better to make that completely clear by actually - implementing the setter and getter and commenting why that is the - case. -

    -
    - -

    - Use implementation directives for all properties even if they are - @dynamic by default. -

    -

    - Even though @dynamic is default, explicitly list it out - with all of the other property implementation directives making it - clear how every property in a class is handled at a single glance. -

    - - @interface MyClass : NSObject - @property(readonly) NSString *name; - @end - - @implementation MyClass - . - . - . - - (NSString*)name { - return @"foo"; - } - @end - - - @interface MyClass : NSObject - @property(readonly) NSString *name; - @end - - @implementation MyClass - @dynamic name; - . - . - . - - (NSString*)name { - return @"foo"; - } - @end - -

    Be aware of the overhead of properties. By default, all synthesized @@ -1533,6 +1623,61 @@ Revision 2.24 + + +

    + Omit the empty set of braces on interfaces that do not declare any + instance variables. + + + + @interface MyClass : NSObject + // Does a lot of stuff + - (void)fooBarBam; + @end + + + @interface MyClass : NSObject { + } + // Does a lot of stuff + - (void)fooBarBam; + @end + + + + + + +

    + For code that will run on iOS only, use of automatically synthesized + instance variables is preferred. +

    +

    + When synthesizing the instance variable, use + @synthesize var = var_; as this prevents accidentally calling + var = blah; when self.var = blah; is intended. +

    +
    + + + // Header file + @interface Foo : NSObject + // A guy walks into a bar. + @property(nonatomic, copy) NSString *bar; + @end + + // Implementation file + @interface Foo () + @property(nonatomic, retain) NSArray *baz; + @end + + @implementation Foo + @synthesize bar = bar_; + @synthesize baz = baz_; + @end + + +
    @@ -1601,7 +1746,7 @@ Revision 2.24

    -Revision 2.24 +Revision 2.36

    diff --git a/pyguide.html b/pyguide.html index 475cebf..d1d75c6 100644 --- a/pyguide.html +++ b/pyguide.html @@ -6,28 +6,33 @@ @@ -100,7 +136,7 @@

    Google Python Style Guide

    - Revision 2.20 + Revision 2.28

    @@ -144,7 +180,7 @@

    Displaying Hidden Details in this Guide

    link - +
    This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you @@ -183,7 +219,7 @@

    pychecker

    link - +
    Run pychecker over your code.
    @@ -255,7 +291,7 @@

    Imports

    link - +
    Use imports for packages and modules only.
    @@ -283,7 +319,7 @@ prefix.
    Use from x import y as z if two modules named - z are to be imported or if y is an + y are to be imported or if y is an inconveniently long name.

    For example the module @@ -305,7 +341,7 @@

    Packages

    link - +
    Import each module using the full pathname location of the module.
    @@ -340,7 +376,7 @@ from sound.effects import echo

    Exceptions

    link - +
    Exceptions are allowed but must be used carefully.
    @@ -408,7 +444,7 @@ from sound.effects import echo

    Global variables

    link - +
    Avoid global variables.
    @@ -449,7 +485,7 @@ from sound.effects import echo

    Nested/Local/Inner Classes and Functions

    link - +
    Nested/local/inner classes and functions are fine.
    @@ -479,7 +515,7 @@ from sound.effects import echo

    List Comprehensions

    link - +
    Okay to use for simple cases.
    @@ -548,7 +584,7 @@ from sound.effects import echo

    Default Iterators and Operators

    link - +
    Use default iterators and operators for types that support them, like lists, dictionaries, and files. @@ -593,7 +629,7 @@ from sound.effects import echo

    Generators

    link - +
    Use generators as needed.
    @@ -626,7 +662,7 @@ from sound.effects import echo

    Lambda Functions

    link - +
    Okay for one-liners.
    @@ -666,7 +702,7 @@ from sound.effects import echo

    Default Argument Values

    link - +
    Okay in most cases.
    @@ -727,7 +763,7 @@ from sound.effects import echo

    Properties

    link - +
    Use properties for accessing or setting data where you would normally have used simple, lightweight accessor or setter methods. @@ -823,7 +859,7 @@ from sound.effects import echo

    True/False evaluations

    link - +
    Use the "implicit" false if at all possible.
    @@ -908,7 +944,7 @@ from sound.effects import echo

    Deprecated Language Features

    link - +
    Use string methods instead of the string module where possible. Use function call syntax instead @@ -944,7 +980,7 @@ from sound.effects import echo

    Lexical Scoping

    link - +
    Okay to use.
    @@ -1010,7 +1046,7 @@ from sound.effects import echo

    Function and Method Decorators

    link - +
    Use decorators judiciously when there is a clear advantage.
    @@ -1080,7 +1116,7 @@ from sound.effects import echo

    Threading

    link - +
    Do not rely on the atomicity of built-in types.
    @@ -1110,7 +1146,7 @@ from sound.effects import echo

    Power Features

    link - +
    Avoid these features.
    @@ -1148,7 +1184,7 @@ from sound.effects import echo

    Semicolons

    link - +
    Do not terminate your lines with semi-colons and do not use semi-colons to put two commands on the same line. @@ -1160,7 +1196,7 @@ from sound.effects import echo

    Line length

    link - +
    Maximum line length is 80 characters.
    @@ -1171,6 +1207,10 @@ from sound.effects import echo earlier.

    +

    + Do not use backslash line continuation. +

    +

    Make use of Python's @@ -1209,7 +1249,7 @@ from sound.effects import echo

    Parentheses

    link - +
    Use parentheses sparingly.
    @@ -1241,7 +1281,7 @@ from sound.effects import echo

    Indentation

    link - +
    Indent your code blocks with 4 spaces.
    @@ -1278,7 +1318,7 @@ from sound.effects import echo

    Blank Lines

    link - +
    Two blank lines between top-level definitions, one blank line between method definitions. @@ -1297,7 +1337,7 @@ from sound.effects import echo

    Whitespace

    link - +
    Follow standard typographic rules for the use of spaces around punctuation. @@ -1376,24 +1416,18 @@ from sound.effects import echo

    Shebang Line

    link - +
    - All .py files (except __init__.py package - files) should begin with a - - #!/usr/bin/python<version> - shebang line. + Most .py files do not need to start with a + #! line. Start the main file of a binary with + #!/usr/bin/python.
    @@ -1402,7 +1436,7 @@ from sound.effects import echo

    Comments

    link - +
    Be sure to use the right style for module, function, method and in-line comments. @@ -1450,24 +1484,66 @@ from sound.effects import echo Functions and Methods

    - Any function or method which is not both obvious and very short - needs a doc string. Additionally, any externally accessible - function or method regardless of length or simplicity needs a - doc string. The doc string should include what the function does - and have detailed descriptions of the input and output. It - should not, generally, describe how it does it unless it's some - complicated algorithm. For tricky code block/inline comments - within the code are more appropriate. The doc string should give - enough information to write a call to the function without - looking at a single line of the function's code. Args should be - individually documented, an explanation following after a colon, - and should use a uniform hanging indent of 2 or 4 spaces. The - doc string should specify the expected types where specific types - are required. A "Raises:" section should list all exceptions - that can be raised by the function. The doc string for generator - functions should use "Yields:" rather than "Returns:". + As used in this section "function" applies to methods, function, and + generators.

    +

    + A function must have a docstring, unless it meets all of the following + criteria: +

      +
    • not externally visible
    • +
    • very short
    • +
    • obvious
    • +
    +

    + +

    + A docstring should give enough information to write a call to the function + without reading the function's code. A docstring should describe the + function's calling syntax and its semantics, not its implementation. For + tricky code, comments alongside the code are more appropriate than using + docstrings. +

    + +

    + Certain aspects of a function should be documented in special sections, + listed below. Each section begins with a heading line, which ends with a + colon. Sections should be indented two spaces, except for the heading. +

    + +
    +
    Args:
    +
    + List each parameter by name. A description should follow the name, and + be separated by a colon and a space. If the description is too long to + fit on a single 80-character line, use a hanging indent of 2 or 4 spaces + (be consistent with the rest of the file). + +

    + The description should mention required type(s) and the meaning of + the argument. +

    + +

    + If a function accepts *foo (variable length argument lists) and/or + **bar (arbitrary keyword arguments), they should be listed as *foo and + **bar. +

    +
    + +
    Returns: (or Yields: for generators)
    +
    + Describe the type and semantics of the return value. If the function + only returns None, this section is not required. +
    + +
    Raises:
    +
    + List all exceptions that are relevant to the interface. +
    +
    +
     def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
         """Fetches rows from a Bigtable.
    @@ -1581,7 +1657,7 @@ from sound.effects import echo
     

    Classes

    link - +
    If a class inherits from no other base classes, explicitly inherit from object. This also applies to nested classes. @@ -1627,7 +1703,7 @@ from sound.effects import echo

    Strings

    link - +
    Use the % operator for formatting strings, even when the parameters are all strings. Use your best judgement @@ -1681,40 +1757,47 @@ Don't do this.

    TODO Comments

    link - -
    - Use TODO comments for code that is temporary, a - short-term solution, or good-enough but not perfect. -
    -
    +
    # TODO(kl@gmail.com): Use a "*" here for string repetition.
    +# TODO(Zeke) Change this to use relations.
    +

    + If your TODO is of the form "At a future date do + something" make sure that you either include a very specific + date ("Fix by November 2009") or a very specific event + ("Remove this code when all clients can handle XML responses."). +

    +
    +

    Imports formatting

    link - +
    Imports should be on separate lines.
    @@ -1757,7 +1840,7 @@ Don't do this.

    Statements

    link - +
    Generally only one statement per line.
    @@ -1794,7 +1877,7 @@ Don't do this.

    Access Control

    link - +
    If an accessor function would be trivial you should use public variables instead of accessor functions to avoid the extra cost of function @@ -1817,11 +1900,13 @@ Don't do this.

    Naming

    link - +
    - module_name, package_name, ClassName, method_name, ExceptionName, - function_name, GLOBAL_VAR_NAME, instance_var_name, - function_parameter_name, local_var_name. + module_name, package_name, ClassName, + method_name, ExceptionName, + function_name, GLOBAL_CONSTANT_NAME, + global_var_name, instance_var_name, function_parameter_name, + local_var_name.