Blink‎ > ‎

Blink Coding Style Guidelines

These guidelines are specific to the Blink project, not to be confused with the general Chromium Coding Style Guidelines.

C++

Indentation

  1. Use spaces, not tabs. Tabs should only appear in files that require them for semantic meaning, like Makefiles. [indentation-no-tabs]
  2. The indent size is 4 spaces.

    Right:

    int main() { return 0; }

    Wrong:

    int main() { return 0; }
    [indentation-4-spaces]

  3. The contents of an outermost namespace block (and any nested namespaces with the same scope) should not be indented. The contents of other nested namespaces should be indented.

    Right:

    // Document.h namespace blink { class Document { Document(); ... }; namespace NestedNamespace { ... } } // namespace blink
    // Document.cpp namespace blink { Document::Document() { ... } } // namespace blink

    Wrong:

    // Document.h namespace blink { class Document { Document(); ... }; namespace NestedNamespace { ... } } // namespace blink
    // Document.cpp
    namespace blink {
    
        Document::Document()
        {
            ...
        }
    
    } // namespace blink
    
    [indentation-namespace]

  4. A case label should line up with its switch statement. The case statement is indented.

    Right:

    switch (condition) { case fooCondition: case barCondition: i++; break; default: i--; }

    Wrong:

    switch (condition) { case fooCondition: case barCondition: i++; break; default: i--; }
    [indentation-case-label]

  5. Boolean expressions at the same nesting level that span multiple lines should have their operators on the left side of the line instead of the right side.

    Right:

    if (attr->name() == srcAttr || attr->name() == lowsrcAttr || (attr->name() == usemapAttr && attr->value().domString()[0] != '#')) return;

    Wrong:

    if (attr->name() == srcAttr || attr->name() == lowsrcAttr || (attr->name() == usemapAttr && attr->value().domString()[0] != '#')) return;
    [indentation-wrap-bool-op]

Spacing

  1. Do not place spaces around unary operators.

    Right:

    i++;

    Wrong:

    i ++;
    [spacing-unary-op]

  2. Do place spaces around binary and ternary operators.

    Right:

    y = m * x + b; f(a, b); c = a | b; return condition ? 1 : 0;

    Wrong:

    y=m*x+b; f(a,b); c = a|b; return condition ? 1:0;
    [spacing-binary-ternary-op]

  3. Do not place spaces before comma and semicolon.

    Right:

    for (int i = 0; i < 10; ++i) doSomething(); f(a, b);

    Wrong:

    for (int i = 0 ; i < 10 ; ++i) doSomething(); f(a , b) ;
    [spacing-comma-semicolon]

  4. Place spaces between control statements and their parentheses.

    Right:

    if (condition) doIt();

    Wrong:

    if(condition)
        doIt();
    
    [spacing-control-paren]

  5. Do not place spaces between a function and its parentheses, or between a parenthesis and its content.

    Right:

    f(a, b);

    Wrong:

    f (a, b); f( a, b );
    [spacing-function-paren]

Line breaking

  1. Each statement should get its own line.

    Right:

    x++; y++; if (condition) doIt();

    Wrong:

    x++; y++; if (condition) doIt();
    [linebreaking-multiple-statements]

  2. An else statement should go on the same line as a preceding close brace if one is present, else it should line up with the if statement.

    Right:

    if (condition) { ... } else { ... } if (condition) doSomething(); else doSomethingElse();

    Wrong:

    if (condition) { ... } else { ... } if (condition) doSomething(); else doSomethingElse(); if (condition) doSomething(); else { ... }
    [linebreaking-else-braces]

  3. An else if statement should be written as an if statement when the prior if concludes with a return statement.

    Right:

    if (condition) { ... return someValue; } if (condition) { ... }

    Wrong:

    if (condition) { ... return someValue; } else if (condition) { ... }
    [linebreaking-else-if]

Braces

  1. Function definitions: place each brace on its own line.

    Right:

    int main() { ... }

    Wrong:

    int main() { ... }
    [braces-function]

  2. Other braces: place the open brace on the line preceding the code block; place the close brace on its own line.

    Right:

    class MyClass { ... }; namespace blink { ... } for (int i = 0; i < 10; ++i) { ... }

    Wrong:

    class MyClass { ... };
    [braces-blocks]

  3. Curly braces are not required for single-line conditionals or loop bodies, but are required for single-statement bodies that span multiple lines.

    Right:

    if (condition)
        doIt();

    if (condition) {
        doIt();
    }

    if (condition) {
        myFunction(reallyLongParam1, reallyLongParam2, ...
            reallyLongParam5);
    }


    Wrong:

    if (condition)
        // Single-line comment ignored by compiler
        doIt();

    if (condition)
        myFunction(reallyLongParam1, reallyLongParam2, ...
            reallyLongParam5);


    [braces-single-line]

  4. If one part of an if-else statement uses curly braces, the other part must too.

    Right:

    if (condition)
        doIt();
    else
        doSomethingElse();

    if (condition) {
        doIt();
    } else {
        doSomethingElse();
    }

    if (condition) {
        doSomethingWith(reallyLongParam1, ...
            reallyLongParam2);
    } else {
        doSomethingElse();
    }

    Wrong:

    if (condition) {
        doIt();
    } else
        doSomethingElse();

    if (condition)
        doIt();
    else {
        doSomethingElse();
    }

    if (condition) {
        doSomethingWith(reallyLongParam1, ...
            reallyLongParam2);
    } else
        doSomethingElse();


    [braces-must-match]

  5. Control clauses without a body should use empty braces:

    Right:

    for ( ; current; current = current->next) { }


    Wrong:

    for ( ; current; current = current->next);


    [braces-empty-block]

Null, false, and 0

  1. Null pointer [zero-null]
    1. In C++, the null pointer value should be written as 0. Use nullptr for smart pointers such as PassRefPtr (see this thread for the reason)
    2. In C, it should be written as NULL.
    3. In Objective-C and Objective-C++, follow the guideline for C or C++, respectively, but use nil to represent a null Objective-C object.

  2. C++ and C bool values should be written as true and false. Objective-C BOOL values should be written as YES and NO. [zero-bool]

  3. Tests for true/false and null/non-null should be done without equality comparisons. Checks for zero/non-zero can be compared directly to zero if desired, but this is left to discretion.

    Right:

    if (condition) doIt(); if (!ptr) return; if (count == 0) return; if (!count) return;

    Wrong:

    if (condition == true) doIt(); if (ptr == NULL) return;
    [zero-comparison]

  4. In Objective-C, instance variables are initialized to zero automatically. Don't add explicit initializations to nil or NO in an init method. [zero-objc-variables]

Floating point literals

  1. Unless required in order to force floating point math, do not append .0, .f and .0f to floating point literals.

    Right:

    const double duration = 60; void setDiameter(float diameter) { radius = diameter / 2; } setDiameter(10); const int framesPerSecond = 12; double frameDuration = 1.0 / framesPerSecond;

    Wrong:

    const double duration = 60.0; void setDiameter(float diameter) { radius = diameter / 2.f; } setDiameter(10.f); const int framesPerSecond = 12; double frameDuration = 1 / framesPerSecond; // integer division
    [float-suffixes]

Names

  1. Use CamelCase. Capitalize the first letter, including all letters in an acronym, in a class, struct, protocol, or namespace name. Lower-case the first letter, including all letters in an acronym, in a variable or function name.

    Right:

    struct Data; size_t bufferSize; class HTMLDocument; String mimeType();

    Wrong:

    struct data; size_t buffer_size; class HtmlDocument; String MIMEType();
    [names-basic]

  2. Use full words, except in the rare case where an abbreviation would be more canonical and easier to understand.

    Right:

    size_t characterSize; size_t length; short tabIndex; // More canonical.

    Wrong:

    size_t charSize; size_t len; short tabulationIndex; // bizarre
    [names-full-words]

  3. Data members in C++ classes should be private. Static data members should be prefixed by "s_". Other data members should be prefixed by "m_".

    Right:

    class String { public: ... private: short m_length; };

    Wrong:

    class String { public: ... short length; };
    [names-data-members]

  4. Prefix Objective-C instance variables with "_".

    Right:

    @class String ... short _length; @end

    Wrong:

    @class String ... short length; @end
    [names-objc-instance-variables]

  5. Precede boolean values with words like "is" and "did".

    Right:

    bool isValid; bool didSendData;

    Wrong:

    bool valid; bool sentData;
    [names-bool]

  6. Precede setters with the word "set". Use bare words for getters. Setter and getter names should match the names of the variables being set/gotten.

    Right:

    void setCount(size_t); // Sets m_count. size_t count(); // Returns m_count.

    Wrong:

    void setCount(size_t); // sets m_theCount size_t getCount();
    [names-setter-getter]

  7. Precede getters that return values through out arguments with the word "get".

    Right:

    void getInlineBoxAndOffset(InlineBox*&, int& caretOffset) const;

    Wrong:

    void inlineBoxAndOffset(InlineBox*&, int& caretOffset) const;
    [names-out-argument]

  8. Use descriptive verbs in function names.

    Right:

    bool convertToASCII(short*, size_t);

    Wrong:

    bool toASCII(short*, size_t);
    [names-verb]

  9. Leave meaningless variable names out of function declarations. A good rule of thumb is if the parameter type name contains the parameter name (without trailing numbers or pluralization), then the parameter name isn't needed. Usually, there should be a parameter name for bools, strings, and numerical types.

    Right:

    void setCount(size_t); void doSomething(ScriptExecutionContext*);

    Wrong:

    void setCount(size_t count); void doSomething(ScriptExecutionContext* context);
    [names-variable-name-in-function-decl]

  10. Prefer enums to bools on function parameters if callers are likely to be passing constants, since named constants are easier to read at the call site. An exception to this rule is a setter function, where the name of the function already makes clear what the boolean is.

    Right:

    doSomething(something, AllowFooBar); paintTextWithShadows(context, ..., textStrokeWidth > 0, isHorizontal()); setResizable(false);

    Wrong:

    doSomething(something, false); setResizable(NotResizable);
    [names-enum-to-bool]

  11. Objective-C method names should follow the Cocoa naming guidelines — they should read like a phrase and each piece of the selector should start with a lowercase letter and use intercaps. [names-objc-methods]

  12. Enum members should use InterCaps with an initial capital letter. [names-enum-members]

  13. Prefer const to #define. Prefer inline functions to macros. [names-const-to-define]

  14. #defined constants should use all uppercase names with words separated by underscores. [names-define-constants]

  15. Macros that expand to function calls or other non-constant computation: these should be named like functions, and should have parentheses at the end, even if they take no arguments (with the exception of some special macros like ASSERT). Note that usually it is preferable to use an inline function in such cases instead of a macro.

    Right:

    #define WBStopButtonTitle() \ NSLocalizedString(@"Stop", @"Stop button title")

    Wrong:

    #define WB_STOP_BUTTON_TITLE \ NSLocalizedString(@"Stop", @"Stop button title") #define WBStopButtontitle \ NSLocalizedString(@"Stop", @"Stop button title")
    [names-define-non-const]

  16. #define, #ifdef "header guards" should be named exactly the same as the file (including case), replacing the '.' with a '_'.

    Right:

    // HTMLDocument.h #ifndef HTMLDocument_h #define HTMLDocument_h

    Wrong:

    // HTMLDocument.h #ifndef _HTML_DOCUMENT_H_ #define _HTML_DOCUMENT_H_
    [names-header-guards]

Other Punctuation

  1. Constructors for C++ classes should initialize all of their members using C++ initializer syntax. Each member (and superclass) should be indented on a separate line, with the colon or comma preceding the member on that line.

    Right:

    MyClass::MyClass(Document* doc) : MySuperClass() , m_myMember(0) , m_doc(doc) { } MyOtherClass::MyOtherClass() : MySuperClass() { }

    Wrong:

    MyClass::MyClass(Document* doc) : MySuperClass() { m_myMember = 0; m_doc = doc; } MyOtherClass::MyOtherClass() : MySuperClass() {}
    [punctuation-member-init]

  2. Prefer index over iterator in Vector iterations for a terse, easier-to-read code.

    Right:

    size_t frameViewsCount = frameViews.size(); for (size_t i = 0; i < frameViewsCount; ++i) frameViews[i]->updateLayoutAndStyleIfNeededRecursive();

    Wrong:

    const Vector<RefPtr<FrameView> >::iterator end = frameViews.end(); for (Vector<RefPtr<FrameView> >::iterator it = frameViews.begin(); it != end; ++it) (*it)->updateLayoutAndStyleIfNeededRecursive();
    [punctuation-vector-index]

Pointers and References

  1. Pointer types in non-C++ code — Pointer types should be written with a space between the type and the * (so the * is adjacent to the following identifier if any). [pointers-non-cpp]

  2. Pointer and reference types in C++ code — Both pointer types and reference types should be written with no space between the type name and the * or &.

    Right:

    Image* SVGStyledElement::doSomething(PaintInfo& paintInfo) { SVGStyledElement* element = static_cast<SVGStyledElement*>(node()); const KCDashArray& dashes = dashArray();

    Wrong:

    Image *SVGStyledElement::doSomething(PaintInfo &paintInfo) { SVGStyledElement *element = static_cast<SVGStyledElement *>(node()); const KCDashArray &dashes = dashArray();
    [pointers-cpp]

  3. An out argument of a function should be passed by reference except rare cases where it is optional in which case it should be passed by pointer.

    Right:

    void MyClass::getSomeValue(OutArgumentType& outArgument) const { outArgument = m_value; } void MyClass::doSomething(OutArgumentType* outArgument) const { doSomething(); if (outArgument) *outArgument = m_value; }

    Wrong:

    void MyClass::getSomeValue(OutArgumentType* outArgument) const { *outArgument = m_value; }
    [pointers-out-argument]

#include Statements

  1. All implementation files must #include "config.h" first. Header files should never include "config.h".

    Right:

    // RenderLayer.h #include "Node.h" #include "RenderObject.h" #include "RenderView.h"

    Wrong:

    // RenderLayer.h #include "config.h" #include "RenderObject.h" #include "RenderView.h" #include "Node.h"
    [include-config-h]

  2. All implementation files must #include the primary header second, just after "config.h". So for example, Node.cpp should include Node.h first, before other files. This guarantees that each header's completeness is tested. This also assures that each header can be compiled without requiring any other header files be included first. [include-primary]

  3. Other #include statements should be in sorted order (case sensitive, as done by the command-line sort tool or the Xcode sort selection command). Don't bother to organize them in a logical order.

    Right:

    // HTMLDivElement.cpp #include "config.h" #include "HTMLDivElement.h" #include "Attribute.h" #include "HTMLElement.h" #include "QualifiedName.h"

    Wrong:

    // HTMLDivElement.cpp #include "HTMLElement.h" #include "HTMLDivElement.h" #include "QualifiedName.h" #include "Attribute.h"
    [include-others]

  4. Includes of system headers must come after includes of other headers. This happens to also be checked and ensured by alphabetical order, as < comes after ".

    Right:

    // ConnectionQt.cpp #include "ArgumentEncoder.h" #include "ProcessLauncher.h" #include "WebPageProxyMessageKinds.h" #include "WorkItem.h" #include <QApplication> #include <QLocalServer> #include <QLocalSocket>

    Wrong:

    // ConnectionQt.cpp #include "ArgumentEncoder.h" #include "ProcessLauncher.h" #include <QApplication> #include <QLocalServer> #include <QLocalSocket> #include "WebPageProxyMessageKinds.h" #include "WorkItem.h"
    [include-system]

  5. Includes that target files inside Source/ should use double quotes ("") instead of angle brackets (<>).

    Right:
    #include "wtf/text/WTFString.h"

    Wrong:

    #include <wtf/text/WTFString.h>
    [include-double-quotes]

"using" Statements

  1. In header files, do not use "using" statements in namespace (or global) scope.

    Right:

    // wtf/Vector.h namespace WTF { class VectorBuffer { using std::min; ... }; } // namespace WTF

    Wrong:

    // wtf/Vector.h namespace WTF { using std::min; class VectorBuffer { ... }; } // namespace WTF
    [using-in-headers]

  2. In header files in the WTF sub-library, however, it is acceptable to use "using" declarations at the end of the file to import one or more names in the WTF namespace into the global scope.

    Right:

    // wtf/Vector.h namespace WTF { } // namespace WTF using WTF::Vector;

    Wrong:

    // wtf/Vector.h namespace WTF { } // namespace WTF using namespace WTF;

    Wrong:

    // runtime/JSObject.h namespace WTF { } // namespace WTF using WTF::PlacementNewAdopt;
    [using-wtf]

  3. In C++ implementation files, do not use "using" declarations of any kind to import names in the standard template library. Directly qualify the names at the point they're used instead.

    Right:

    // HTMLBaseElement.cpp namespace blink { std::swap(a, b); c = std::numeric_limits<int>::max() } // namespace blink

    Wrong:

    // HTMLBaseElement.cpp using std::swap; namespace blink { swap(a, b); } // namespace blink

    Wrong:

    // HTMLBaseElement.cpp using namespace std; namespace blink { swap(a, b); } // namespace blink
    [using-in-cpp]

  4. In implementation files, if a "using namespace" statement is for a nested namespace whose parent namespace is defined in the file, put the statement inside that namespace definition.

    Right:

    // HTMLBaseElement.cpp namespace blink { using namespace HTMLNames; } // namespace blink

    Wrong:

    // HTMLBaseElement.cpp using namespace blink::HTMLNames; namespace blink { } // namespace blink
    [using-nested-namespaces]

  5. In implementation files, put all other "using" statements at the beginning of the file, before any namespace definitions and after any "include" statements.

    Right:

    // HTMLSelectElement.cpp using namespace other; namespace blink { } // namespace blink

    Wrong:

    // HTMLSelectElement.cpp namespace blink { using namespace other; } // namespace blink
    [using-position]

Types

  1. Omit "int" when using "unsigned" modifier. Do not use "signed" modifier. Use "int" by itself instead.

    Right:

    unsigned a; int b;

    Wrong:

    unsigned int a; // Doesn't omit "int". signed b; // Uses "signed" instead of "int". signed int c; // Doesn't omit "signed".
    [types-unsigned]

Classes

  1. Use a constructor to do an implicit conversion when the argument is reasonably thought of as a type conversion and the type conversion is fast. Otherwise, use the explicit keyword or a function returning the type. This only applies to single argument constructors.

    Right:

    class LargeInt { public: LargeInt(int); ... class Vector { public: explicit Vector(int size); // Not a type conversion. PassOwnPtr<Vector> create(Array); // Costly conversion. ...

    Wrong:

    class Task { public: Task(ScriptExecutionContext*); // Not a type conversion. explicit Task(); // No arguments. explicit Task(ScriptExecutionContext*, Other); // More than one argument. ...
    [classes-explicit]

Comments

  1. Use only one space before end of line comments and in between sentences in comments.

    Right:

    f(a, b); // This explains why the function call was done. This is another sentence.

    Wrong:

    int i; // This is a comment with several spaces before it, which is a non-conforming style. double f; // This is another comment. There are two spaces before this sentence which is a non-conforming style.
    [comments-eol]

  2. Make comments look like sentences by starting with a capital letter and ending with a period (punctation). One exception may be end of line comments like this "if (x == y) // false for NaN". [comments-sentences]

  3. Use FIXME: (without attribution) to denote items that need to be addressed in the future.

    Right:

    drawJpg(); // FIXME: Make this code handle jpg in addition to the png support.

    Wrong:

    drawJpg(); // FIXME(joe): Make this code handle jpg in addition to the png support.
    
    drawJpg(); // TODO: Make this code handle jpg in addition to the png support.
    [comments-fixme]

Python

Python code should follow PEP-8, except that there is no limit on line length. This differs from Chromium coding style (and the Chromium OS Python style guidelines) in three respects:
  • no limit on line length (unlike PEP-8)
  • uses 4 space indent (like PEP-8)
  • uses function_name, method_name rather than FunctionName, MethodName (like PEP-8).
You can modify the pylintrc that is included with depot_tools (and configured for Chromium) with the following line:
cat pylintrc | sed -E -e "s/^(indent-string=)('  ')$/\\1'    '/" -e 's/^(max-line-length=)(80)$/\18000/' > ~/blink-pylintrc
...and then call it via:
pylint --rcfile=~/blink-pylintrc

Layout tests

License

Existing files in Blink use a longer header license block inherited from WebKit, however new files should follow the Chromium File Header Style:

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

To use this license block you must make sure you have completed the External Contributor Checklist.

License for this document

This page began as the WebKit Coding Style Guidelines, Licensed under BSD:

BSD License

Copyright (C) 2009 Apple Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

References


Comments