coding-style.qdoc 42.5 KB
Newer Older
Leena Miettinen's avatar
Leena Miettinen committed
1 2
/****************************************************************************
**
3
** Copyright (c) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
Leena Miettinen's avatar
Leena Miettinen committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator
Leena Miettinen's avatar
Leena Miettinen committed
7 8 9 10 11 12 13 14 15 16 17 18
**
**
** GNU Free Documentation License
**
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of this
** file.
**
**
****************************************************************************/

19
/*!
Leena Miettinen's avatar
Leena Miettinen committed
20
    \previouspage qtcreator-ui-text.html
21
    \page coding-style.html
22
    \nextpage qtcreator-api.html
23

24
    \title Qt Creator Coding Rules
25

26
    \note This document is work in progress.
27

28 29
    The coding rules aim to guide Qt Creator developers, to help them write
    understandable and maintainable code, and to minimize confusion and surprises.
30

31 32
    As usual, rules are not set in stone. If you have a good reason to break one,
    do so. But first make sure that at least some other developers agree with you.
33

34 35 36 37
    To contribute to the main Qt Creator source, you should comply to the
    following rules:

    \list
Tobias Hunger's avatar
Tobias Hunger committed
38
        \li The most important rule is: KISS (keep it short and simple). Always
39 40
            choose the simpler implementation option over the more complicated one.
            This makes maintenance a lot easier.
Tobias Hunger's avatar
Tobias Hunger committed
41
        \li Write good C++ code. That is, readable, well commented when necessary,
42
            and object-oriented.
Tobias Hunger's avatar
Tobias Hunger committed
43
        \li Take advantage of Qt. Do not re-invent the wheel. Think about which parts
44 45
            of your code are generic enough that they might be incorporated into
            Qt instead of Qt Creator.
Tobias Hunger's avatar
Tobias Hunger committed
46
        \li Adapt the code to the existing structures in Qt Creator.
47 48
            If you have improvement ideas, discuss them with other developers
            before writing the code.
Tobias Hunger's avatar
Tobias Hunger committed
49
        \li Follow the guidelines in \l{Code Constructs}, \l{Formatting}, and
50
            \l{Patterns and Practices}.
Tobias Hunger's avatar
Tobias Hunger committed
51
        \li Document interfaces. Right now we use qdoc, but changing to doxygen
52 53
            is being considered.
        \endlist
54 55


56
    \section1 Submitting Code
57

Eike Ziller's avatar
Eike Ziller committed
58
    To submit code to Qt Creator, you must understand the tools and mechanics as well as
59
    the philosophy behind Qt development. For more information about how to set up
Eike Ziller's avatar
Eike Ziller committed
60 61 62
    the development environment for working on Qt Creator and how to submit code
    and documentation for inclusion, see
    \l{http://wiki.qt-project.org/index.php/Main_Page}{Guidelines for Contributions to the Qt Project}.
63

64
    \section1 Binary and Source Compatibility
65

66 67 68 69 70
    The following list describes how the releases are numbered and defines
    \e {binary compatibility} and \e {source code compatibility} between
    releases:

    \list
71 72
        \li \QC 3.0.0 is a \e {major release}, \QC 3.1.0 is a \e {minor
            release}, and \QC 3.1.3 is a \e {patch release}.
Tobias Hunger's avatar
Tobias Hunger committed
73
        \li \e {Backward binary compatibility} means that code linked to an
74
            earlier version of the library still works.
Tobias Hunger's avatar
Tobias Hunger committed
75
        \li \e {Forward binary compatibility} means that code linked to a
76
            newer version of the library works with an older library.
Tobias Hunger's avatar
Tobias Hunger committed
77
        \li \e {Source code compatibility} means that code compiles without
78 79 80
            modification.
        \endlist

81
    We do not currently guarantee binary nor source code
82
    compatibility between major releases and minor releases.
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    However, we try to preserve backward binary compatibility and
    backward source code compatibility for patch releases within the same minor release:
    \list
        \li Soft API freeze: Starting shortly after the beta release of a minor release,
            we start keeping backward source code compatibility within that minor release,
            including its patch releases. This means that from that point, code that uses \QC API will
            compile against the API of all coming versions of this minor release, including its
            patch releases. There still might be occasional exceptions to this rule, which should
            be properly communicated.
        \li Hard API freeze: Starting with the release candidate of a minor release,
            we keep backward source code compatibility within that minor release, including its
            patch releases. We also start keeping backward binary compatibility, with the exception
            that this will not be reflected in the plugins' compatVersion setting. So, \QC plugins
            written against the release candidate will not actually load in the final release or
            later versions, even though the binary compatibility of the libraries would
            theoretically allow for it. See the section about plugin specs below.
        \li Hard ABI freeze: Starting with the final release of a minor release,
            we keep backward source code and binary compatibility for this release and all its
            patch releases.
    \endlist
104

105
    For preserving backward compatibility:
106
    \list
107
        \li Do not add or remove any public API (for example global functions,
108 109 110
            public/protected/private member functions).
        \li Do not reimplement functions (not even inlines,
            nor protected or private functions).
Tobias Hunger's avatar
Tobias Hunger committed
111
        \li Check
Eike Ziller's avatar
Eike Ziller committed
112
            \l {http://wiki.qt-project.org/index.php/Binary_Compatibility_Workarounds}{Binary Compatibility Workarounds}
113
            for ways to preserve binary compatibility.
114
    \endlist
115

116 117
    For more information on binary compatibility, see
    \l{http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++}{Binary Compatibility Issues With C++}.
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    From the viewpoint of \l{Plugin Specifications} this means that
    \list
        \li \QC plugins in patch releases will have the minor release as \c {compatVersion}. For
            example the plugins from version 3.1.2 will have \c {compatVersion="3.1.0"}.
        \li Pre-releases of the minor release, including the release candidate,
            will still have themselves as the \c {compatVersion}, meaning that plugins compiled
            against the final release will not load in the pre-releases.
        \li \QC plugin developers can decide if their plugin requires a certain patch release
            (or later) of other \QC plugins, or if they work with all patch releases of this minor
            version, by setting the corresponding \c {version} when declaring the dependency on
            the other plugin. The default for \QC plugins provided by the Qt Project is to require
            the latest patch release.
    \endlist

    For example, the \c {Find} plugin in \QC 3.1 beta (internal version number 3.0.82) will have
    \code
        <plugin name="Find" version="3.0.82" compatVersion="3.0.82">
          <dependencyList>
            <dependency name="Core" version="3.0.82"/>
            ....
    \endcode
    The \c {Find} plugin in \QC 3.1.0 final will have
    \code
        <plugin name="Find" version="3.1.0" compatVersion="3.1.0">
          <dependencyList>
            <dependency name="Core" version="3.1.0"/>
            ....
    \endcode
    The \c {Find} plugin in \QC 3.1.1 patch release will have version 3.1.1, will be
    backward binary compatible with \c {Find} plugin version 3.1.0 (\c {compatVersion="3.1.0"}),
    and will require a \c {Core} plugin that is binary backward compatible with \c {Core}
    plugin version 3.1.1:
    \code
        <plugin name="Find" version="3.1.1" compatVersion="3.1.0">
          <dependencyList>
            <dependency name="Core" version="3.1.1"/>
            ....
    \endcode

158
    \section1 Code Constructs
159

160 161 162
    Follow the guidelines for code constructs to make the code faster and
    clearer. In addition, the guidelines allow you to take advantage of the strong
    type checking in C++.
163

164
    \list
Tobias Hunger's avatar
Tobias Hunger committed
165
        \li Prefer preincrement to postincrement whenever possible.
166 167 168
            Preincrement is potentially faster than postincrement. Just
            think about the obvious implementations of pre/post-increment. This
            rule applies to decrement too:
169

170 171 172
            \code
            ++T;
            --U;
173

174
            -NOT-
175

176 177 178
            T++;
            U--;
            \endcode
179

Tobias Hunger's avatar
Tobias Hunger committed
180
        \li Try to minimize evaluation of the same code over and over. This is
181
            aimed especially at loops:
182

183
            \code
184

185 186 187 188
            Container::iterator end = large.end();
            for (Container::iterator it = large.begin(); it != end; ++it) {
                    ...;
            }
189

190
            -NOT-
191

192 193 194 195 196
            for (Container::iterator it = large.begin();
                 it != large.end(); ++it) {
                    ...;
            }
            \endcode
hjk's avatar
hjk committed
197 198


Tobias Hunger's avatar
Tobias Hunger committed
199
        \li You can use the Qt \c foreach loop in non-time-critical code with a Qt
200 201
            container. It is a nice way to keep line noise down and to give the
            loop variable a proper name:
hjk's avatar
hjk committed
202

203 204 205
            \code
                foreach (QWidget *widget, container)
                    doSomething(widget);
206

207
                -NOT-
hjk's avatar
hjk committed
208

209 210 211 212
                Container::iterator end = container.end();
                for (Container::iterator it = container.begin(); it != end; ++it)
                    doSomething(*it);
            \endcode
213

214 215
            Make the loop variable const, if possible. This might prevent
            unnecessary detaching of shared data:
hjk's avatar
hjk committed
216

217 218 219
            \code
                foreach (const QString &name, someListOfNames)
                    doSomething(name);
hjk's avatar
hjk committed
220

221
                - NOT -
222

223 224 225
                foreach (QString name, someListOfNames)
                    doSomething(name);
            \endcode
226

227
        \endlist
228

229
    \section1 Formatting
230

231
    \section2 Capitalizing Identifiers
232

233
    Use \l{http://en.wikipedia.org/wiki/CamelCase}{camel case} in identifiers.
234

235
    Capitalize the first word in an identifier as follows:
236

237
    \list
Tobias Hunger's avatar
Tobias Hunger committed
238 239 240 241
        \li Class names begin with a capital letter.
        \li Function names begin with a lower case letter.
        \li Variable names begin with a lower case letter.
        \li Enum names and values begin with a capital letter. Enum values
242 243 244 245 246 247
            contain some part of the name of the enum type.
    \endlist

    \section2 Whitespace

    \list
Tobias Hunger's avatar
Tobias Hunger committed
248 249 250
        \li Use four spaces for indentation, no tabs.
        \li Use blank lines to group statements together where suited.
        \li Always use only one blank line.
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    \endlist

    \section3 Pointers and References

    For pointers or references, always use a single space before an asterisk (*)
    or an ampersand (&), but never after.
    Avoid C-style casts when possible:

    \code
    char *blockOfMemory = (char *)malloc(data.size());
    char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));

    -NOT-

    char* blockOfMemory = (char* ) malloc(data.size());
    \endcode

    Of course, in this particulare case, using \c new might be an even better
    option.

    \section3  Operator Names and Parentheses

    Do not use spaces between operator names and function names. The equation
    marks (==) are a part of the function name, and therefore, spaces make the
    declaration look like an expression:

    \code
    operator==(type)

    -NOT-

    operator == (type)
    \endcode

    \section3 Function Names and Parentheses

    Do not use spaces between function names and parentheses:

    \code
    void mangle()

    -NOT-

    void mangle ()
    \endcode

    \section3 Keywords

    Always use a single space after a keyword, and before a curly brace:

    \code
    if (foo) {
    }

    -NOT-
306

307 308
    if(foo){
    }
309
    \endcode
310

hjk's avatar
hjk committed
311 312 313 314 315
    \section3 Comments

    In general, put one space after "//". To align text in multiline
    comments, you can insert multiple spaces.

316 317 318 319 320 321 322
    \section2 Braces

    As a base rule, place the left curly brace on the same line as the
    start of the statement:

    \code
    if (codec) {
323 324
    }

325
    -NOT-
326 327 328 329

    if (codec)
    {
    }
330
    \endcode
331

332 333
    Exception: Function implementations and class declarations always have
    the left brace in the beginning of a line:
334

335
    \code
336 337 338 339 340 341 342 343
    static void foo(int g)
    {
        qDebug("foo: %i", g);
    }

    class Moo
    {
    };
344 345 346 347 348 349 350 351 352 353 354 355 356 357
    \endcode

    Use curly braces when the body of a conditional statement contains more
    than one line, and also if a single line statement is somewhat complex.
    Otherwise, omit them:

    \code
    if (address.isEmpty())
        return false;

    for (int i = 0; i < 10; ++i)
        qDebug("%i", i);

    -NOT-
358 359 360 361 362 363 364 365

    if (address.isEmpty()) {
        return false;
    }

    for (int i = 0; i < 10; ++i) {
        qDebug("%i", i);
    }
366
    \endcode
367

368 369
    Exception 1: Use braces also if the parent statement covers several
    lines or if it wraps:
370

371
    \code
372 373
    if (address.isEmpty()
            || !isValid()
Leena Miettinen's avatar
Leena Miettinen committed
374
            || !codec) {
375
        return false;
Leena Miettinen's avatar
Leena Miettinen committed
376
    }
377
    \endcode
378

379
    \note This could be re-written as:
380

381
    \code
382 383 384 385 386 387 388 389
    if (address.isEmpty())
        return false;

    if (!isValid())
        return false;

    if (!codec)
        return false;
390
    \endcode
391

392 393 394 395 396
    Exception 2: Use braces also in if-then-else blocks where either the
    if-code or the else-code covers several lines:

    \code
    if (address.isEmpty()) {
397
        --it;
398
    } else {
399 400 401 402
        qDebug("%s", qPrintable(address));
        ++it;
    }

403 404 405
    -NOT-

    if (address.isEmpty())
406
        --it;
407
    else {
408 409 410
        qDebug("%s", qPrintable(address));
        ++it;
    }
411
    \endcode
412

413 414
    \code
    if (a) {
415 416 417 418
        if (b)
            ...
        else
            ...
419
    }
420

421 422 423
    -NOT-

    if (a)
424 425 426 427
        if (b)
            ...
        else
            ...
428
    \endcode
429

430
    Use curly braces when the body of a conditional statement is empty:
431

432
    \code
433 434
    while (a) {}

435
    -NOT-
436

437 438 439 440 441 442
    while (a);
    \endcode

    \section2 Parentheses

    Use parentheses to group expressions:
443

444
    \code
445 446
    if ((a && b) || c)

447 448 449 450
    -NOT-

    if (a && b || c)
    \endcode
451

452
    \code
453 454
    (a + b) & c

455
    -NOT-
456

457 458
    a + b & c
    \endcode
459

460
    \section2 Line Breaks
461

462
    \list
Tobias Hunger's avatar
Tobias Hunger committed
463 464 465 466
        \li Keep lines shorter than 100 characters.
        \li Insert line breaks if necessary.
        \li Commas go at the end of a broken line.
        \li Operators start at the beginning of the new line.
467 468 469 470 471
            \code
            if (longExpression
                || otherLongExpression
                || otherOtherLongExpression) {
            }
472

473
            -NOT-
474

475 476 477 478 479 480
            if (longExpression ||
                otherLongExpression ||
                otherOtherLongExpression) {
            }
            \endcode
    \endlist
481

482
    \section2 Declarations
483

484
    \list
Tobias Hunger's avatar
Tobias Hunger committed
485
        \li Use this order for the access sections of your class: public,
486 487 488
            protected, private. The public section is interesting for every
            user of the class. The private section is only of interest for the
            implementors of the class (you).
489

Tobias Hunger's avatar
Tobias Hunger committed
490
        \li Avoid declaring global objects in the declaration file of the class.
491
            If the same variable is used for all objects, use a static member.
492

Tobias Hunger's avatar
Tobias Hunger committed
493
        \li Use \c{class} instead of \c{struct}. Some compilers mangle that
494 495
            difference into the symbol names and spit out warnings if a struct
            declaration is followed by a class definition. To avoid ongoing
Sergio Ahumada's avatar
Sergio Ahumada committed
496
            changes from one to the other we declare \c{class} the preferred way.
497

498
    \endlist
499

500
    \section3 Declaring Variables
501

502
    \list
Tobias Hunger's avatar
Tobias Hunger committed
503
        \li Avoid global variables of class type to rule out initialization order problems.
504
            Consider using \c Q_GLOBAL_STATIC if they cannot be avoided.
Tobias Hunger's avatar
Tobias Hunger committed
505
        \li Declare global string literals as
506 507 508
            \code
            const char aString[] = "Hello";
            \endcode
Tobias Hunger's avatar
Tobias Hunger committed
509
        \li Avoid short names (such as, a, rbarr, nughdeget) whenever possible.
510 511
            Use single-character variable names only for counters and
            temporaries, where the purpose of the variable is obvious.
Tobias Hunger's avatar
Tobias Hunger committed
512
        \li Declare each variable on a separate line:
513 514 515 516 517
            \code
            QString a = "Joe";
            QString b = "Foo";

            -NOT-
518

519 520
            QString a = "Joe", b = "Foo";
            \endcode
521

522 523 524 525 526 527 528 529 530 531
            \note \c{QString a = "Joe"} formally calls a copy constructor on a
            temporary that is constructed from a string literal. Therefore, it is
            potentially more expensive than direct construction by
            \c {QString a("Joe")}. However, the compiler is allowed to elide the
            copy (even if this has side effects), and modern compilers typically do
            so. Given these equal costs, Qt Creator code favours the '=' idiom as
            it is in
            line with the traditional C-style initialization, it cannot be
            mistaken as function declaration, and it reduces the level of nested
            parantheses in more initializations.
532

Tobias Hunger's avatar
Tobias Hunger committed
533
        \li Avoid abbreviations:
534

535 536 537 538 539
            \code
            int height;
            int width;
            char *nameOfThis;
            char *nameOfThat;
540

541 542 543 544 545
            -NOT-

            int a, b;
            char *c, *d;
            \endcode
con's avatar
con committed
546

Tobias Hunger's avatar
Tobias Hunger committed
547
        \li Wait with declaring a variable until it is needed. This is especially
548 549
            important when initialization is done at the same time.
    \endlist
con's avatar
con committed
550

hjk's avatar
hjk committed
551 552 553
    \section2 Namespaces

    \list
554
        \li Put the left curly brace on the same line as the \c namespace keyword.
Tobias Hunger's avatar
Tobias Hunger committed
555 556 557
        \li Do not indent declarations or definitions inside.
        \li Optional, but recommended if the namespaces spans more than a few lines:
            Add a comment after the right curly brace repeating the namespace.
hjk's avatar
hjk committed
558 559 560 561 562 563 564 565 566

        \code
        namespace MyPlugin {

        void someFunction() { ... }

        }  // namespace MyPlugin
        \endcode

Tobias Hunger's avatar
Tobias Hunger committed
567 568
        \li As an exception, if there is only a single class declaration inside
            the namespace, all can go on a single line:
hjk's avatar
hjk committed
569 570 571
        \code
        namespace MyPlugin { class MyClass; }
        \endcode
hjk's avatar
hjk committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635

        \li Do not use using-directives in header files.

        \li Do not rely on using-directives when defining classes and
        functions, instead define it in a properly named declarative region.

        \li Do not rely on using-directives when accessing global functions.

        \li In other cases, you are encouraged to use using-directives,
        as they help you avoid cluttering the code. Prefer putting all
        using-directives near the top of the file, after all includes.

        \code
        [in foo.cpp]
        ...
        #include "foos.h"
        ...
        #include <utils/filename.h>
        ...
        using namespace Utils;

        namespace Foo {
        namespace Internal {

        void SomeThing::bar()
        {
            FileName f;              // or Utils::FileName f
            ...
        }
        ...
        } // namespace Internal      // or only // Internal
        } // namespace Foo           // or only // Foo

        -NOT-

        [in foo.h]
        ...
        using namespace Utils;       // Wrong: no using-directives in headers

        class SomeThing
        {
            ...
        };

        -NOT-

        [in foo.cpp]
        ...
        using namespace Utils;

        #include "bar.h"             // Wrong: #include after using-directive

        -NOT-

        [in foo.cpp]
        ...
        using namepace Foo;

        void SomeThing::bar()        // Wrong if Something is in namespace Foo
        {
            ...
        }
        \endcode

hjk's avatar
hjk committed
636 637
    \endlist

638
    \section1 Patterns and Practices
con's avatar
con committed
639

640
    \target coding-rules-namespacing
Eike Ziller's avatar
Eike Ziller committed
641 642
    \section2 Namespacing

Eike Ziller's avatar
Eike Ziller committed
643
    Read \l {http://wiki.qt-project.org/index.php/Qt_In_Namespace}{Qt In Namespace}
Eike Ziller's avatar
Eike Ziller committed
644 645 646 647
    and keep in mind that all of Qt Creator is \e{namespace aware} code.

    The namespacing policy within Qt Creator is as follows:
    \list
Tobias Hunger's avatar
Tobias Hunger committed
648 649 650 651 652
        \li Classes/Symbols of a library or plugin that are exported for use of
            other libraries or plugins are in a namespace specific to that
            library/plugin, e.g. \c{MyPlugin}.
        \li Classes/Symbols of a library or plugin that are not exported are in
            an additional \c{Internal} namespace, e.g. \c{MyPlugin::Internal}.
Eike Ziller's avatar
Eike Ziller committed
653 654
    \endlist

655
    \section2 Passing File Names
con's avatar
con committed
656

657 658 659 660
    Qt Creator API expects file names in portable format, that is, with slashes (/)
    instead of backslashes (\\) even on Windows. To pass a file name from the user
    to the API, convert it with QDir::fromNativeSeparators first. To present a file
    name to the user, convert it back to native format with
661 662
    QDir::toNativeSeparators. Consider using Utils::FileName::fromUserInput(QString)
    and Utils::FileName::toUserOutput() for these tasks.
con's avatar
con committed
663

664 665
    Use Utils::FileName when comparing file names, because that takes case sensitivity into account.
    Also make sure that you compare clean paths (QDir::cleanPath()).
666

667
    \section2 Plugin Extension Points
con's avatar
con committed
668

669 670 671 672 673 674 675
    A plugin extension point is an interface that is provided by one plugin
    to be implemented by others. The plugin then retrieves all
    implementations of the interface and uses them. That is, they \e extend the
    functionality of the plugin. Typically, the
    implementations of the interface are put into the global object pool
    during plugin initialization, and the plugin retrieves them from the
    object pool at the end of plugin initialization.
con's avatar
con committed
676

677 678 679 680 681 682 683
    For example, the Find plugin provides the FindFilter interface for
    other plugins to implement. With the FindFilter interface, additional search
    scopes can be added, that appear in the \gui {Advanced Search} dialog. The
    Find plugin retrieves all FindFilter implementations from the global
    object pool and presents them in the dialog. The plugin forwards the
    actual search request to the correct FindFilter implementation, which
    then performs the search.
con's avatar
con committed
684

685
    \section2 Using the Global Object Pool
686

687 688 689 690 691 692 693 694 695 696 697 698
    You can add objects to the global object pool via
    \l{ExtensionSystem::PluginManager::addObject()}, and retrieve objects
    of a specific type again via
    \l{ExtensionSystem::PluginManager::getObjects()}.  This should mostly
    be used for implementations of \l{Plugin Extension Points}.

    \note Do not put a singleton into the pool, and do not retrieve
    it from there. Use the singleton pattern instead.

    \section2 C++ Features

    \list
Tobias Hunger's avatar
Tobias Hunger committed
699
        \li Do not use exceptions, unless you know what you do.
700

Tobias Hunger's avatar
Tobias Hunger committed
701
        \li Do not use RTTI (Run-Time Type Information; that is, the typeinfo
702 703
            struct, the dynamic_cast or the typeid operators, including throwing
            exceptions), unless you know what you do.
704

Tobias Hunger's avatar
Tobias Hunger committed
705
        \li Do not use virtual inheritance, unless you know what you do.
706

Tobias Hunger's avatar
Tobias Hunger committed
707
        \li Use templates wisely, not just because you can.
708 709 710 711

            Hint: Use the compile autotest to see whether a C++ feature is supported
            by all compilers in the test farm.

Tobias Hunger's avatar
Tobias Hunger committed
712
        \li All code is ASCII only (7-bit characters only, run \c {man ascii} if unsure)
713
            \list
Tobias Hunger's avatar
Tobias Hunger committed
714
                \li Rationale: We have too many locales inhouse and an unhealthy
715 716 717
                    mix of UTF-8 and Latin1 systems. Usually, characters > 127 can
                    be broken without you even knowing by clicking Save in your
                    favourite editor.
Tobias Hunger's avatar
Tobias Hunger committed
718 719
                \li For strings: Use \\nnn (where nnn is the octal representation
                    of whatever locale you want your string in) or \\xnn (where nn
720 721
                    is hexadecimal).
                    For example: QString s = QString::fromUtf8("\\213\\005");
Tobias Hunger's avatar
Tobias Hunger committed
722
              \li For umlauts in documentation, or other non-ASCII characters,
723 724 725
                  either use the qdoc \c {\unicode} command or use the relevant macro.
                  For example: \c{\uuml} for \uuml.
           \endlist
726

Tobias Hunger's avatar
Tobias Hunger committed
727
        \li Use static keywords instead of anonymous namespaces whenever possible.
728 729 730
            A name localized to the compilation unit with static is
            guaranteed to have internal linkage. For names declared in anonymous
            namespaces, the C++ standard unfortunately mandates external linkage
731 732
            (ISO/IEC 14882, 7.1.1/6, or see various discussions about this on the gcc
            mailing lists).
733
    \endlist
734

735
    \section3 Null Pointers
736

737 738
    Using a plain zero (0) for null pointer constants is always correct and
    least effort to type.
739

740 741
    \code
    void *p = 0;
742

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    -NOT-

    void *p = NULL;

    -NOT-

    void *p = '\0';

    -NOT-

    void *p = 42 - 7 * 6;
    \endcode

    \note As an exception, imported third party code as well as code
    interfacing the native APIs (src/support/os_*) can use NULL.

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
    \section2 C++11 Features

    Code should compile with Microsoft Visual Studio 2010, g++ 4.5, and Clang 3.1.

    \section3 Lambdas

    You can use lambdas with the following restrictions:

    \list
        \li You have to explicitly specify the return type, if the lambda contains more than a
            single expression. Otherwise it does not compile with VS2010.
            \code
            []() -> QString {
                Foo *foo = activeFoo();
                return foo ? foo->displayName() : QString();
            });

            -NOT-

            []() {
                Foo *foo = activeFoo();
                return foo ? foo->displayName() : QString();
            });
            \endcode

        \li If you use static functions from the class that the lambda is located in, you have to
            explicitly capture \c this. Otherwise it does not compile with g++ 4.7 and earlier.
            \code
            void Foo::something()
            {
                ...
                [this]() { Foo::someStaticFunction(); }
                ...
            }

            -NOT-

            void Foo::something()
            {
                ...
                []() { Foo::someStaticFunction(); }
                ...
            }
            \endcode
    \endlist

    Format the lambda according to the following rules:

    \list
        \li Always write parentheses for the parameter list, even if the function does not take
            parameters.
            \code
            []() { doSomething(); }

            -NOT

            [] { doSomething(); }
            \endcode

        \li Place the capture-list, parameter list, return type, and opening brace on the first line,
            the body indented on the following lines, and the closing brace on a new line.
            \code
            []() -> bool {
                something();
                return isSomethingElse();
            }

            -NOT-

            []() -> bool { something();
            somethingElse(); }
            \endcode

        \li Place a closing parenthesis and semicolon of an enclosing function call on the same line
            as the closing brace of the lambda.
            \code
            foo([]() {
                something();
            });
            \endcode

        \li If you are using a lambda in an 'if' statement, start the lambda on a new line, to
            avoid confusion between the opening brace for the lambda and the opening brace for the
            'if' statement.
            \code
            if (anyOf(fooList,
                    [](Foo foo) {
                        return foo.isGreat();
                    }) {
                return;
            }

            -NOT-

            if (anyOf(fooList, [](Foo foo) {
                        return foo.isGreat();
                    }) {
                return;
            }
            \endcode

        \li Optionally, place the lambda completely on one line if it fits.
            \code
            foo([]() { return true; });

            if (foo([]() { return true; })) {
                ...
            }
            \endcode

    \endlist

    \section3 \c auto Keyword

    Optionally, you can use the \c auto keyword in the following cases. If in doubt,
    for example if using \c auto could make the code less readable, do not use \c auto.
    Keep in mind that code is read much more often than written.

    \list
        \li When it avoids repetition of a type in the same statement.
            \code
            auto something = new MyCustomType;
            auto keyEvent = static_cast<QKeyEvent *>(event);
            auto myList = QStringList() << QLatin1String(“FooThing”) << QLatin1String(“BarThing”);
            \endcode

        \li When assigning iterator types.
            \code
            auto it = myList.const_iterator();
            \endcode

    \endlist

892 893 894
    \section2 Using QObject

    \list
895 896 897 898
        \li Remember to add the Q_OBJECT macro to QObject subclasses that rely
            on the meta object system. Meta object system related features are
            the definition of signals and slots, the use of \c{qobject_cast<>},
            and others. See also \l{Casting}.
899 900 901 902 903 904
        \li Prefer Qt5-style \c{connect()} calls over Qt4-style.
        \li When using Qt4-style \c{connect()} calls, normalize the arguments
            for signals and slots inside connect statements to safely make
            signal and slot lookup a few cycles faster. You can use
            $QTDIR/util/normalize to normalize existing code. For more
            information, see \l{http://qt-project.org/doc/qt-4.8/qmetaobject.html#normalizedSignature}{QMetaObject::normalizedSignature}.
905 906 907 908 909 910 911 912 913 914
    \endlist

    \section2 File Headers

    If you create a new file, the top of the file should include a
    header comment equal to the one found in other source files of Qt Creator.

    \section2 Including Headers

    \list
Tobias Hunger's avatar
Tobias Hunger committed
915
        \li Use the following format to include Qt headers:
Tobias Hunger's avatar
Tobias Hunger committed
916 917
            \c{#include <QWhatEver>}. Do not include the module as it might have changed between
            Qt4 and Qt5.
Tobias Hunger's avatar
Tobias Hunger committed
918
        \li Arrange includes in an order that goes from specific to generic to
919
            ensure that the headers are self-contained. For example:
920
        \list
Tobias Hunger's avatar
Tobias Hunger committed
921 922 923 924 925 926
            \li \c{#include "myclass.h"}
            \li \c{#include "otherclassinplugin.h"}
            \li \c{#include <otherplugin/someclass.h>}
            \li \c{#include <QtClass>}
            \li \c{#include <stdthing>}
            \li \c{#include <system.h>}
927
        \endlist
Tobias Hunger's avatar
Tobias Hunger committed
928
        \li Enclose headers from other plugins in square brackets (<>) rather than
929 930
            quotation marks ("") to make it easier to spot external dependencies in
            the sources.
Tobias Hunger's avatar
Tobias Hunger committed
931
        \li Add empty lines between long blocks of \e peer headers and try to
932 933 934 935 936 937
            arrange the headers in alphabetic order within a block.
    \endlist

    \section2 Casting

    \list
Tobias Hunger's avatar
Tobias Hunger committed
938
        \li Avoid C casts, prefer C++ casts (\c static_cast, \c const_cast,
939 940 941
            \c reinterpret_cast) Both \c reinterpret_cast and
            C-style casts are dangerous, but at least \c reinterpret_cast
            will not remove the const modifier.
Tobias Hunger's avatar
Tobias Hunger committed
942
        \li Do not use \c dynamic_cast, use \c {qobject_cast} for QObjects, or
943
            refactor your design, for example by introducing a \c {type()}
944
            function (see QListWidgetItem), unless you know what you do.
945 946 947 948 949
    \endlist

    \section2 Compiler and Platform-specific Issues

    \list
Tobias Hunger's avatar
Tobias Hunger committed
950
        \li Be extremely careful when using the question mark operator.
951 952 953 954 955 956 957 958
            If the returned types are not identical, some compilers generate
            code that crashes at runtime (you will not even get a compiler warning):
            \code
            QString s;
            // crash at runtime - QString vs. const char *
            return condition ? s : "nothing";
            \endcode

Tobias Hunger's avatar
Tobias Hunger committed
959
        \li Be extremely careful about alignment.
960 961 962 963 964 965 966 967 968 969 970

            Whenever a pointer is cast such that the required alignment of
            the target is increased, the resulting code might crash at runtime
            on some architectures. For example, if a \c {const char *} is cast to a
            \c {const int *}, it will crash on machines where integers have to be
            aligned at two-byte or four-byte boundaries.

            Use a union to force the compiler to align variables correctly.
            In the example below, you can be sure that all instances of
            AlignHelper are aligned at integer-boundaries:
            \code
971 972 973 974 975
            union AlignHelper
            {
                char c;
                int i;
            };
976
            \endcode
977

Tobias Hunger's avatar
Tobias Hunger committed
978
        \li Anything that has a constructor or needs to run code to be
979 980 981
            initialized cannot be used as global object in library code,
            since it is undefined when that constructor or code will be run
            (on first usage, on library load, before \c {main()} or not at all).
982

983 984 985
            Even if the execution time of the initializer is defined for
            shared libraries, you will get into trouble when moving that code
            in a plugin or if the library is compiled statically:
986

987 988
            \code
            // global scope
989

990
            -NOT-
991

992 993
            // Default constructor needs to be run to initialize x:
            static const QString x;
994

995
            -NOT-
996

997 998
            // Constructor that takes a const char * has to be run:
            static const QString y = "Hello";
999

1000
            -NOT-
1001

1002
            QString z;
1003

1004
            -NOT-
1005

1006 1007 1008
            // Call time of foo() undefined, might not be called at all:
            static const int i = foo();
            \endcode
1009

1010
            Things you can do:
1011

1012 1013 1014 1015
            \code
            // global scope
            // No constructor must be run, x set at compile time:
            static const char x[] = "someText";
1016

1017 1018
            // y will be set at compile time:
            static int y = 7;
1019

1020 1021
            // Will be initialized statically, no code being run.
            static MyStruct s = {1, 2, 3};
1022

1023 1024 1025
            // Pointers to objects are OK, no code needed to be run to
            // initialize ptr:
            static QString *ptr = 0;
1026

1027
            // Use Q_GLOBAL_STATIC to create static global objects instead:
1028

1029
            Q_GLOBAL_STATIC(QString, s)
1030

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
            void foo()
            {
                s()->append("moo");
            }
            \endcode

            \note Static objects in function scope are no problem. The constructor
            will be run the first time the function is entered. The code is not
            reentrant, though.

Tobias Hunger's avatar
Tobias Hunger committed
1041
        \li A \c char is signed or unsigned dependent on the architecture. Use signed
Sergio Ahumada's avatar
Sergio Ahumada committed
1042
            \c char or \c uchar if you explicitly want a signed or unsigned char.
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
            The following code will break on PowerPC, for example:

            \code
            // Condition is always true on platforms where the
            // default is unsigned:
            if (c >= 0) {
                ...
            }
            \endcode

Tobias Hunger's avatar
Tobias Hunger committed
1053
        \li Avoid 64-bit enum values. The AAPCS (Procedure Call Standard
1054 1055 1056
            for the ARM Architecture) embedded ABI hard codes
            all enum values to a 32-bit integer.

Tobias Hunger's avatar
Tobias Hunger committed
1057
        \li Do not mix const and non-const iterators. This will silently crash
1058 1059 1060
            on broken compilers.
            \code
            for (Container::const_iterator it = c.constBegin(); it != c.constEnd(); ++it)
1061

1062
            -NOT-
1063

1064 1065 1066
            for (Container::const_iterator it = c.begin(); it != c.end(); ++it)
            \endcode
    \endlist
1067

1068
    \section2 Esthetics
1069

1070
    \list
Tobias Hunger's avatar
Tobias Hunger committed
1071 1072 1073 1074 1075 1076
        \li Prefer enums to define const over static const int or defines.
            Enumeration values will be replaced by the compiler at compile time,
            resulting in faster code. Defines are not namespace safe.
        \li Prefer verbose argument names in headers.
            Qt Creator will show the argument names in their completion box.
            It will look better in the documentation.
1077
    \endlist
1078

1079
    \section2 Inheriting from Template or Tool Classes
1080

1081 1082
    Inheriting from template or tool classes has the following potential
    pitfalls:
1083

1084
    \list
Tobias Hunger's avatar
Tobias Hunger committed
1085 1086
        \li The destructors are not virtual, which can lead to memory leaks.
        \li The symbols are not exported (and mostly inline), which can lead to
1087
            symbol clashes.
1088 1089
    \endlist

1090 1091 1092 1093
    For example, library A has class \c {Q_EXPORT X: public QList<QVariant> {};}
    and library B has class \c {Q_EXPORT Y: public QList<QVariant> {};}.
    Suddenly, QList symbols are exported from two libraries which results in a
    clash.
1094

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

    \section2 Inheritance Versus Aggregation

    \list
        \li Use inheritance if there is a clear \e{is-a} relation.
        \li Use aggregation for re-use of orthogonal building blocks.
        \li Prefer aggregation over inheritance if there is a choice.
    \endlist


1105
    \section2 Conventions for Public Header Files
1106

1107 1108
    Our public header files have to survive the strict settings of
    some of our users. All installed headers have to follow these rules:
1109

1110
    \list
1111

Tobias Hunger's avatar
Tobias Hunger committed
1112
        \li No C style casts (\c{-Wold-style-cast}). Use \c static_cast, \c const_cast
1113 1114
            or \c reinterpret_cast, for basic types, use the constructor form:
            \c {int(a)} instead of \c {(int)a}. For more information, see \l{Casting}.
1115

Tobias Hunger's avatar
Tobias Hunger committed
1116
        \li No float comparisons (\c{-Wfloat-equal}). Use \c qFuzzyCompare to compare
1117
            values with a delta. Use \c qIsNull to check whether a float is
Sergio Ahumada's avatar
Sergio Ahumada committed
1118
            binary 0, instead of comparing it to 0.0, or, preferred, move
1119
            such code into an implementation file.
1120

1121
       \li Do not hide virtual functions in subclasses (\{-Woverloaded-virtual}).
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
           If the baseclass A has a virtual \c {int val()} and subclass B an
           overload with the same name, \c {int val(int x)}, the A \c val function
           is hidden. Use the \c using keyword to make it visible again, and
           add the following silly workaround for broken compilers:
           \code
               class B: public A
               {
               #ifdef Q_NO_USING_KEYWORD
               inline int val() { return A::val(); }
               #else
               using A::val;
               #endif
               };
           \endcode
1136

Tobias Hunger's avatar
Tobias Hunger committed
1137
        \li Do not shadow variables (\c{-Wshadow}).