Jump to content

Policies/Frameworks Coding Style: Difference between revisions

From KDE Community Wiki
Aseigo (talk | contribs)
--scrollbars
Add additional information about Qt/KF includes from techbase
 
(67 intermediate revisions by 37 users not shown)
Line 1: Line 1:
This document describes the recommended coding style for kdelibs. Nobody is forced to use this style, but to have consistent formating of the source code files it is recommended to take use of it.


'''In short: Kdelibs coding style follows the Qt 4 coding style.'''
{{Note|1=<!--T:1-->
This document describes the recommended coding style for KDE Frameworks. With Frameworks 5.80 Extra-CMake-Modules contains a finalized clang-format configuration file with this coding style.}}


== Indentation ==
 
{{Note|
In short: KDE Frameworks coding style follows the [http://wiki.qt.io/Qt_Coding_Style Qt coding style], with one main difference:  ''using curly braces even when the body of a conditional statement contains only one line''.}}
 
== Indentation == <!--T:3-->
* No tabs
* No tabs
* 4 Spaces instead of one tab
* 4 Spaces instead of one tab


== Variable delclaration ==
== Variable declaration == <!--T:4-->
* Each variable declaration on a new line
* Each variable should be declared on a new line
* Take useful names, no short names, except:
* Each new word in a variable name starts with a capital letter (so-called camelCase)
* Single character variable names can be used for counters and temporary variables, where the purpose is obvious
* Variables and functions start with a small letter
* Each new word in a variable name starts with a capital letter
* Avoid abbreviations
* Avoid abbreviations
* Use indicative/useful names. No short names, except:
** Single character variable names can denote counters and temporary variables whose purpose is obvious
* Variables and functions start with a lowercase letter
* Member variable names should be prefixed with '''m_''' to make it easier to distinguish them from function parameters and local variable names
** The same applies to Private (d-pointer) class member variable names,  (it may be a bit overkill when the Private class is merely used as a struct and all the code is in the public class, so you can use the '''m_''' prefix everywhere to keep it consistent, or switch to prefixing '''m_''' when adding the first ''method'' to a Private class)
* Static (global) variable names should be prefixed with '''s_'''


<!--T:5-->
Example:
Example:
<code cppqt>
<syntaxhighlight lang="cpp-qt">
// wrong
// wrong
KProgressBar *prbar;
KProgressBar *prbar;
Line 25: Line 33:
QString progressText;
QString progressText;
QString errorString;
QString errorString;
</code>
</syntaxhighlight>


== Whitespace ==
== Whitespace == <!--T:8-->
* Use blank lines to group statements
* Use blank lines to group statements
* Use only one empty line
* Use only one empty line
* Use one space after each keyword
* Use one space after each keyword
** Exception: No space between return and ';'
* No space after left parentheses/before right parentheses
* For pointers or references, use a single space before '*' or '&', but not after
* For pointers or references, use a single space before '*' or '&', but not after
* No space after a cast
* No space after a cast
* Single spaces around binary arithmetic operators '+', '-', '*', '/', '%'
* In function headers and calls: No space before and one space after commas
** Exception: Normalized SIGNAL/SLOT string descriptors in calls to QObject::connect()
* Insert a single space before and after the colon in a range-based for loop


<!--T:9-->
Example:
Example:
<code cppqt>
 
<syntaxhighlight lang="cpp-qt">
 
// wrong
// wrong
QString* myString;
QString* myString;
Line 45: Line 62:
if (true) {
if (true) {
}
}
</code>
</syntaxhighlight>
 
== Enumerations ==
Ideally it should be one member per line.
 
Always add a trailing comma to the last member in an Enumeration. This helps produce better diffs (and has the good side-effect that code formatting tools, e.g. <code>clang-format</code>, will not put the whole enum on one line).
 
The same rule in the Braces section below applies, i.e. the left curly brace goes on the same line as the start of the statement.
 
Example:
 
<syntaxhighlight lang="cpp-qt">
// Wrong
enum ViewType
{
    FullView,
    CompactView
};
 
// Correct
enum ViewType {
    FullView,
    CompactView, // The last enum member should have a trailing comma
};
 
</syntaxhighlight>


== Braces ==
== Braces == <!--T:12-->
As a base rule, the left curly brace goes on the same line as the start of the statement.
As a base rule, the left curly brace goes on the same line as the start of the statement.


<!--T:13-->
Example:
Example:
<code cppqt>
 
<syntaxhighlight lang="cpp-qt">
 
// wrong
// wrong
if (true)
if (true)
{
{
}
}
enum ViewType
{
    FullView,
    CompactView
};


// correct
// correct
if (true) {
if (true) {
}
}
</code>


Exception: Function implementations and class declarations always have the left brace on the start of a line.
enum ViewType {
    FullView,
    CompactView,
};
 
</syntaxhighlight>
 
 
Exception: Function implementations, class, struct and namespace declarations always have the opening brace on the start of a line.


Example:
Example:
<code cppqt>
 
<syntaxhighlight lang="cpp-qt">
void debug(int i)
void debug(int i)
{
{
Line 74: Line 133:
{
{
};
};
</code>
</syntaxhighlight>


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.


<!--T:18-->
Use curly braces even when the body of a conditional statement contains only one line.
<!--T:19-->
Example:
Example:
<code cppqt>
 
<syntaxhighlight lang="cpp-qt">
 
// wrong
// wrong
if (true) {
if (true)
     return true;
     return true;
}


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


// correct
// correct
if (true)
if (true) {
     return true;
     return true;
}


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


Exception 1: Use braces also if the parent statement covers several lines or wraps.
Put 'else' on the same line as the closing brace of the corresponding if block


Example:
Example:
<code cppqt>
if (address.isEmpty() || !isValid()
    || !codec) {
    return false;
}
</code>


Exception 2: Use braces also in if-then-else blocks where either the if-code or the else-code covers several lines.
<syntaxhighlight lang="cpp-qt">
 
Example:
<code cppqt>
// wrong
// wrong
if (true)
if (active)
     return true;
     return true;
else {
else
     ++it;
     return j == 0;
     return false;
 
}
for (int i = 0; i < 10; ++i)
     qDebug("%i", i);


// correct
// correct
if (true) {
if (active) {
     return true;
     return true;
} else {
} else {
     ++it;
     return j == 0;
     return false;
}
 
for (int i = 0; i < 10; ++i) {
     qDebug("%i", i);
}
}
</code>
</syntaxhighlight>


== Switch statements ==
== Switch statements == <!--T:22-->
Case labels are on the same column as the switch
Case labels are on the same column as the switch


<!--T:23-->
Example:
Example:
<code cppqt>
 
<syntaxhighlight lang="cpp-qt">
switch (myEnum) {
switch (myEnum) {
case Value1:
case Value1:
Line 144: Line 206:
     break;
     break;
}
}
</code>
</syntaxhighlight>
 
 
== Line breaks == <!--T:24-->
Try to keep lines shorter than 160 characters. In case you don't like the clang-format results you can use intermediate variables or add manual linebreaks if needed, see the [[#clang-format preserve linebreaks]] snippet.
 
==Includes==
* If possible use forward declarations in header files and put the corresponding includes in the implementation files.
* Includes are grouped in sections which come in this order:
** In implementation files the corresponding header file (if applicable). This helps catch when you forget to put includes or forward declarations in the header.
** Headers from same framework.
** Headers from other frameworks.
** Qt headers.
** Other headers.
* Each section is sorted alphabetically.
 
Example:
<syntaxhighlight lang="cpp-qt">
// Includes in the implementation of the fictitious class KoolStuffPlugin
// Own header
#include "koolstuffplugin.h"
 
// Own framework
#include "koollib.h"
#include "koolstuff.h"
 
// Other frameworks
#include <KComboBox>
#include <KFile>
#include <KIO/FileJob>
#include <KNotification>
#include <KPlotWidget>
 
// Qt
#include <QString>
 
// Other
#include <stdlib.h>
</syntaxhighlight>
 
== Qt and KDE Frameworks Includes == <!--T:25-->
* Omit the module name and only use the class name for Qt and KDE Frameworks includes. That way chances are good that future migrations of Qt classes between different modules do not need any adjustments in the code.
 
<!--T:26-->
Qt example:
 
<syntaxhighlight lang="cpp-qt">
 
// wrong
#include <QtCore/QString>
 
 
// correct
#include <QString>
</syntaxhighlight>
 
KDE Frameworks example:
 
<syntaxhighlight lang="cpp-qt">
// wrong
#include <KIOCore/KFileItem>
#include <KIOCore/KIO/HostInfo>
 
// correct
#include <KFileItem>
#include <KIO/HostInfo>
</syntaxhighlight>
 
== Include Guards ==
 
* Take the name of the header file, make it all upper case, and replace anything that is not a letter or a number with an underscore '_'.
* If you would include it with a leading directory, use that as part of the include guard.
* Do not add leading or trailing underscores.
* Put them below any license text.
 
Example for kaboutdata.h:
<syntaxhighlight lang="cpp-qt">
#ifndef KABOUTDATA_H
#define KABOUTDATA_H
</syntaxhighlight>
 
 
Example for kio/job.h:
<syntaxhighlight lang="cpp-qt">
#ifndef KIO_JOB_H
#define KIO_JOB_H
</syntaxhighlight>
 
 
== Clang-format automatic code formatting == <!--T:29-->
By including the [https://api.kde.org/ecm/kde-module/KDEClangFormat.html KDEClangFormat] CMake module the [https://invent.kde.org/frameworks/extra-cmake-modules/-/blob/master/kde-modules/clang-format.cmake .clang-format file] is copied into the source directory. Using the provided `kde_clang_format` function one can create a target which formats all given files.
Projects can enforce the formatting using a Git [https://api.kde.org/ecm/kde-module/KDEGitCommitHooks.html pre-commit hook] which uses the "git clang-format" tool to ensure the changes are properly formatted.
 
=== Tips and tricks ===
==== Overriding <code>#include</code> ordering ====
The formatting rules in the KDE Frameworks are set to order <code>#include</code> directives (alphabetically, in ascending order), however sometimes one header must be included before another or the build will fail; you can override the ordering of <code>#include</code>'s by simply adding an empty line between them:
<syntaxhighlight lang="cpp-qt">
// clang-format will order them this way
#include "shellapi.h"
#include "windows.h"
 
// To override the order, add an empty line between them, ideally with a comment
// to explain why for next person reading this code
#include "windows.h"
 
#include "shellapi.h" // Must be included after "windows.h"
</syntaxhighlight>
 
==== Formatting Enumerations ====
<syntaxhighlight lang="cpp-qt">
// Without a trailing comma to enums and initializer lists, clang-format will squash the members
// on one line (or more, if the length exceeds the 160 characters limit)
enum ViewType { FullView, CompactView };
const QStringList values = {QStringLiteral("value1"), QStringLiteral("value2")};
 
// With a trailing comma to enums and initializer lists, clang-format will put each member on a separate line
enum ViewType {
    FullView,
    CompactView,
};
const QStringList values = {
    QStringLiteral("value1"),
    QStringLiteral("value2"),
};
</syntaxhighlight>
 
==== Preserving manual line breaks ====
<syntaxhighlight lang="cpp-qt" id="clang-format preserve linebreaks">
// If the statement is longer than 160 characters, clang-format will break it into two lines
const QStringList result =
    MyVeryVeryLongFunction(QStringLiteral("averyverylongparameterforthisfunction"), QStringLiteral("averyverylongparameterforthisfunction"));
// You can use a comment '''//''' at the end to preserve the manual line-break
const QStringList result = MyVeryVeryLongFunction(QStringLiteral("averyverylongparameterforthisfunction"), //
                                                  QStringLiteral("averyverylongparameterforthisfunction"));
 
</syntaxhighlight>


== Artistic Style (astyle) automatic code formatting ==
==== Fixing indentation in assignment expressions ====
You can use [http://astyle.sourceforge.net/ astyle] (<=1.19) to format code or to test if you have followed this document. Run the following command:
<syntaxhighlight lang="cpp-qt">
<code>
// Here the indentation feels a bit off because it is only indented one tab and not relatively to the variable declaration
astyle --indent=spaces=4 --brackets=linux \
int resultFromComplexCalculation = someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename1
      --indent-labels --pad=oper --unpad=paren \
    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename2
      --one-line=keep-statements --convert-tabs \
    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename3;
      --indent-preprocessor \
// Adding parentheses around the entire statement will ensure it is indented relatively to the variable declaration
      `find -type f -name '*.cpp'` `find -type f -name '*.h'`
int resultFromComplexCalculation = (someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename1
</code>
                                    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename2
                                    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename3);


== Vim script ==
</syntaxhighlight>
You can find a vim script in kdesdk/scripts/kde-devel-vim.vim that helps you to keep the coding style correct. In addition to defaulting to the kdelibs coding style it will automatically use the correct style for Solid and kdepim code. If you want to add rules for other projects feel free to add them in the SetCodingStyle function.


To use the script, include it in your ~/.vimrc like this:
==== Disabling formatting for specific parts ====
<code>
<syntaxhighlight lang="cpp-qt">
source /path/to/kde/sources/kdesdk/scripts/kde-devel-vim.vim
// clang-format off
</code>
Some fragile or from third parties imported code...
// clang-format on
</syntaxhighlight>


But you should be careful with excluding parts from the formatting and only do this when it would break code or it would require too many manual interventions as suggested above.


Document started by Urs Wolfer. Some parts of this document have been adopted from the Qt Coding Style document posted by Zack Rusin on kde-core-devel.
Document started by Urs Wolfer. Some parts of this document have been adopted from the Qt Coding Style document posted by Zack Rusin on kde-core-devel.


[[Category:Policies]] [[Category:C++]]
[[Category:Policies]] [[Category:C++]]

Latest revision as of 14:03, 3 April 2023

Note

This document describes the recommended coding style for KDE Frameworks. With Frameworks 5.80 Extra-CMake-Modules contains a finalized clang-format configuration file with this coding style.


Note

In short: KDE Frameworks coding style follows the Qt coding style, with one main difference: using curly braces even when the body of a conditional statement contains only one line.


Indentation

  • No tabs
  • 4 Spaces instead of one tab

Variable declaration

  • Each variable should be declared on a new line
  • Each new word in a variable name starts with a capital letter (so-called camelCase)
  • Avoid abbreviations
  • Use indicative/useful names. No short names, except:
    • Single character variable names can denote counters and temporary variables whose purpose is obvious
  • Variables and functions start with a lowercase letter
  • Member variable names should be prefixed with m_ to make it easier to distinguish them from function parameters and local variable names
    • The same applies to Private (d-pointer) class member variable names, (it may be a bit overkill when the Private class is merely used as a struct and all the code is in the public class, so you can use the m_ prefix everywhere to keep it consistent, or switch to prefixing m_ when adding the first method to a Private class)
  • Static (global) variable names should be prefixed with s_

Example:

// wrong
KProgressBar *prbar;
QString prtxt, errstr;

// correct
KProgressBar *downloadProgressBar;
QString progressText;
QString errorString;

Whitespace

  • Use blank lines to group statements
  • Use only one empty line
  • Use one space after each keyword
    • Exception: No space between return and ';'
  • No space after left parentheses/before right parentheses
  • For pointers or references, use a single space before '*' or '&', but not after
  • No space after a cast
  • Single spaces around binary arithmetic operators '+', '-', '*', '/', '%'
  • In function headers and calls: No space before and one space after commas
    • Exception: Normalized SIGNAL/SLOT string descriptors in calls to QObject::connect()
  • Insert a single space before and after the colon in a range-based for loop

Example:

// wrong
QString* myString;
if(true){
}

// correct
QString *myString;
if (true) {
}

Enumerations

Ideally it should be one member per line.

Always add a trailing comma to the last member in an Enumeration. This helps produce better diffs (and has the good side-effect that code formatting tools, e.g. clang-format, will not put the whole enum on one line).

The same rule in the Braces section below applies, i.e. the left curly brace goes on the same line as the start of the statement.

Example:

// Wrong
enum ViewType
{
    FullView,
    CompactView
};

// Correct
enum ViewType {
    FullView,
    CompactView, // The last enum member should have a trailing comma
};

Braces

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

Example:

// wrong
if (true)
{
}

enum ViewType
{
    FullView,
    CompactView
};

// correct
if (true) {
}

enum ViewType {
    FullView,
    CompactView,
};


Exception: Function implementations, class, struct and namespace declarations always have the opening brace on the start of a line.

Example:

void debug(int i)
{
    qDebug("foo: %i", i);
}

class Debug
{
};


Use curly braces even when the body of a conditional statement contains only one line.

Example:

// wrong
if (true)
    return true;

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


// correct
if (true) {
    return true;
}

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

Put 'else' on the same line as the closing brace of the corresponding if block

Example:

// wrong
if (active)
    return true;
else
    return j == 0;

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

// correct
if (active) {
    return true;
} else {
    return j == 0;
}

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

Switch statements

Case labels are on the same column as the switch

Example:

switch (myEnum) {
case Value1:
    doSomething();
    break;
case Value2:
    doSomethingElse();
    // fall through
default:
    defaultHandling();
    break;
}


Line breaks

Try to keep lines shorter than 160 characters. In case you don't like the clang-format results you can use intermediate variables or add manual linebreaks if needed, see the #clang-format preserve linebreaks snippet.

Includes

  • If possible use forward declarations in header files and put the corresponding includes in the implementation files.
  • Includes are grouped in sections which come in this order:
    • In implementation files the corresponding header file (if applicable). This helps catch when you forget to put includes or forward declarations in the header.
    • Headers from same framework.
    • Headers from other frameworks.
    • Qt headers.
    • Other headers.
  • Each section is sorted alphabetically.

Example:

// Includes in the implementation of the fictitious class KoolStuffPlugin
// Own header
#include "koolstuffplugin.h"

// Own framework
#include "koollib.h"
#include "koolstuff.h"

// Other frameworks
#include <KComboBox>
#include <KFile>
#include <KIO/FileJob>
#include <KNotification>
#include <KPlotWidget>

// Qt
#include <QString>

// Other
#include <stdlib.h>

Qt and KDE Frameworks Includes

  • Omit the module name and only use the class name for Qt and KDE Frameworks includes. That way chances are good that future migrations of Qt classes between different modules do not need any adjustments in the code.

Qt example:

// wrong
#include <QtCore/QString>


// correct
#include <QString>

KDE Frameworks example:

// wrong
#include <KIOCore/KFileItem>
#include <KIOCore/KIO/HostInfo>

// correct
#include <KFileItem>
#include <KIO/HostInfo>

Include Guards

  • Take the name of the header file, make it all upper case, and replace anything that is not a letter or a number with an underscore '_'.
  • If you would include it with a leading directory, use that as part of the include guard.
  • Do not add leading or trailing underscores.
  • Put them below any license text.

Example for kaboutdata.h:

#ifndef KABOUTDATA_H
#define KABOUTDATA_H


Example for kio/job.h:

#ifndef KIO_JOB_H
#define KIO_JOB_H


Clang-format automatic code formatting

By including the KDEClangFormat CMake module the .clang-format file is copied into the source directory. Using the provided `kde_clang_format` function one can create a target which formats all given files. Projects can enforce the formatting using a Git pre-commit hook which uses the "git clang-format" tool to ensure the changes are properly formatted.

Tips and tricks

Overriding #include ordering

The formatting rules in the KDE Frameworks are set to order #include directives (alphabetically, in ascending order), however sometimes one header must be included before another or the build will fail; you can override the ordering of #include's by simply adding an empty line between them:

// clang-format will order them this way
#include "shellapi.h"
#include "windows.h"

// To override the order, add an empty line between them, ideally with a comment
// to explain why for next person reading this code
#include "windows.h"

#include "shellapi.h" // Must be included after "windows.h"

Formatting Enumerations

// Without a trailing comma to enums and initializer lists, clang-format will squash the members
// on one line (or more, if the length exceeds the 160 characters limit)
enum ViewType { FullView, CompactView };
const QStringList values = {QStringLiteral("value1"), QStringLiteral("value2")};

// With a trailing comma to enums and initializer lists, clang-format will put each member on a separate line
enum ViewType {
    FullView,
    CompactView,
};
const QStringList values = {
    QStringLiteral("value1"),
    QStringLiteral("value2"),
};

Preserving manual line breaks

// If the statement is longer than 160 characters, clang-format will break it into two lines
const QStringList result =
    MyVeryVeryLongFunction(QStringLiteral("averyverylongparameterforthisfunction"), QStringLiteral("averyverylongparameterforthisfunction"));
// You can use a comment '''//''' at the end to preserve the manual line-break
const QStringList result = MyVeryVeryLongFunction(QStringLiteral("averyverylongparameterforthisfunction"), //
                                                  QStringLiteral("averyverylongparameterforthisfunction"));

Fixing indentation in assignment expressions

// Here the indentation feels a bit off because it is only indented one tab and not relatively to the variable declaration
int resultFromComplexCalculation = someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename1
    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename2
    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename3;
// Adding parentheses around the entire statement will ensure it is indented relatively to the variable declaration
int resultFromComplexCalculation = (someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename1
                                    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename2
                                    + someveryveryveryveryveryveryveryveryveryveryveryveryverylongvariablename3);

Disabling formatting for specific parts

// clang-format off
Some fragile or from third parties imported code...
// clang-format on

But you should be careful with excluding parts from the formatting and only do this when it would break code or it would require too many manual interventions as suggested above.

Document started by Urs Wolfer. Some parts of this document have been adopted from the Qt Coding Style document posted by Zack Rusin on kde-core-devel.