Project

General

Profile

Actions

Coding Styleguide » History » Revision 7

« Previous | Revision 7/17 (diff) | Next »
quintus, 03/21/2020 12:32 PM


Coding Styleguide

Those who have worked on the TSC project will remember the dreaded discussion about coding style. This project will avoid the trap by using a consistent coding style right from the start. It is outlined in this document.

The game's source code is formatted according to the 1TBS style, which is a variant of K&R, with slight adjustments. Details are documented below.

In general, try to keep your code readable. Specifically, it is often useful to leave empty lines to separate logically grouped statements from one another.

Indentation, line length

Source code is indented with 4 spaces, tabs are not used. Lines should be broken around 80 characters, and the resulting continuation lines should be indented so that it makes sense to look at. Example:

if (somecondition) {
    thisIsAVeryLongFunctionName(this_is_a_parameter,
                                this_is_another_parameter,
                                third_parameter);
}

Commentary

Semantically, comments should normally reflect why code is written the way it is. Normally it is not required to explain what code does, unless it is an exceptionally complex part. Syntactically, use // for one and two lines of comments. Starting with the third line, comments should use the bock syntax /* ... */. In the block syntax, align each star with the one on the preceeding line. Terminate the comment block on the last line of the comment.

// Careful: this is used in foobar() as well

/* This code is designed to specifically fit the purpose of an example.
 * It was not at all easy to come up with all this text, but for the
 * sake of an example, it was required to do so. */

Documentation comments

Where Doxygen is used to generate documentation, use Doxygen's /// markers for short and the /** markers for long documentation. Other than that, the above advice applies.

Case of identifiers

  • Macros are ALL_IN_CAPS. They need to stand out.
  • Class identifiers use CamelCase. Structure and enum identifiers are snake_case (makes it easy to spot whether this type is copy-by-value or copy-by-reference: every lowercase type is copy-by-value).
  • Member function identifiers are CamelCase. This keeps function names short (they tend to be longer than member variable names).
  • All variables and constants (unless the constants are macros, see above) are snake_case. This includes static member variables, even if they are constant. This way a non-function member is easily identifiable by being lowercase. The different variable types are distinguished by the prefix (see below).
#define THIS_IS_A_MACRO(x) foo_ ## x

struct my_struct;
enum class my_enum;

class MyClass {
    MyClass();
    ~MyClass();

    void MemberFunction();
    static int StaticMemberFunction();

    int m_member_variable;
    static int static_member;
};

void foo() {
    static int local_static_variable;
    float normal_local_var = 3.5f;
    // ...
}

Abbreviated Hungarian Notation

Identifiers of variables and constants begin with a short sequence of characters that encodes some important information about the variable in question. This is called Hungarian Notation, but in full, it is cumbersome to read and leads to long identifier names. The following prefix characters have been chosen with respect to two goals: Make variable scope immediately visible, and warn of "unusual" types.

Prefix Meaning
No prefix: Local variable
m Member variable
f File-local variable
g Global variable
p Variable holds a pointer (both raw and managed pointers)
a Variable holds a raw array (not: vector or other C++ containers)

The scope prefix comes before the type prefix. Thus, mp_foo is a member variable holding a pointer, and ga_argv is a global variable holding a raw C array.

There are two special cases. First, member variables of structs and enums do not have a leading m prefix, because they do not normally contain functions, but are only accessed from the outside (whereas for classes as per the secrecy principle access to member variables from the outside is unusual), and it would be cumbersome to always add the extra m. Second, static member variables of classes do not have a scope prefix. Instead, they are always to be accessed via the class name.

static int f_something; // File-local variable
extern int g_globvar;   // Global variable

class MyClass {
    void MyFunc() {
        int* p_int;                   // Local variable
        m_normal_member += "AAA";     // Accessing member variable
        DoSomething(MyClass::foobar); // Exception: accessing static member variable via class name, not directly
    }

    std::string m_normal_member;    // Normal member variable
    int* mp_int;                    // Member variable with pointer
    static const float foobar = 42; // Exception: Static member variable
};

struct point {
    int x;            // Struct members have no "m" prefix
    int y;
    int z;
    owner* p_owner;   // But they do have the type prefix if required.
};

point MoveUp(point p) {
    p.y -= 10;         // Access to struct member without "m"
    return p;
}

enum class color { red, green, blue }; // Exception: enum members do not have "m"
void MyFunc(color c) {
    if (c == color::red) { // Because they are accessed only from the outside.
      // ...
    }
}

Compound Statements

The opening brace resides on the same line as the statement it applies to, regardless of whether this is a function, a control flow statement, or a class or enum declaration. The closing brace has a line on its own to ensure it is easily spottable where a block ends.

class Foo {
};

if (condition) {
    // ...
}

while (condition) {
    // ...
}

void main() {
    // ...
}

The rare case of a terminal while has the while after the closing brace on the same line.

{
    // ...
} while (condition)

Brace Cuddling

In an if/elsif/else statement, braces are cuddled to keep code compact.

if (condition1) {
    // ...
} else if (condition2) {
    // ...
} else {
    // ...
}

Braces around short statements

Do not leave out braces even for one-line statements. This should prevent any accidental cutting of conditional clauses.

// Short: required braces
if (condition) {
    doit();
}

// Also requires braces
if (condition1) {
    doit();
} else { // Thanks to brace cuddling, this is not as bad as in pure K&R
    doother();
}

// Requires braces in any style to keep clarity
if (condition1) {
    doit();
} else {
    doother1();
    if (condition2) {
        something();
    }
    else {
        andmore();
    }
}

Parantheses and spacing

Between a keyword and the opening paranthesis is exactly one space. Between the closing paranthesis and the opening curly brace is exactly one space as well. There is no space between a function name and the opening paranthesis of its argument list, neither in declaration nor in calling of a function.

void Foo() { // No space between function name and (, but one space between ) and {
    if (condition) { // One space between keyword if and (, and one space between ) and {
        // ...
    }
}

Visibility Specifiers

In class declarations, visibility labels like public and private are on the same level like the corresponding class statement.

class MyClass {
public:
    MyClass();
    ~MyClass();

private:
    void PrivateMethod();
};

enum specifics

Names of enum identifiers are singular, not plural. If used as a type, color var reads more natural than colors var. Use enum class instead of raw enum whenever possible (this is C++11 specific and allows colliding enum identifiers in case you wonder that enum class is valid syntax).

enum class color { red, green, blue };

void Foo(color c) {
    // ...
}

File names

All source code files are in snake_case. C++ source code files end in .cpp, C++ headers end in .hpp. C source files end with .c, C headers in .h.

Inclusion of headers

Each C/C++ source file includes only the headers it needs to compile, and all inclusions are at the top of the file. Inclusions are done in this order:

  1. The header file corresponding to this .c/.cpp file. Doing this first ensures that the .hpp file is self-contained, because on compilation of the corresponding .cpp file the compiler will error out on the very first #include line then if the header is not self-contained. For .hpp files, this step is obviously missing.
  2. Other internal headers.
  3. External library headers.
  4. Standard library headers.

The path delimiter for #include statements is always a forward slash, because this compiles on both Windows and Unix systems. External and standard library headers are included with angle #include <>, internal headers with quoted #include "".

// This is foo.cpp, it has a header foo.hpp.
#include "foo.hpp"
#include "../misc/internal_header.hpp"
#include <curl.h>
#include <vector>
#include <cstdlib>

Forward declarations in headers

To increase compile times and keep the inclusion graph simple, headers should try hard to not require other internal headers. If an internal type is required in a header, it should be forward-declared in that very header. Note that it is possible to forward-declare classes, structs, and even enums. In most cases, forward-declarations are entirely sufficient. For instance, pointers, references, many templated types, and even smart pointers can be used with only the forward-declaration available.

// Forward declarations
class MyClass;

class MyOtherClass {
public:
    MyOtherClass(MyClass& mc) : m_mc(mc) {}
    void Foo(MyClass* p_mc){ /* ... */ }
private:
    MyClass& m_mc;
};

The corresponding .cpp file will then have to include the internal header for MyClass:

#include "my_other_class.hpp"
#include "../misc/my_class.hpp" // <---

Updated by quintus almost 5 years ago · 7 revisions