coding-style.qdoc 12.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/*!

\contentpage{index.html}{Qt Creator}
\page coding-style.html

\title Qt Creator Coding Rules

THIS IS PRELIMINARY.

\section1 Introduction

The aim of this section is to serve as a guide for the developers, to aid us
to build understandable and maintainable code, to create less confusion and
surprises when working on Qt Creator.

As usual: Rules are not set in stone. If there's a good reason to break one,
do it, preferably after making sure that there are others agreeing.

This document is incomplete.

In general, if you want to contribute to the main source, we expect at least
that you:

\list 1
\o The most important rule first: KISS (keep it simple ...): always
   use a simple implementation in favor of a more complicated one.
   This eases maintenance a lot.
\o Write good C++ code: Readable, well commented when necessary,
   and taking advantage of the OO model. Follow the \l{Formatting} guidelines.
   There are also certain \l{Code Constructs} that we try to follow.
\o Adapt the code to the structures already existing in Qt Creator, or in
   the case that you have better ideas, discuss them with other developers
   before writing the code.
\o Take advantage of Qt. Don't re-invent the wheel. Think about what parts
   of your code are generic enough that they might be incorporated into 
   Qt proper. 
\o Document interfaces. Right now we use qdoc, but changing to doxygen
   is being considered.
\endlist


\section1 Submitting Code

44 45
Send your contributions to qt-creator@trolltech.com

46 47
It is implicitly understood that all patches contributed to The Qt Creator
Project are made under under the Gnu General Public License, version 2 or later
48 49
and currently we require that you sign a copyright assignment form. We are
working on a better solution.
50 51 52 53 54 55 56 57 58

If you have a problem with that, don't contribute code.

Also please don't just pop up out of the blue with a huge patch (or
small) that changes something substantial in Qt Creator. Always discuss your
ideas with the other developers on mailing list first.

When you create the patch, please use git or use "diff -up" since we find
that a lot easier to read than the other diff formats. Also please do not
59 60
send patches that implement or fixes several different things; several
patches is a much better option. Or send as your a url to pull from.
61 62

We also require you to provide a commit message entry with every patch,
63
that describes in detail what the patch is doing.
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110


\section1 Code Constructs

We have several guidelines on code constructs, some of these exist to
make the code faster, others to make the code clearer. Yet others
exist to allow us to take advantage of the strong type checking
in C++.

\list 1
\o Declaration of variables should wait as long as possible. The rule
  is: "Don't declare it until you need it." In C++ there are a lot of
  user defined types, and these can very often be expensive to
  initialize. This rule connects to the next rule too.

\o Make the scope of a variable as small as possible.

\o Prefer preincrement to postincrement whenever possible.
  Preincrement has potential of being faster than postincrement. Just
  think about the obvious implementations of pre/post-increment. This
  rule applies to decrement too.

\code
	++T;
	--U;
	-NOT-
	T++; // not used in Qt Creator
	U--; // not used in Qt Creator
\endcode

\o Try to minimize evaluation of the same code over and over. This is
   aimed especially at loops.

\code

	Container::iterator end = large.end();
	for (Container::iterator it = large.begin(); it != end; ++it) {
		...;
	}
	-NOT-
	for (Container::iterator it = large.begin();
	     it != large.end(); ++it) {
		...;
	}
\endcode


hjk's avatar
hjk committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
\o Using Qt's foreach is ok in non-time critical code when using a QTL 
   container. It is a nice way to keep line noise down and to give the
   loop variable a proper name:

\code
        foreach (QWidget *widget, container)
            doSomething(widget);

        -VS-

	Container::iterator end = container.end();
	for (Container::iterator it = container.begin(); it != end; ++it)
            doSomething(*it);
\endcode
   
    If the loop variable can be made const, do so. This can prevent 
    unnecessary detaching of shared data in some cases. So:

\code
        foreach (const QString &name, someListOfNames)
            doSomething(name);
        
        - NOT -

        foreach (QString name, someListOfNames)
            doSomething(name);
\endcode

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

\section1 Formatting

\section2 Declarations

Only one declaration on each line.
\code
	int a;
	int b;
	-NOT-
	int a, b; // not used in Qt Creator
\endcode

  This is especially important when initialization is done at the same
  time.
\code
	QString a = "Joe";
	QString b = "Foo";
	-NOT-
	QString a = "Joe", b = "Foo"; // not used in Qt Creator
\endcode
	[Note that 'QString a = "Joe"' is formally calling a copy constructor 
	on a temporary constructed from a string literal and therefore has the
	potential of being more expensive then direct construction by
	'QString a("joe")'. However the compiler is allowed to elide the copy
	(even if it had 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, _and_ cannot be
	mistaken as function declaration, _and_ reduces the level of nested
	parantheses in more initializations.]
	

\section2  Pointers and references

\code
	char *p = "flop";
	char &c = *p;
	-NOT-
	char* p = "flop"; // not used in Qt Creator
	char & c = *p;     // not used in Qt Creator
\endcode

  This is simply in line with the official Qt guide lines.

  Also note that we will have:
\code
	const char *p;
	-NOT-
	char const * p; // not used in Qt Creator
\endcode


  Using a plain 0 for Null pointer constants is always correct and least effort
  to type. So:
\code
	void *p = 0;
	-NOT-
	void *p = NULL; // not used in Qt Creator
	-NOT-
	void *p = '\0'; // not used in Qt Creator
	-NOT-
	void *p = 42 - 7 * 6; // also not used in Qt Creator
\endcode
  Note: As an exception, imported third party code as well as code
  interfacing the "native" APIs (src/support/os_*) can use NULL.


\section2  Operator names and parentheses
\code
	operator==(type)
	-NOT-
	operator == (type)  // not used in Qt Creator
\endcode

  The == is part of the function name, separating it makes the
  declaration look like an expression.


\section2 Function names and parentheses
\code
	void mangle()
	-NOT-
	void mangle ()  // not used in Qt Creator
\endcode



\section2 Naming rules

  Simply follow the style of Qt proper. As examples:
 \list
  \o Use descriptive but simple and short names. Do not abbreviate.

  \o Class names are capitalized, and function names lowercased.
    Enums are named like Classes, values are in lower-case.
\endlist



\section2 Formatting
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
   We are using the Qt Coding style, please follow the guidelines below.

Indentation
  4 spaces, no tabs

Declaring variables
  Declare each variable on a separate line
  Avoid short (e.g., a,rbarr,nughdeget) names whenever possible
  Single character variable names are only okay for counters and temporaries, where the purpose of the variable is obvious
  Wait with declaring a variable until it is needed

  Variables and functions start with a small letter. Each consecutive word in a variable's name starts with a capital letter
  Avoid abbreviations

    // Wrong
    int a, b;
    char *c, *d;

    // Correct
    int height;
    int width;
    char *nameOfThis;
    char *nameOfThat;

Whitespace
  Use blank lines to group statements together where suited
  Always use only one blank line
  Always use a single space after a keyword, and before a curly brace.

268
\code
269 270 271 272 273 274 275
    // Wrong
    if(foo){
    }

    // Correct
    if (foo) {
    }
276
\endcode
277 278 279

  For pointers or references, always use a single space before '*' or '&', but never after.
  Avoid C-style casts when possible.
280
\code
281 282 283 284 285 286
    // Wrong
    char* blockOfMemory = (char* ) malloc(data.size());

    // Correct
    char *blockOfMemory = (char *)malloc(data.size());
    char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
287 288 289
\endcode
  Of course, in this particulare case, using \c new might be an even better
  option.
290 291 292

Braces
  As a base rule, the left curly brace goes on the same line as the start of the statement:
293
\code
294 295 296 297 298 299 300 301
    // Wrong
    if (codec)
    {
    }

    // Correct
    if (codec) {
    }
302
\endcode
303 304

  Exception: Function implementations and class declarations always have the left brace on the start of a line:
305
\code
306 307 308 309 310 311 312 313
    static void foo(int g)
    {
        qDebug("foo: %i", g);
    }

    class Moo
    {
    };
314
\endcode
315 316

  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.
317
\code
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    // Wrong
    if (address.isEmpty()) {
        return false;
    }

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

    // Correct
    if (address.isEmpty())
        return false;

    for (int i = 0; i < 10; ++i)
        qDebug("%i", i);
333
\endcode
334 335

  Exception 1: Use braces also if the parent statement covers several lines / wraps
336
\code
337 338 339 340 341
    // Correct
    if (address.isEmpty() || !isValid()
        || !codec) {
        return false;
    }
342
\endcode
343 344

  Exception 2: Use braces also in if-then-else blocks where either the if-code or the else-code covers several lines
345
\code
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    // Wrong
    if (address.isEmpty())
        --it;
    else {
        qDebug("%s", qPrintable(address));
        ++it;
    }

    // Correct
    if (address.isEmpty()) {
        --it;
    } else {
        qDebug("%s", qPrintable(address));
        ++it;
    }

    // Wrong
    if (a)
        if (b)
            ...
        else
            ...

    // Correct
    if (a) {
        if (b)
            ...
        else
            ...
    }
376
\endcode
377 378

  Use curly braces when the body of a conditional statement is empty
379
\code
380 381 382 383 384
    // Wrong
    while (a);

    // Correct
    while (a) {}
385
\endcode
386 387 388

Parentheses
  Use parentheses to group expressions:
389
\code
390 391 392 393 394 395 396 397 398 399 400
    // Wrong
    if (a && b || c)

    // Correct
    if ((a && b) || c)

    // Wrong
    a + b & c

    // Correct
    (a + b) & c
401
\endcode
402 403 404 405

Line breaks
  Keep lines shorter than 100 characters; insert line breaks if necessary.
  Commas go at the end of a broken line; operators start at the beginning of the new line. The operator is at the end of the line to avoid having to scroll if your editor is too narrow.
406
\code
407 408 409 410 411 412 413 414 415 416 417
    // Wrong
    if (longExpression +
        otherLongExpression +
        otherOtherLongExpression) {
    }

    // Correct
    if (longExpression
        + otherLongExpression
        + otherOtherLongExpression) {
    }
418
\endcode
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435


\section2 Declarations

  - Use this order for the access sections of your class: public,
    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). [Obviously not true since this is
    for developers, and we do not want one developer only to be able to
    read and understand the implementation of class internals. Lgb]

  - Avoid declaring global objects in the declaration file of the class.
    If the same variable is used for all objects, use a static member.

  - Avoid global or static variables.


436 437 438 439
\section2 API/ABI stability
  We currently do not gurantee any API nor ABI compatibility between releases.


440 441 442 443 444
\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.

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
\section2 Include order

  Always go from less general to more general. In a typical implementation
  file that would look like
\code
  #include "myownheader.h"
  ...
  #include "other_headers_from_my_own_plugin.h"
  ...
  #include <other_plugin/headers_from_other_plugin.h>
  ...
  #include <QtCore/QSomeCoreClass>
  ...
  #include <QtGui/QSomeGuiClass>
  ...
  #include <some_system_C++_header>
  ...
  #include <some_system_C_header>
\endcode
  This order ensures that the headers are self-contained.

  Using <...> instead of "..." for headers from other plugins helps
  spotting plugin-external dependencies in the sources.

  Using empty lines between blocks of "peer" headers are encouraged.

471 472 473 474 475 476 477 478 479 480 481
\section2 Documentation

  The documentation is generated from source and header files.
  You document for the other developers, not for yourself.
  In the header you should document interfaces, i.e.  what the function does,
   not the implementation.
  In the .cpp files you document the implementation if the implementation 
  in non-obvious.


*/