Project

General

Profile

Coding Styleguide » History » Version 16

quintus, 03/24/2020 01:13 PM

1 1 quintus
# Coding Styleguide
2
3 2 quintus
{{toc}}
4
5 1 quintus
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.
6
7 8 quintus
The game's source code is formatted mostly according to the [1TBS](http://astyle.sourceforge.net/astyle.html#_style=1tbs) style, which is a variant of K&R, with slight adjustments. Details are documented below. Most (not all!) rules can be followed by formatting with the [astyle](http://astyle.sourceforge.net) command like this:
8 1 quintus
9 8 quintus
~~~~
10
$ astyle --style=1tbs --indent=spaces=4 --indent-namespaces \
11 9 quintus
  --attach-classes --attach-namespaces --attach-closing-while --attach-inlines --attach-extern-c \
12 8 quintus
  --align-pointer=type --align-reference=type \
13 16 quintus
  --break-one-line-headers --add-braces --close-templates --lineend=linux \
14 8 quintus
   yourfile.cpp
15
~~~~
16
17 1 quintus
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.
18
19 8 quintus
One of the design goals of this document is to keep the styling consequent and easy to follow. For instance, instead of the questionable distinction of attaching braces to structs, but not to classes in the 1TBS style, this style says to simply always attach the braces (the only exception being function definitions). In so far it includes elements from the Stroustrup style. Likewise, indenting every brace block is easier to remember than not to indent namespaces.
20 1 quintus
21 8 quintus
## Commentary
22 1 quintus
23 8 quintus
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.
24 1 quintus
25
~~~~~ c++
26 8 quintus
// Careful: this is used in foobar() as well
27
28
/* This code is designed to specifically fit the purpose of an example.
29
 * It was not at all easy to come up with all this text, but for the
30
 * sake of an example, it was required to do so. */
31
~~~~~
32
33 1 quintus
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.
34 16 quintus
35
## Line endings
36
37
All files use only LF as line endings (unix-style line endings).
38 8 quintus
39
## Indentation and line length
40
41
Source code is indented with 4 spaces, tabs are not used. All blocks enclosed in braces are indented, including namespaces. Do not indent labels, including visibility labels like `public` and `private`; they should line up with the enclosing statement. Preprocessor statements are not indented.
42
43
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ c++
44
#ifndef MY_HEADER
45
#define MY_HEADER
46
47
namespace MyNamespace {
48
    class MyClass {
49
    public:
50
        MyClass();
51
       ~MyClass();
52
    };
53
54 11 quintus
    struct MysSruct {
55 8 quintus
        int a;
56
        int b;
57
    };
58
}
59
60 11 quintus
void myFunc()
61 8 quintus
{
62 11 quintus
    foo();
63 8 quintus
    if (something) {
64 11 quintus
        bar();
65
        baz();
66 8 quintus
    }
67
}
68
#endif
69
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70
71
Lines should be broken around 80 characters, and the resulting continuation lines should be indented so that it makes sense to look at. Example:
72
73
~~~~~ c++
74 1 quintus
if (somecondition) {
75 11 quintus
    thisIsAVeryLongFunctionName(this_is_a_parameter,
76 1 quintus
                                this_is_another_parameter,
77
                                third_parameter);
78
}
79
~~~~~
80
81 8 quintus
This is not a hard requirement. You should use whatever conveys the meaning best. That's why the `astyle` command above does not include a hard line wrap option.
82 1 quintus
83 8 quintus
## Placement of braces
84 1 quintus
85 9 quintus
Braces are placed on the same line like the statement they belong to, be that a class or namespace declaration, an `extern C`, or anything else. The only exception from this are ordinary function definitions: for them the opening brace is broken into the next line. In any case, the closing brace always has its own line (makes it easy to spot the end of a block). `if/elseif/else` is cuddled to keep code compact, and the rare case of a trailing `while` has the `while` attached to the brace. Do not leave out braces even for one-line statements. This should prevent any accidental cutting of conditional clauses. To keep style consistent, also do not use all-in-one-line conditionals (this violates the expectation that the closing brace for each block can be found on its own line at the relevant indentation level).
86 1 quintus
87 8 quintus
Keen readers will notice that for in-function statements this uses the 1TBS style, and for out-of-function statements the Stroustrup style. Examples below.
88 1 quintus
89 8 quintus
~~~~~~~~~~~ c++
90
// Exception: function definition
91
void main()
92
{
93
    // ...
94 1 quintus
}
95
96 9 quintus
// Member functions also fall under the exception.
97 11 quintus
void Foo::setX(int x)
98 9 quintus
{
99
    m_x = x;
100
}
101
102 8 quintus
// Everything else: attach the braces.
103
class Foo {
104
    // ...
105
};
106 10 quintus
struct Foo {
107 8 quintus
    // ...
108
};
109 10 quintus
enum class Foo {
110 8 quintus
    // ...
111
};
112
if (condition) {
113
    // ...
114
}
115
while (condition) {
116
    // ...
117 1 quintus
}
118
119 9 quintus
// A function definition inside a class definition does not count as an "ordinary" function. Attach.
120
// This is mostly useful for defining short class constructors or getters/setters.
121
class Foo {
122 12 quintus
    Foo(int x) : m_x {}
123
    inline int getX() { return m_x; }
124 9 quintus
};
125
126 8 quintus
// Trailing while attached
127
{
128
    // ...
129
} while (condition)
130
131
// Brace kuddling from 1TBS
132
if (condition1) {
133
    // ...
134
} else if (condition2) {
135
    // ...
136
} else {
137
    // ...
138
}
139
140
// Required braces around one-line statements
141
if (condition) {
142
    doit();
143
}
144
145
// Also requires braces
146
if (condition1) {
147
    doit();
148
} else { // Thanks to brace cuddling, this is not as bad as in pure K&R
149
    doother();
150
}
151
152
// DO NOT DO THIS
153 11 quintus
if (condition) { oneliner(); }
154 8 quintus
// Break it.
155
if (condition) {
156 11 quintus
    oneliner();
157 8 quintus
}
158
~~~~~~~~~~~
159
160
## Initial assignment
161
162
Assign an initial value to any variable you declare. This prevents undefined values from coming from a forgotten assignment and eases debugging quite a bit, because it obviates the question "is this a real value or was this variable never assigned?".
163
164
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ c++
165
int a;     // BAD
166
int a = 0; // GOOD
167
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168
169
## Pointer and reference alignment, multi-variable declarations
170
171
Place the `*` and `&` next to the type, not to the name. They belong semantically to the type. Do not declare multiple variables in one line if one of them is a pointer, it causes confusion:
172
173
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ c++
174
int i = 0, j = 0; // Okay, no pointer
175
176
int* p  = nullptr;         // Pointer to int
177
int* p1 = nullptr, p2 = 0; // DONT DO THIS. p2 is not a pointer!
178
179
// Instead, break the lines up.
180
int* p1 = nullptr;
181
int  p2 = 0;
182
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
183
184
Multiple variable assignments should be aligned at the `=`.
185
186
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ c++
187
int foo    = 0;
188
int foobar = 0;
189
int la     = 0;
190
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
191
192
## Parantheses and spacing
193
194
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*.
195
196
Template angles and index brackets do not have any surrounding space.
197
198
~~~~~~~~ c++
199 11 quintus
void foo(int myparam) // No spaces around the "(" and ")"
200 8 quintus
{
201 1 quintus
    if (condition) { // One space between keyword if and "(", and one space between ")" and "{"
202 11 quintus
        myFunc(5);   // No spaces around the "(" and ")"
203 1 quintus
    }
204
}
205 8 quintus
206
vector[3] = foo;                // No space between "vector" and "[3]"
207
map<string, vector<int>> mymap; // No spaces around <> (C++11 syntax)
208
~~~~~~~~
209
210 1 quintus
## Case of identifiers
211 8 quintus
212 1 quintus
* Macros are ALL_IN_CAPS. They need to stand out, because macro expansion can have surprises which may explain cryptic error messages.
213 11 quintus
* Variable identifiers use snake_case, including identifiers for variables declared `const` and/or `static`. The different variable types are distinguished by the prefix (see [below](#Abbreviated-Hungarian-Notation)).
214
* Function identifiers use snakedCamelCase (i.e. first word is lowercase, the rest is CamelCase). Constructors and destructors are the only exception to this rule (because C++’ syntax requires them to be the same way as the type identifier).
215
* Type identifiers (class, enum, struct identifiers) use CamelCase.
216 10 quintus
217 11 quintus
The different casing rules make it easy to spot which kind of identifier one is dealing with. Between one-word functions and variables a distinction is not possible except for the variable prefix; it is expected that most function identifiers are composed of multiple words, so that this is not an issue.
218
219 1 quintus
~~~~~~ c++
220
#define THIS_IS_A_MACRO(x) foo_ ## x
221
222 10 quintus
struct MyStruct;
223
enum class MyEnum;
224 1 quintus
225
class MyClass {
226
    MyClass();
227
    ~MyClass();
228
229 11 quintus
    void memberFunction();
230
    static int staticMemberFunction();
231 1 quintus
232
    int m_member_variable;
233
    static int static_member;
234 3 quintus
};
235 1 quintus
236 11 quintus
void foo()
237 8 quintus
{
238 3 quintus
    static int local_static_variable;
239 1 quintus
    float normal_local_var = 3.5f;
240 3 quintus
    // ...
241 1 quintus
}
242 3 quintus
~~~~~~
243
244 1 quintus
## Abbreviated Hungarian Notation
245 3 quintus
246
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](https://en.wikipedia.org/wiki/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.
247 1 quintus
248
| Prefix | Meaning                                                          |
249
|--------+------------------------------------------------------------------|
250
|        | No prefix: Local variable                                        |
251
| m      | Member variable                                                  |
252
| f      | File-local variable                                              |
253
| g      | Global variable                                                  |
254
| p      | Variable holds a pointer (both raw and managed pointers)         |
255
| a      | Variable holds a raw array (not: vector or other C++ containers) |
256
257
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.
258
259
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.
260
261
~~~~~~~~~~~ c++
262
static int f_something; // File-local variable
263
extern int g_globvar;   // Global variable
264
265 8 quintus
class MyClass {
266 11 quintus
    void myFunc() {
267 1 quintus
        int* p_int;                   // Local variable
268
        m_normal_member += "AAA";     // Accessing member variable
269 11 quintus
        doSomething(MyClass::foobar); // Exception: accessing static member variable via class name, not directly
270 1 quintus
    }
271 7 quintus
272 1 quintus
    std::string m_normal_member;    // Normal member variable
273
    int* mp_int;                    // Member variable with pointer
274
    static const float foobar = 42; // Exception: Static member variable
275
};
276
277 10 quintus
struct Point {
278 1 quintus
    int x;            // Struct members have no "m" prefix
279 7 quintus
    int y;
280
    int z;
281
    owner* p_owner;   // But they do have the type prefix if required.
282
};
283 8 quintus
284 13 quintus
Point moveUp(Point p)
285 8 quintus
{
286 1 quintus
    p.y -= 10;         // Access to struct member without "m"
287
    return p;
288 7 quintus
}
289
290 10 quintus
enum class Color { red, green, blue }; // Exception: enum members do not have "m"
291 11 quintus
void myFunc(color c)
292 8 quintus
{
293 10 quintus
    if (c == Color::red) { // Because they are accessed only from the outside.
294 7 quintus
      // ...
295
    }
296
}
297
~~~~~~~~~~~
298
299
## enum specifics
300
301
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).
302
303
~~~~~~ c++
304 10 quintus
enum class Color { red, green, blue };
305 7 quintus
306 11 quintus
void foo(Color c)
307 8 quintus
{
308 7 quintus
    // ...
309
}
310
~~~~~~
311
312 14 quintus
## Use of namespaces
313
314
If the STL is used, always include the STL namespace at the top of the `.cpp` file. The same goes for internal namespaces (that is, those that are defined by the game itself).
315
316
~~~~~ c++
317
#include <iostream>
318
319
using namespace std;
320
using namespace InternalNameSpace;
321
322
void main()
323
{
324
    cout << "Doing something" << endl; // Actually std::cout and std::endl
325
    doIt(); // Actually InternalNamespace::DoIt()
326
}
327
~~~~~
328
329
Library namespaces should normally be spelled out in full, unless they are exceptionally long. In that case, abbreviate them with `namespace` at the top of the `.cpp` file.
330
331
~~~~~~~ c++
332
namespace LLN = LongLibraryNamespace;
333
// ...
334
LLN::foo var;
335
~~~~~~~
336
337
If a library namespace is needed really often in a function, you can include it _in that function only_.
338
339
~~~~~~~ c++
340
void Foo::someFunction()
341
{
342
    using namespace MyLib;
343
    // All the below functions come from the MyLib namespace
344
    doA();
345
    doB();
346
    doC(0);
347
    doD("foo");
348
}
349
~~~~~~~
350
351 7 quintus
## File names
352
353 1 quintus
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`.
354
355 14 quintus
## Guidelines for headers
356 1 quintus
357 14 quintus
### Header guards
358 1 quintus
359 14 quintus
All headers use header guards. The header guard is composed from the filename without the file extension coverted to CAPITAL_LETTERS.
360 1 quintus
361 14 quintus
~~~~~ c++
362
// my_file.hpp
363
#ifndef MY_FILE
364
#define MY_FILE
365
// ...
366
#endif
367
~~~~~
368 7 quintus
369 14 quintus
### Namespaces in headers
370
371
Namespaces in headers are always spelled out in full and not abbreviated or included. This includes the STL namespace if it is used. This way the inclusion of a header does not define unexpected new namespaces.
372
373
~~~~~~ c++
374
namespace MyNamespace {
375
    class MyClass {
376
        MyClass();
377
        std::vector<std::string> m_my_values;
378
    }
379
}
380 7 quintus
~~~~~~~
381
382 15 quintus
### Forward declarations in headers
383 7 quintus
384 8 quintus
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.
385 11 quintus
386 7 quintus
~~~~~~~~~~ c++
387
// Forward declarations
388
class MyClass;
389
390
class MyOtherClass {
391 1 quintus
public:
392
    MyOtherClass(MyClass& mc) : m_mc(mc){}
393
    void foo(MyClass* p_mc){ /* ... */ }
394
private:
395
    MyClass& m_mc;
396
};
397
~~~~~~~~~~
398
399
The corresponding `.cpp` file will then have to include the internal header for `MyClass`:
400
401
~~~~~~ c++
402
#include "my_other_class.hpp"
403
#include "../misc/my_class.hpp" // <---
404
~~~~~~
405 14 quintus
406
### Inclusion of headers
407
408
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:
409
410
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.
411
2. Other internal headers.
412
3. External library headers.
413
4. Standard library headers.
414
415
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 ""`.
416
417
~~~~~~~ c++
418
// This is foo.cpp, it has a header foo.hpp.
419
#include "foo.hpp"
420
#include "../misc/internal_header.hpp"
421
#include <curl.h>
422
#include <vector>
423
#include <cstdlib>
424
~~~~~~~