6 Coding Style
Kevin Ottens edited this page 2021-01-26 12:07:50 +01:00

Coding Style

General

The coding style of the project is based on the coding style of Qt. An overview of this coding style can be found here:

Important: Note that like the KDE Frameworks Coding Style we have one exception on top of the Qt one: we use curly braces even when the body of a conditional statement contains only one line.

Variable names

Member variables should be prefixed with a underscore. For example write _myClassVariable instead of myClassVariable.

Header files

Every header file should contain a copyright note and #pragma once should preferred instead of #ifndef header guards.

STL

When possible use data structures from Qt. For example use QVector instead of std::vector.

Algorithms

When possible use algorithms from the STL or Qt. For example use std::copy_if instead of coding it by hand.

Smart Pointers

QSharedPointer should be used instead of std::shared_ptr. However, it is okay to use a STL smart pointer if there is no equivalent in Qt, like std::unique_ptr.

Accessors and Properties

Assuming a member named _value in a class inheriting from QObject, it is common to expect the following:

  • a Q_PROPERTY named value (with the NOTIFY part referring to the signal if it applies);
  • a getter type value() const;
  • a setter void setValue(type value)
  • a signal void valueChanged(type value)

Note that if the type of _value is bool, then the getter is expected to be named isValue() and not value().

Favor return by value

One should return from functions by value, for instance: QVector<int> computeValues();

Returning references or const references should be the exception not the rule. Similarly values should be received by value not by reference: const auto values = computeValues();

Although const auto &values = computeValues(); is semantically correct it looks foreign in the code base. We favor consistency.

Unit Tests

Names of unit tests should follow the scheme proposed by Roy Osherove in his book The Art of Unit Testing. The general scheme is:

void testUnitOfWork_stateUnderTest_expectedBehaviour()

It is explained here.

Example

The following shows how a class that inherits from QObject should be declared:

class Foo : public QObject
{
    Q_OBJECT
    Q_PROPERTY(....)
public:
    enum Bar {
    };
    Q_ENUM(Bar)

    static void staticMethods();

    explicit Foo(QObject *parent = nullptr);

    bool publicMethod() const;

signals:
   void mySignal();

protected slots:
    void protectedSlot();

protected:
    void protectedMethod();

private slots:
    void privateSlot();

private:
    void privateMethod();

    bool _member;
};