8/4/2019 C++ Practices
1/44
C++ Practices
Guidelines to improve readability
of code
8/4/2019 C++ Practices
2/44
Naming Conventions
8/4/2019 C++ Practices
3/44
Names representing types must be in
mixed case starting with upper case
Line, SavingsAccount
8/4/2019 C++ Practices
4/44
Variable names must be in mixed case
starting with lower case.
line, savingsAccount Makes variables easy to distinguish from
types, and effectively resolves potential
naming collision as in the declaration Line
line
8/4/2019 C++ Practices
5/44
Named constants (including enumerationvalues) must be all uppercase using underscoreto separate words
In general, the use of such constants should beminimized. In many cases implementing thevalue as a method is a better choice:
int getMaxIterations() // NOT: MAX_ITERATIONS = 25
{return 25;
}
8/4/2019 C++ Practices
6/44
Names representing methods or functionsmust be verbs and written in mixed casestarting with lower case
getName(), computeTotalWidth()
Common practice in the C++ developmentcommunity. This is identical to variable
names, but functions in C++ are alreadydistingushable from variables by theirspecific form
8/4/2019 C++ Practices
7/44
Abbreviations and acronyms must not be
uppercase when used as name
exportHtmlSource();//NOT: exportHTMLSource(); openDvdPlayer();//NOT: openDVDPlayer();
8/4/2019 C++ Practices
8/44
Global variables should always be referred
to using the :: operator
::mainWindow.open(),::applicationContext.getName()
In general, the use of global variables
should be avoided
8/4/2019 C++ Practices
9/44
Private class variables should have
underscore suffix
class SomeClass { private: int length_; } void setDepth (int depth)
{
depth_ = depth;}
8/4/2019 C++ Practices
10/44
Generic variables should have the same
name as their type void setTopic(Topic* topic)
// NOT: void setTopic(Topic* value)
// NOT: void setTopic(Topic* aTopic)
// NOT: void setTopic(Topic* t)
void connect(Database* database)
// NOT: void connect(Database* db)
// NOT: void connect (Database* oracleDB)
8/4/2019 C++ Practices
11/44
Variables with a large scope should have long
names, variables with a small scope can have
short names
Scratch variables used for temporary storage orindices 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 cand
d.
8/4/2019 C++ Practices
12/44
The name of the object is implicit, and
should be avoided in a method name
line.getLength();// NOT:line.getLineLength();
8/4/2019 C++ Practices
13/44
The terms get/setmust be used where an
attribute is accessed directly
employee.getName();employee.setName(name);
matrix.getElement(2, 4);
matrix.setElement(2, 4, value);
8/4/2019 C++ Practices
14/44
The term compute can be used in
methods where something is computed
valueSet->computeAverage();
matrix->computeInverse()
8/4/2019 C++ Practices
15/44
The term findcan be used in methods
where something is looked up
vertex.findNearestVertex();matrix.findMinElement();
8/4/2019 C++ Practices
16/44
Variables representing GUI components
should be suffixed by the component type
name
mainWindow, propertiesDialog,
widthScale, loginText, leftScrollbar,
mainForm, fileMenu, minLabel, exitButton,
yesToggle etc
8/4/2019 C++ Practices
17/44
Plural form should be used on names
representing a collection of objects
int values[];
8/4/2019 C++ Practices
18/44
The suffix No should be used for variables
representing an entity number
tableNo, employeeNo
8/4/2019 C++ Practices
19/44
Iterator variables should be called i,j, ketc
for (int i = 0; i < nTables); i++){ : }
8/4/2019 C++ Practices
20/44
The prefix is should be used for boolean
variables and methods
isSet, isVisible, isFinished, isFound, isOpen
There are a few alternatives to the is prefix that
fit better in some situations. These are the has,
can and shouldprefixes:
bool hasLicense(); bool canEvaluate();
bool shouldSort();
8/4/2019 C++ Practices
21/44
Complement names must be used for
complement operations
get/set,add/remove,create/destroy,start/stop,insert/delete,increment/decreme
nt, old/new, begin/end, first/last, up/down,
min/max,next/previous,old/new,open/close
, show/hide, suspend/resume, etc.
Reduce complexity by symmetry
8/4/2019 C++ Practices
22/44
Abbreviations in names should be avoided
computeAverage();// NOT: compAvg();
8/4/2019 C++ Practices
23/44
Negated boolean variable names must be
avoided
bool is
Error;// NOT: isNoErrorboolisFound;// NOT: isNotFound
8/4/2019 C++ Practices
24/44
Exception classes should be suffixed with
Exception
class Access
Exception
{
:
}
8/4/2019 C++ Practices
25/44
Functions (methods returning something)
should be named after what they return
and procedures (voidmethods) after what
they do
getSum() and add()
8/4/2019 C++ Practices
26/44
Use of global variables should be
minimized
In C++ there is no reason global variablesneed to be used at all. The same is true
for global functions
8/4/2019 C++ Practices
27/44
Class variables should never be declared public
The concept of C++ information hiding andencapsulation is violated by public variables. Use privatevariables and access functions instead
One exception to this rule is when the class is essentiallya data structure, with no behavior (equivalent to a Cstruct). In this case it is appropriate to make the class'instance variables public
Note that structs are kept in C++ for compatibility with Conly, and avoiding them increases the readability of thecode by reducing the number of constructs used. Use aclass instead.
8/4/2019 C++ Practices
28/44
C++ pointers and references should havetheir reference symbol next to the typerather than to the name
float* x;// NOT: float *x;
int& y;// NOT: int &y;
Thepointer-ness orreference-ness of avariable is a property of the type ratherthan the name
8/4/2019 C++ Practices
29/44
Implicit test for0should not be used other
than for boolean variables and pointers
if (n
Lines != 0)// NOT: if (nLines)
if (value != 0.0)// NOT: if (value)
It is not necessarily defined by the C++
standard that ints and floats 0 areimplemented as binary 0
8/4/2019 C++ Practices
30/44
Variables should be declared in the
smallest scope possible
Keeping the operations on a variablewithin a small scope, it is easier to control
the effects and side effects of the variable
8/4/2019 C++ Practices
31/44
Only loop control statements must be
included in the for() construction
sum = 0; for (i = 0; i < 100; i++)sum += value[i];
// NOT: for (i = 0, sum = 0; i < 100; i++)sum += value[i];
8/4/2019 C++ Practices
32/44
Loop variables should be initialized immediately before the loop
isDone = false;
while (!isDone)
{
:}
// Not
isDone=false;
while(!isDone){
:
}
8/4/2019 C++ Practices
33/44
do-while loops can be avoided
do-while loops are less readable thanordinary while loops and forloops since
the conditional is at the bottom of the loop.The reader must scan the entire loop inorder to understand the scope of the loop.In addition, do-while loops are not needed.Any do-while loop can easily be rewritteninto a while loop or a forloop.
8/4/2019 C++ Practices
34/44
The use of break and continue in loops
should be avoided.
These statements should only be used ifthey give higher readability than their
structured counterparts
8/4/2019 C++ Practices
35/44
The form while(true) should be used for infinite loops
while (true)
{
:
}
for (;;)
{ // NO!
:
}
while (1){ // NO!
:
}
8/4/2019 C++ Practices
36/44
Functions must always have the return
value explicitly listed
int get
Value()// NOT: getValue() { : }
8/4/2019 C++ Practices
37/44
Basic indentation should be 2
for (i = 0; i < nElements; i++)
a[i] = 0;
Indentation of 1 is too small to emphasize thelogical layout of the code. Indentation larger than4 makes deeply nested code difficult to read andincreases the chance that the lines must be split.
Choosing between indentation of 2, 3 and 4, 2and 4 are the more common, and 2 chosen toreduce the chance of splitting code lines
8/4/2019 C++ Practices
38/44
The class declarations should have the
following form:
class SomeClass : public BaseClass {
public: ...
protected: ..private: ...
}
8/4/2019 C++ Practices
39/44
Method definitions should have the
following form
void some
Method()
{
...
}
8/4/2019 C++ Practices
40/44
The function return type can be put in the
left column immediately above the function
name
void
MyClass::myMethod(void)
{:
}
8/4/2019 C++ Practices
41/44
White Space
-Conventional operators should be surrounded
by a space character.
- C++ reserved words should be followed by awhite space.
- Commas should be followed by a white space.
- Colons should be surrounded by white space.
- Semicolons in for statments should be followedby a space character
8/4/2019 C++ Practices
42/44
Methods should be separated by three
blank lines
By making the space larger than spacewithin a method, the methods will stand
out within the class
8/4/2019 C++ Practices
43/44
Use//for all comments, including multi-
line comments
// Comment spanning// more than one line
8/4/2019 C++ Practices
44/44