1 /****************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
7 ** Contact: Nokia Corporation (info@qt.nokia.com)
10 ** GNU Free Documentation License
12 ** Alternatively, this file may be used under the terms of the GNU Free
13 ** Documentation License version 1.3 as published by the Free Software
14 ** Foundation and appearing in the file included in the packaging of this
17 ** If you have questions regarding the use of this file, please contact
18 ** Nokia at qt-info@nokia.com.
20 ****************************************************************************/
24 \contentspage{index.html}{Qt Creator}
25 \page coding-style.html
27 \title Qt Creator Coding Rules
29 \note This document is work in progress.
31 The coding rules aim to guide Qt Creator developers, to help them write
32 understandable and maintainable code, and to minimize confusion and surprises.
34 As usual, rules are not set in stone. If you have a good reason to break one,
35 do so. But first make sure that at least some other developers agree with you.
37 To contribute to the main Qt Creator source, you should comply to the
41 \o The most important rule is: KISS (keep it short and simple). Always
42 choose the simpler implementation option over the more complicated one.
43 This makes maintenance a lot easier.
44 \o Write good C++ code. That is, readable, well commented when necessary,
46 \o Take advantage of Qt. Do not re-invent the wheel. Think about which parts
47 of your code are generic enough that they might be incorporated into
48 Qt instead of Qt Creator.
49 \o Adapt the code to the existing structures in Qt Creator.
50 If you have improvement ideas, discuss them with other developers
51 before writing the code.
52 \o Follow the guidelines in \l{Code Constructs}, \l{Formatting}, and
53 \l{Patterns and Practices}.
54 \o Document interfaces. Right now we use qdoc, but changing to doxygen
59 \section1 Submitting Code
61 To submit code to Qt, you must understand the tools and mechanics as well as
62 the philosophy behind Qt development. For more information about how to set up
63 the development environment for working on a Qt library and how to submit code
64 and documentation for inclusion to Qt, see
65 \l{http://qt.gitorious.org/qt/pages/QtContributionGuidelines}{Qt Contribution Guidelines}.
67 \section1 Binary and Source Compatibility
69 The following list describes how the releases are numbered and defines
70 \e {binary compatibility} and \e {source code compatibility} between
74 \o Qt Creator 2.0.0 is a \e {major release}, Qt Creator 2.1.0 is a \e {minor
75 release}, and Qt Creator 2.1.3 is a \e {patch release}.
76 \o \e {Backward binary compatibility} means that code linked to an
77 earlier version of the library still works.
78 \o \e {Forward binary compatibility} means that code linked to a
79 newer version of the library works with an older library.
80 \o \e {Source code compatibility} means that code compiles without
84 We do not currently guarantee API nor ABI
85 (\l{http://en.wikipedia.org/wiki/Application_binary_interface}{application binary interface})
86 compatibility between major releases.
88 However, we try to preserve compatibility between minor and patch releases,
92 \o Preserve backward binary compatibility and backward source code
93 compatibility in minor releases.
94 \o Preserve backward and forward binary compatibility and forward and
95 backward source code compatibility in patch releases:
97 \o Do not add or remove any public API (e.g. global functions,x
98 public/protected/private methods).
99 \o Do not reimplement methods (not even inlines,
100 nor protected or private methods).
102 \l {http://developer.qt.nokia.com/wiki/Binary_Compatibility_Workarounds}{Binary Compatibility Workarounds}
103 for ways to preserve binary compatibility.
107 \note This is not yet mandatory.
108 For more information on binary compatibility, see
109 \l{http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++}{Binary Compatibility Issues With C++}.
111 \section1 Code Constructs
113 Follow the guidelines for code constructs to make the code faster and
114 clearer. In addition, the guidelines allow you to take advantage of the strong
115 type checking in C++.
118 \o Prefer preincrement to postincrement whenever possible.
119 Preincrement is potentially faster than postincrement. Just
120 think about the obvious implementations of pre/post-increment. This
121 rule applies to decrement too:
133 \o Try to minimize evaluation of the same code over and over. This is
134 aimed especially at loops:
138 Container::iterator end = large.end();
139 for (Container::iterator it = large.begin(); it != end; ++it) {
145 for (Container::iterator it = large.begin();
146 it != large.end(); ++it) {
152 \o You can use the Qt \c foreach loop in non-time-critical code with a Qt
153 container. It is a nice way to keep line noise down and to give the
154 loop variable a proper name:
157 foreach (QWidget *widget, container)
162 Container::iterator end = container.end();
163 for (Container::iterator it = container.begin(); it != end; ++it)
167 Make the loop variable const, if possible. This might prevent
168 unnecessary detaching of shared data:
171 foreach (const QString &name, someListOfNames)
176 foreach (QString name, someListOfNames)
184 \section2 Capitalizing Identifiers
186 Use \l{http://en.wikipedia.org/wiki/CamelCase}{camel case} in identifiers.
188 Capitalize the first word in an identifier as follows:
191 \o Class names begin with a capital letter.
192 \o Function names begin with a lower case letter.
193 \o Variable names begin with a lower case letter.
194 \o Enum names begin with a capital letter. Enum values use lower case and
195 contain some part of the name of the enum type.
201 \o Use four spaces for indentation, no tabs.
202 \o Use blank lines to group statements together where suited.
203 \o Always use only one blank line.
206 \section3 Pointers and References
208 For pointers or references, always use a single space before an asterisk (*)
209 or an ampersand (&), but never after.
210 Avoid C-style casts when possible:
213 char *blockOfMemory = (char *)malloc(data.size());
214 char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
218 char* blockOfMemory = (char* ) malloc(data.size());
221 Of course, in this particulare case, using \c new might be an even better
224 \section3 Operator Names and Parentheses
226 Do not use spaces between operator names and function names. The equation
227 marks (==) are a part of the function name, and therefore, spaces make the
228 declaration look like an expression:
238 \section3 Function Names and Parentheses
240 Do not use spaces between function names and parentheses:
252 Always use a single space after a keyword, and before a curly brace:
266 As a base rule, place the left curly brace on the same line as the
267 start of the statement:
280 Exception: Function implementations and class declarations always have
281 the left brace in the beginning of a line:
284 static void foo(int g)
286 qDebug("foo: %i", g);
294 Use curly braces when the body of a conditional statement contains more
295 than one line, and also if a single line statement is somewhat complex.
296 Otherwise, omit them:
299 if (address.isEmpty())
302 for (int i = 0; i < 10; ++i)
307 if (address.isEmpty()) {
311 for (int i = 0; i < 10; ++i) {
316 Exception 1: Use braces also if the parent statement covers several
317 lines or if it wraps:
320 if (address.isEmpty()
327 \note This could be re-written as:
330 if (address.isEmpty())
340 Exception 2: Use braces also in if-then-else blocks where either the
341 if-code or the else-code covers several lines:
344 if (address.isEmpty()) {
347 qDebug("%s", qPrintable(address));
353 if (address.isEmpty())
356 qDebug("%s", qPrintable(address));
378 Use curly braces when the body of a conditional statement is empty:
388 \section2 Parentheses
390 Use parentheses to group expressions:
408 \section2 Line Breaks
411 \o Keep lines shorter than 100 characters.
412 \o Insert line breaks if necessary.
413 \o Commas go at the end of a broken line.
414 \o Operators start at the beginning of the new line.
417 || otherLongExpression
418 || otherOtherLongExpression) {
423 if (longExpression ||
424 otherLongExpression ||
425 otherOtherLongExpression) {
430 \section2 Declarations
433 \o Use this order for the access sections of your class: public,
434 protected, private. The public section is interesting for every
435 user of the class. The private section is only of interest for the
436 implementors of the class (you).
437 \o Avoid declaring global objects in the declaration file of the class.
438 If the same variable is used for all objects, use a static member.
441 \section3 Declaring Variables
444 \o Avoid global or static variables.
445 \o Avoid short names (such as, a, rbarr, nughdeget) whenever possible.
446 Use single-character variable names only for counters and
447 temporaries, where the purpose of the variable is obvious.
448 \o Declare each variable on a separate line:
455 QString a = "Joe", b = "Foo";
458 \note \c{QString a = "Joe"} formally calls a copy constructor on a
459 temporary that is constructed from a string literal. Therefore, it is
460 potentially more expensive than direct construction by
461 \c {QString a("Joe")}. However, the compiler is allowed to elide the
462 copy (even if this has side effects), and modern compilers typically do
463 so. Given these equal costs, Qt Creator code favours the '=' idiom as
465 line with the traditional C-style initialization, it cannot be
466 mistaken as function declaration, and it reduces the level of nested
467 parantheses in more initializations.
469 \o Avoid abbreviations:
483 \o Wait with declaring a variable until it is needed. This is especially
484 important when initialization is done at the same time.
487 \section1 Patterns and Practices
489 \section2 Passing File Names
491 Qt Creator API expects file names in portable format, that is, with slashes (/)
492 instead of backslashes (\\) even on Windows. To pass a file name from the user
493 to the API, convert it with QDir::fromNativeSeparators first. To present a file
494 name to the user, convert it back to native format with
495 QDir::toNativeSeparators.
497 When comparing file names, consider using FileManager::fixFileName which
498 makes sure that paths are clean and absolute and also takes Windows
499 case-insensitivity into account (even if it is an expensive operation).
501 \section2 Plugin Extension Points
503 A plugin extension point is an interface that is provided by one plugin
504 to be implemented by others. The plugin then retrieves all
505 implementations of the interface and uses them. That is, they \e extend the
506 functionality of the plugin. Typically, the
507 implementations of the interface are put into the global object pool
508 during plugin initialization, and the plugin retrieves them from the
509 object pool at the end of plugin initialization.
511 For example, the Find plugin provides the FindFilter interface for
512 other plugins to implement. With the FindFilter interface, additional search
513 scopes can be added, that appear in the \gui {Advanced Search} dialog. The
514 Find plugin retrieves all FindFilter implementations from the global
515 object pool and presents them in the dialog. The plugin forwards the
516 actual search request to the correct FindFilter implementation, which
517 then performs the search.
519 \section2 Using the Global Object Pool
521 You can add objects to the global object pool via
522 \l{ExtensionSystem::PluginManager::addObject()}, and retrieve objects
523 of a specific type again via
524 \l{ExtensionSystem::PluginManager::getObjects()}. This should mostly
525 be used for implementations of \l{Plugin Extension Points}.
527 \note Do not put a singleton into the pool, and do not retrieve
528 it from there. Use the singleton pattern instead.
530 \section2 C++ Features
533 \o Do not use exceptions, unless you know what you do.
534 \o Do not use RTTI (Run-Time Type Information; that is, the typeinfo
535 struct, the dynamic_cast or the typeid operators, including throwing
536 exceptions), unless you know what you do.
537 \o Use templates wisely, not just because you can.
539 Hint: Use the compile autotest to see whether a C++ feature is supported
540 by all compilers in the test farm.
542 \o All code is ASCII only (7-bit characters only, run \c {man ascii} if unsure)
544 \o Rationale: We have too many locales inhouse and an unhealthy
545 mix of UTF-8 and Latin1 systems. Usually, characters > 127 can
546 be broken without you even knowing by clicking Save in your
548 \o For strings: Use \\nnn (where nnn is the octal representation
549 of whatever locale you want your string in) or \xnn (where nn
551 For example: QString s = QString::fromUtf8("\\213\\005");
552 \o For umlauts in documentation, or other non-ASCII characters,
553 either use the qdoc \c {\unicode} command or use the relevant macro.
554 For example: \c{\uuml} for \uuml.
556 \o Use static keywords instead of anonymous namespaces whenever possible.
557 A name localized to the compilation unit with static is
558 guaranteed to have internal linkage. For names declared in anonymous
559 namespaces, the C++ standard unfortunately mandates external linkage
560 (ISO/IEC 14882, 7.1.1/6, or see various discussions about this on the gcc mailing
564 \section3 Null Pointers
566 Using a plain zero (0) for null pointer constants is always correct and
567 least effort to type.
582 void *p = 42 - 7 * 6;
585 \note As an exception, imported third party code as well as code
586 interfacing the native APIs (src/support/os_*) can use NULL.
588 \section2 Using QObject
591 \o Every QObject subclass must have a Q_OBJECT macro, even if it
592 does not have signals or slots, if it is intended to be used
593 with qobject_cast<>. See also \l{Casting}.
594 \o Normalize the arguments for signals and slots
595 (see \l{http://doc.qt.nokia.com/4.7/qmetaobject.html#normalizedSignature}{QMetaObject::normalizedSignature}
596 inside connect statements
597 to safely make signal and slot lookup a few cycles faster.
598 You can use $QTDIR/util/normalize to normalize existing code.
601 \section2 File Headers
603 If you create a new file, the top of the file should include a
604 header comment equal to the one found in other source files of Qt Creator.
606 \section2 Including Headers
609 \o Use the following format to include Qt headers:
610 \c{#include <QtCore/QWhatEver>}.
611 \o Arrange includes in an order that goes from specific to generic to
612 ensure that the headers are self-contained. For example:
614 \o \c{#include "myclass.h"}
615 \o \c{#include "otherclassinplugin.h"}
616 \o \c{#include <otherplugin/someclass.h>}
617 \o \c{#include <QtModule/QtClass>}
618 \o \c{#include <stdthing>}
619 \o \c{#include <system.h>}
621 \o Enclose headers from other plugins in square brackets (<>) rather than
622 quotation marks ("") to make it easier to spot external dependencies in
624 \o Add empty lines between long blocks of \e peer headers and try to
625 arrange the headers in alphabetic order within a block.
631 \o Avoid C casts, prefer C++ casts (\c static_cast, \c const_cast,
632 \c reinterpret_cast) Both \c reinterpret_cast and
633 C-style casts are dangerous, but at least \c reinterpret_cast
634 will not remove the const modifier.
635 \o Do not use \c dynamic_cast, use \c {qobject_cast} for QObjects, or
636 refactor your design, for example by introducing a \c {type()}
637 method (see QListWidgetItem), unless you know what you do.
640 \section2 Compiler and Platform-specific Issues
643 \o Be extremely careful when using the question mark operator.
644 If the returned types are not identical, some compilers generate
645 code that crashes at runtime (you will not even get a compiler warning):
648 // crash at runtime - QString vs. const char *
649 return condition ? s : "nothing";
652 \o Be extremely careful about alignment.
654 Whenever a pointer is cast such that the required alignment of
655 the target is increased, the resulting code might crash at runtime
656 on some architectures. For example, if a \c {const char *} is cast to a
657 \c {const int *}, it will crash on machines where integers have to be
658 aligned at two-byte or four-byte boundaries.
660 Use a union to force the compiler to align variables correctly.
661 In the example below, you can be sure that all instances of
662 AlignHelper are aligned at integer-boundaries:
671 \o Anything that has a constructor or needs to run code to be
672 initialized cannot be used as global object in library code,
673 since it is undefined when that constructor or code will be run
674 (on first usage, on library load, before \c {main()} or not at all).
676 Even if the execution time of the initializer is defined for
677 shared libraries, you will get into trouble when moving that code
678 in a plugin or if the library is compiled statically:
685 // Default constructor needs to be run to initialize x:
686 static const QString x;
690 // Constructor that takes a const char * has to be run:
691 static const QString y = "Hello";
699 // Call time of foo() undefined, might not be called at all:
700 static const int i = foo();
707 // No constructor must be run, x set at compile time:
708 static const char x[] = "someText";
710 // y will be set at compile time:
713 // Will be initialized statically, no code being run.
714 static MyStruct s = {1, 2, 3};
716 // Pointers to objects are OK, no code needed to be run to
718 static QString *ptr = 0;
720 // Use Q_GLOBAL_STATIC to create static global objects instead:
722 Q_STATIC_GLOBAL(QString, s)
730 \note Static objects in function scope are no problem. The constructor
731 will be run the first time the function is entered. The code is not
734 \o A \c char is signed or unsigned dependent on the architecture. Use signed
735 \c char or \c uchar if you explicitely want a signed or unsigned char.
736 The following code will break on PowerPC, for example:
739 // Condition is always true on platforms where the
740 // default is unsigned:
746 \o Avoid 64-bit enum values. The AAPCS (Procedure Call Standard
747 for the ARM Architecture) embedded ABI hard codes
748 all enum values to a 32-bit integer.
750 \o Do not mix const and non-const iterators. This will silently crash
753 for (Container::const_iterator it = c.constBegin(); it != c.constEnd(); ++it)
757 for (Container::const_iterator it = c.begin(); it != c.end(); ++it)
764 \o Prefer enums to define const over static const int or defines.
765 Enumeration values will be replaced by the compiler at compile time,
766 resulting in faster code. Defines are not namespace safe.
767 \o Prefer verbose argument names in headers.
768 Qt Creator will show the argument names in their completion box.
769 It will look better in the documentation.
772 \section2 Inheriting from Template or Tool Classes
774 Inheriting from template or tool classes has the following potential
778 \o The destructors are not virtual, which can lead to memory leaks.
779 \o The symbols are not exported (and mostly inline), which can lead to
783 For example, library A has class \c {Q_EXPORT X: public QList<QVariant> {};}
784 and library B has class \c {Q_EXPORT Y: public QList<QVariant> {};}.
785 Suddenly, QList symbols are exported from two libraries which results in a
788 \section2 Namespacing
790 Read \l {http://developer.qt.nokia.com/wiki/Qt_In_Namespace}{Qt In Namespace}
791 and keep in mind that all of Qt Creator is \e{namespace aware} code.
793 \section2 Conventions for Public Header Files
795 Our public header files have to survive the strict settings of
796 some of our users. All installed headers have to follow these rules:
800 \o No C style casts (\c{-Wold-style-cast}). Use \c static_cast, \c const_cast
801 or \c reinterpret_cast, for basic types, use the constructor form:
802 \c {int(a)} instead of \c {(int)a}. For more information, see \l{Casting}.
804 \o No float comparisons (\c{-Wfloat-equal}). Use \c qFuzzyCompare to compare
805 values with a delta. Use \c qIsNull to check whether a float is
806 binary 0, instead of comparing it to 0.0, or, prefered, move
807 such code into an implementation file.
809 \o Do not hide virtual methods in subclasses (\{-Woverloaded-virtual}).
810 If the baseclass A has a virtual \c {int val()} and subclass B an
811 overload with the same name, \c {int val(int x)}, the A \c val function
812 is hidden. Use the \c using keyword to make it visible again, and
813 add the following silly workaround for broken compilers:
817 #ifdef Q_NO_USING_KEYWORD
818 inline int val() { return A::val(); }
825 \o Do not shadow variables (\c{-Wshadow}).
827 \o Avoid things like \c {this->x = x;} if possible.
829 \o Do not give variables the same name as functions declared in
832 \o To improve code readability, always check whether a preprocessor
833 variable is defined before probing its value (\c{-Wundef}).
836 #if defined(Foo) && Foo == 0
849 \section1 Documentation
851 The documentation is generated from source and header files. You document
852 for the other developers, not for yourself. In the header files, document
853 interfaces. That is, what the function does, not the implementation.
855 In the .cpp files, you can document the implementation if the
856 implementation is not obvious.