Coding conventions - Spearis666/NG-Poster GitHub Wiki
This document lists C++ coding recommendations used in my software.
The recommendations are based on established standards collected from a number of sources and individual experience.
The recommendations are grouped by topic and each recommendation is numbered to make it easier to refer to during reviews.
Layout of the recommendations is as follows:
Example :
some exampleInformations :
Motivation, background and additional information.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
The main goal of the recommendation is to improve readability and thereby the understanding and the maintainability and general quality of the code. It is impossible to cover all the specific cases in a general guide and the programmer should be flexible.
The attempt is to make a guideline, not to force a particular coding style onto individuals. Experienced programmers normally want to adopt a style like this anyway, but having one, and at least requiring everyone to get familiar with it, usually makes people start thinking about programming style and evaluate their own habits in this area.
On the other hand, new and inexperienced programmers normally use a style guide as a convenience of getting into the programming jargon more easily.
Example :
Line, SavingsAccountInformations :
Common practice in the C++ development community.
Example :
line, savingsAccountInformations :
Common practice in the C++ development community. Makes variables easy to distinguish from types, and effectively resolves potential naming collision as in the declaration Line line;
5. Named constants (including enumeration values) MUST be all uppercase using underscore to separate words.
Example :
MAX_ITERATIONS, COLOR_RED, PIInformations :
Common practice in the C++ development community. In general, the use of such constants SHOULD be minimized.
6. Names representing methods or functions MUST be verbs and written in mixed case starting with lower case.
Example :
getName(), computeTotalWidth()Informations :
Common practice in the C++ development community. This is identical to variable names, but functions in C++ are already distingushable from variables by their specific form.
Example :
model::analyzer, io::iomanager, common::math::geometryInformations :
Common practice in the C++ development community.
Example :
exportHtmlSource(); // NOT: exportHTMLSource();
openDvdPlayer(); // NOT: openDVDPlayer();
Informations :
Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type whould have to be named dVD, hTML etc. which obviously is not very readable. Another problem is illustrated in the examples above; When the name is connected to another, the readbility is seriously reduced; the word following the abbreviation does not stand out as it SHOULD.
Example :
class SomeClass
{
private:
int length_;
}
Informations :
Apart from its name and its type, the scope of a variable is its most important feature. Indicating class scope by using underscore makes it easy to distinguish class variables from local scratch variables. This is important because class variables are considered to have higher significance than method variables, and SHOULD be treated with special care by the programmer.A side effect of the underscore naming convention is that it nicely resolves the problem of finding reasonable variable names for setter methods and constructors:
void setDepth (int depth)
{
depth_ = depth;
}
An issue is whether the underscore should be added as a prefix or as a suffix. Both practices are commonly used, but the latter is recommended because it seem to best preserve the readability of the name.
It should be noted that scope identification in variables has been a controversial issue for quite some time. It seems, though, that this practice now is gaining acceptance and that it is becoming more and more common as a convention in the professional development community.
Example :
void setTopic(Topic* topic) // NOT: void setTopic(Topic* value)
Informations :
Reduce complexity by reducing the number of terms and names used. Also makes it easy to deduce the type given a variable name only.
If for some reason this convention doesn't seem to fit it is a strong indication that the type name is badly chosen.
11. Variables with a large scope SHOULD have long names, variables with a small scope can have short names.
Scratch variables used for temporary storage or indices are best kept short. A programmer reading such variables SHOULD be able to assume that its value is not used outside of a few lines of code. Common scratch variables for integers are i, j, k, m, n and for characters c and d.
Example :
line.getLength(); // NOT: line.getLineLength();
Informations :
The latter seems natural in the class declaration, but proves superfluous in use, as shown in the example.
Example :
employee.getName();
Informations :
Common practice in the C++ development community.
Example :
valueSet->computeAverage();
Informations :
Give the reader the immediate clue that this is a potentially time-consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.
Example :
matrix.findMinElement();
Informations :
Give the reader the immediate clue that this is a simple look up method with a minimum of computations involved. Consistent use of the term enhances readability.
Example :
printer.initializeFontSet();
Informations :
The american initialize SHOULD be preferred over the English initialise. Abbreviation init SHOULD be avoided.
Example :
mainWindow, propertiesDialog, widthScale, loginText, leftScrollbar, mainForm, fileMenu, minLabel, exitButton, yesToggle etc.Informations :
Enhances readability since the name gives the user an immediate clue of the type of the variable and thereby the objects resources.
Example :
vector<Point> points;
Informations :
Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements.
Example :
nPoints, nLinesInformations :
The notation is taken from mathematics where it is an established convention for indicating a number of objects.
Example :
iTable, iEmployeeInformations :
The notation is taken from mathematics where it is an established convention for indicating an entity number.
An alternative is to suffix such variables with an No: tableNo, employeeNo.
Example :
for (int i = 0; i < nTables); i++) {
doSomething();
}
Informations :
The notation is taken from mathematics where it is an established convention for indicating iterators.
Variables named j, k etc. SHOULD be used for nested loops only.
Example :
isSet, isVisible, isFinished, isFound, isOpenInformations :
Common practice in the C++ development community and partially enforced in Java.
Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to choose more meaningful names.There are a few alternatives to the is prefix that fit better in some situations. These are the has, can and should prefixes:
bool hasLicense();
bool canEvaluate();
bool shouldSort();
Example :
get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, old/new, open/close, show/hide, suspend/resume, etc.Informations :
Reduce complexity by symmetry.
Example :
computeAverage(); // NOT: compAvg();
Informations :
There are two types of words to consider. First are the common words listed in a language dictionary. These MUST NOT be abbreviated. Never write:
cmd instead of command
cp instead of copy
pt instead of point
comp instead of compute
init instead of initialize
etc.
Then there are domain specific phrases that are more naturally known through their abbreviations/acronym. These phrases SHOULD be kept abbreviated. Never write:
HypertextMarkupLanguage instead of html
CentralProcessingUnit instead of cpu
PriceEarningRatio instead of pe
etc.
Example :
Line* line; // NOT: Line* pLine;
Informations :
Many variables in a C/C++ environment are pointers, so a convention like this is almost impossible to follow. Also objects in C++ are often oblique types where the specific implementation SHOULD be ignored by the programmer. Only when the actual type of an object is of special significance, the name SHOULD emphasize the type.
Example :
bool isError; // NOT: isNoError
Informations :
The problem arises when such a name is used in conjunction with the logical negation operator as this results in a double negative. It is not immediately apparent what !isNotFound means.
Example :
enum Color {
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE
};
Informations :
This gives additional information of where the declaration can be found, which constants belongs together, and what concept the constants represent.An alternative approach is to always refer to the constants through their common type: Color::RED, Airline::AIR_FRANCE etc.
Note also that the enum name typically SHOULD be singular as in enum Color {...}. A plural name like enum Colors {...} may look fine when declaring the type, but it will look silly in use.
28. Functions (methods returning something) SHOULD be named after what they return and procedures (void methods) after what they do.
Increase readability. Makes it clear what the unit SHOULD do and especially all the things it is not supposed to do. This again makes it easier to keep the code clean of side effects.
29. C++ header files SHOULD have the extension .h (preferred) or .hpp. Source files can have the extension .cpp (recommended), .C, .cc or .c++.
Example :
MyClass.cpp, MyClass.hInformations :
These are all accepted C++ standards for file extension.
30. A class SHOULD be declared in a header file and defined in a source file where the name of the files match the name of the class.
Example :
MyClass.h, MyClass.cppInformations :
Makes it easy to find the associated files of a given class. An obvious exception is template classes that MUST be both declared and defined inside a .h file.
Example :
class MyClass
{
public:
int getValue () {return value_;} // NO!
}
Informations :
The header files SHOULD declare an interface, the source file SHOULD implement it. When looking for an implementation, the programmer SHOULD always know that it is found in the source file.
Informations :
80 columns is a common dimension for editors, terminal emulators, printers and debuggers, and files that are shared between several people SHOULD keep within these constraints. It improves readability when unintentional line breaks are avoided when passing a file between programmers.
These characters are bound to cause problem for editors, printers, terminal emulators or debuggers when used in a multi-programmer, multi-platform environment.
Example :
totalSum = a + b + c +
d + e;
//
setText ("Long line split"
"into two parts.");
//
for (int tableNo = 0; tableNo < nTables;
tableNo += tableStep) {
doSomething();
}
Informations :
Split lines occurs when a statement exceed the 80 column limit given above. It is difficult to give rigid rules for how lines SHOULD be split, but the examples above SHOULD give a general hint.In general:
- Break after a comma.
- Break after an operator.
- Align the new line with the beginning of the expression on the previous line.
Example :
#ifndef COM_COMPANY_MODULE_CLASSNAME_H
#define COM_COMPANY_MODULE_CLASSNAME_H
//
#endif // COM_COMPANY_MODULE_CLASSNAME_H
Informations :
The construction is to avoid compilation errors. The name convention resembles the location of the file inside the source tree and prevents naming conflicts.
36. Include statements SHOULD be sorted and grouped. Sorted by their hierarchical position in the system with low level files included first. Leave an empty line between groups of include statements.
Example :
#include <fstream>
#include <iomanip>
//
#include <qt/qbutton.h>
#include <qt/qtextfield.h>
//
#include "com/company/ui/PropertiesDialog.h"
#include "com/company/ui/MainWindow.h"
Informations :
In addition to show the reader the individual include files, it also give an immediate clue about the modules that are involved.
Include file paths MUST never be absolute. Compiler directives SHOULD instead be used to indicate root directories for includes.
Common practice. Avoid unwanted compilation side effects by "hidden" include statements deep into a source file.
Enforces information hiding.
39. The parts of a class MUST be sorted public, protected and private (in this order). All sections MUST be identified explicitly. public, protected and private MUST be separated with a blank line. Not applicable sections SHOULD be left out. Order is constructor(s), destructor(s), members functions, getters, setters and datas members. All this part SHOULD be preceded with FUNCTIONS, EVENTS FUNCTIONS, FUNCTIONS - GETTER, FUNCTIONS - SETTER, DATA depending on the type.
Example :
class Test : public Worker
{
public:
Test();
~Test();
//
/***********************************************************************
* FUNCTIONS *
**********************************************************************/
void doSomething();
//
/***********************************************************************
* FUNCTIONS - GETTER *
**********************************************************************/
int getX();
//
/***********************************************************************
* FUNCTIONS - SETTER *
**********************************************************************/
void setX(int x);
//
/***********************************************************************
* DATA *
**********************************************************************/
int x_;
}
Informations :
With ordering "public first" people who only wish to use the class can stop reading when they reach the protected/private sections.
Example :
floatValue = static_cast<float>(intValue); // NOT: floatValue = intValue;
Informations :
By this, the programmer indicates that he is aware of the different types involved and that the mix is intentional.
This ensures that variables are valid at any time. Sometimes it is impossible to initialize a variable to a valid value where it is declared:
int x, y, z;
getCenter(&x, &y, &z);
In these cases it SHOULD be left uninitialized rather than initialized to some phony value.
In C++ there is no reason global variables need to be used at all. The same is true for global functions or file scope (static) variables.
The concept of C++ information hiding and encapsulation is violated by public variables. Use private variables and access functions instead. One exception to this rule is when the class is essentially a data structure, with no behavior (equivalent to a C struct). In this case it is appropriate to make the class' instance variables public.
Note that structs are kept in C++ for compatibility with C only, and avoiding them increases the readability of the code by reducing the number of constructs used. Use a class instead.
44. C++ pointers and references SHOULD have their reference symbol next to the type rather than to the name.
Example :
float* x; // NOT: float *x;
int& y; // NOT: int &y;
Informations :
The pointer-ness or reference-ness of a variable is a property of the type rather than the name. C-programmers often use the alternative approach, while in C++ it has become more common to follow this recommendation.
Example :
if (nLines != 0) // NOT: if (nLines)
if (value != 0.0) // NOT: if (value)
Informations :
It is not necessarily defined by the C++ standard that ints and floats 0 are implemented as binary 0. Also, by using an explicit test the statement gives an immediate clue of the type being tested.It is common also to suggest that pointers SHOULDn't test implicitly for 0 either, i.e. if (line == 0) instead of if (line). The latter is regarded so common in C/C++ however that it can be used.
Keeping the operations on a variable within a small scope, it is easier to control the effects and side effects of the variable.
Example :
sum = 0;
for (i = 0; i < 100; i++)
sum += value[i];
//
// NOT :
for (i = 0, sum = 0; i < 100; i++)
sum += value[i];
Informations :
Increase maintainability and readability. Make a clear distinction of what controls and what is contained in the loop.
Example :
isDone = false;
while (!isDone) {
doSomething();
}
//
// NOT :
bool isDone = false;
doSomething();
while (!isDone) {
doSomething();
}
do-while loops are less readable than ordinary while loops and for loops since the conditional is at the bottom of the loop. The reader MUST scan the entire loop in order to understand the scope of the loop.
In addition, do-while loops are not needed. Any do-while loop can easily be rewritten into a while loop or a for loop. Reducing the number of constructs used enhance readbility.
These statements SHOULD only be used if they give higher readability than their structured counterparts.
Example :
while (true) {
doSomething();
}
Informations :
Testing against 1 is neither necessary nor meaningful. The form for (;;) is not very readable, and it is not apparent that this actually is an infinite loop.
Example :
bool isFinished = (elementNo < 0) || (elementNo > maxElement);
bool isRepeatedEntry = elementNo == lastElement;
if (isFinished || isRepeatedEntry) {
doSomething();
}
//
// NOT:
if ((elementNo < 0) || (elementNo > maxElement)||
elementNo == lastElement) {
doSomething();
}
Informations :
By assigning boolean variables to expressions, the program gets automatic documentation. The construction will be easier to read, debug and maintain.
53. The nominal case SHOULD be put in the if-part and the exception in the else-part of an if statement.
Example :
bool isOk = readFile (fileName);
if (isOk) {
doSomething();
} else {
doSomething();
}
Informations :
Makes sure that the exceptions don't obscure the normal path of execution. This is important for both the readability and performance.
Example :
if (isDone)
doCleanup();
//
// NOT: if (isDone) doCleanup();
Informations :
This is for debugging purposes. When writing on a single line, it is not apparent whether the test is really true or not.
Example :
File* fileHandle = open(fileName, "w");
if (!fileHandle) {
doSomething();
}
//
// NOT:
if (!(fileHandle = open(fileName, "w"))) {
doSomething();
}
Informations :
Conditionals with executable statements are just very difficult to read. This is especially true for programmers new to C/C++.
56. The use of magic numbers in the code SHOULD be avoided. Numbers other than 0 and 1 SHOULD be considered declared as named constants instead.
If the number does not have an obvious meaning by itself, the readability is enhanced by introducing a named constant instead. A different approach is to introduce a method from which the constant can be accessed.
Example :
double total = 0.0; // NOT: double total = 0;
double speed = 3.0e8; // NOT: double speed = 3e8;
Informations :
This emphasizes the different nature of integer and floating point numbers. Mathematically the two model completely different and non-compatible concepts.Also, as in the last example above, it emphasizes the type of the assigned variable (sum) at a point in the code where this might not be evident.
Example :
double total = 0.5; // NOT: double total = .5;
Informations :
The number and expression system in C++ is borrowed from mathematics and one SHOULD adhere to mathematical conventions for syntax wherever possible. Also, 0.5 is a lot more readable than .5; There is no way it can be mixed with the integer 5.
Example :
int getValue() // NOT: getValue()
Informations :
If not exlicitly listed, C++ implies int return value for functions. A programmer MUST never rely on this feature, since this might be confusing for programmers not aware of this artifact.
Goto statements violate the idea of structured code. Only in some very few cases (for instance breaking out of deeply nested structures) SHOULD goto be considered, and only if the alternative structured counterpart is proven to be less readable.
NULL is part of the standard C library, but is made obsolete in C++.
Example :
for (i = 0; i < nElements; i++)
a[i] = 0;
Informations :
Indentation of 1 is too small to emphasize the logical layout of the code. Indentation larger than 4 makes deeply nested code difficult to read and increases the chance that the lines MUST be split.
63. Block layout MUST be as illustrated in example 1/2 below. Function and class blocks MUST use the block layout of example 3/4. Constructor with initialization list MUST be as illustrated in example 5 (colon on new line, first initialization after 3 spaces, each new initialization on new line, opening bracket on new line).
Example :
// Example 1:
while (!done) {
doSomething();
done = moreToDo();
}
//
// Example 2:
while (
!done &&
!nextStep)
{
doSomething();
done = moreToDo();
}
//
// Example 3:
void test()
{
doSomething();
moreToDo();
}
//
// Example 4:
void test(
int param1,
int param2)
{
doSomething();
moreToDo();
}
//
// Example 5:
void test(int iValue, int iValue2)
: iValue_(iValue),
iValue_2(iValue2)
{
doSomething();
moreToDo();
}
Example :
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
Informations :
This follows partly from the general block rule above.
Example :
switch (condition) {
case ABC :
statements;
// Fallthrough
case DEF :
statements;
break;
default :
statements;
break;
}
Informations :
Note that each case keyword is indented relative to the switch statement as a whole. This makes the entire switch statement stand out. Note also the extra space before the : character. The explicit Fallthrough comment SHOULD be included whenever there is a case statement without a break statement. Leaving the break out is a common error, and it MUST be made clear that it is intentional when it is not there.
Example :
try {
statements;
} catch (Exception& exception) {
statements;
}
Informations :
This follows partly from the general block rule above.
Example :
if (condition)
statement;
//
while (condition)
statement;
//
for (initialization; condition; update)
statement;
Informations :
It is a common recommendation that brackets SHOULD always be used in all these cases. However, brackets are in general a language construct that groups several statements. Brackets are per definition superfluous on a single statement. A common argument against this syntax is that the code will break if an additional statement is added without also adding the brackets. In general however, code SHOULD never be written to accommodate for changes that might arise.
68. Function call parameter exceding the max 80 line lenght MUST use new blank line for each parameter, with the first also on new line. Indentation of closing parenthesis must be on new line, following the opening parenthesis indentation.
Example :
doSomething(
param1,
doAnotherThing(
param1,
param2
),
param3
);
- Conventional operators MUST be surrounded by a space character.
- C++ reserved words MUST be followed by a white space.
- Commas MUST be followed by a white space.
- Colons MUST be surrounded by white space.
- Semicolons in for statments MUST be followed by a space character.
Example :
a = (b + c) * d; // NOT: a=(b+c)*d
while (true) // NOT: while(true)
doSomething(a, b, c, d); // NOT: doSomething(a,b,c,d);
case 100 : // NOT: case 100:
for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++)
Informations :
Makes the individual components of the statements stand out. Enhances readability. It is difficult to give a complete list of the suggested use of whitespace in C++ code. The examples above however SHOULD give a general idea of the intentions.
Example :
AsciiFile* file;
int nPoints;
float x, y;
Informations :
Enhance readability. The variables are easier to spot from the types by alignment.
Example :
if (a == lowValue) compueSomething();
else if (a == mediumValue) computeSomethingElse();
else if (a == highValue) computeSomethingElseYet();
//
value = (potential * oilDensity) / constant1 +
(depth * waterDensity) / constant2 +
(zCoordinateValue * gasDensity) / constant3;
//
minPosition = computeDistance(min, x, y, z);
averagePosition = computeDistance(average, x, y, z);
//
switch (value) {
case PHASE_OIL : strcpy(phase, "Oil"); break;
case PHASE_WATER : strcpy(phase, "Water"); break;
case PHASE_GAS : strcpy(phase, "Gas"); break;
}
Informations :
There are a number of places in the code where white space can be included to enhance readability even if this violates common guidelines. Many of these cases have to do with code alignment. General guidelines on code alignment are difficult to give, but the examples above SHOULD give a general clue.
In general, the use of comments SHOULD be minimized by making the code self-documenting by appropriate name choices and an explicit logical structure.
In an international environment English is the preferred language.
Example :
// Comment spanning
// more than one line.
Informations :
Since multilevel C-commenting is not supported, using // comments ensure that it is always possible to comment out entire sections of a file using /* */ for debugging purposes etc.
Example :
while (true) {
/// Do something
something();
}
//
// NOT :
while (true) {
// Do something
something();
}
Informations :
This is to avoid that the comments break the logical structure of the program.
Regarding standardized class and method documentation the Java development community is more mature than the C/C++ one.