CST2550 Code Guidelines 2020
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
CST2550 Code Guidelines
2020
1 Introduction
It is common for software projects (and employers) to have code guidelines to ensure code is clear, consistent, maintainable and easier to understand and debug.
The following code guidelines are based roughly on those used on large real software projects, but limited and simplified to avoid topics not covered in this module.
You should always aim to follow them, especially when working on coursework, as this will result in clearer, more easily maintainable code. Following these guidelines will also result in your coursework achieving higher marks for code quality.
Note: sometimes examples, e.g. in lecture slides do not follow these guidelines. This is to allow you to focus on the topics being covered and to fit examples in limited space in lecture slides.
2 Layout
2.1 Comment block
Each file should start with a comment block introducing the file, stating the author name (Note: for your coursework submissions use only your student ID, not your name to allow anonymous marking), creation date and last updated date. For example:
1 /*
2 foo . cpp
3 Author : John Smith <JS@mdx . ac .uk >
4 Created : 1/7/2018
5 Updated : 23/5/2020
6 */
2.2 Header guards
Header files should also have header guards wrapping the whole file. An upper-case, unique name (normally the file name surrounded by underscores) should be used:
1 2 3 4 5 6 7 8 9 10 11 |
|
# ifndef _PRODUCTS_H_ # define _PRODUCTS_H_ /* products .h Author : John Smith <JS@mdx . ac .uk > Created : 1/1/2020 Updated : 1/1/2020 */ // ... header file code ... |
12 # endif
2.3 Include statements
Include required STL library headers and/or your own header files. When including your headers you should only give the name of the header file, not a directory structure (which will not be the same on another machine, e.g. when marking your coursework). Fore example:
1 # include <vector >
2 # include " products .h" // just the header file name
1 # include <vector >
2 # include "/user/home/john/work/ project / products .h" // not the path
2.4 Line length
Lines of code should not be so long that they do not show in the editor window. Therefore, lines
should not be longer than 80 characters long.
Longer lines should be sensibly split across multiple lines, e.g.:
1 double vector_ dot_product (std :: vector <double > vector1 ,
2 std :: vector <double > vector2 );
When code is split across multiple lines it should be indented appropriately.
2.5 Namespaces
You should prefix library functions with the namespace where appropriate. Including using namespace statements will pollute the namespace with all functions from the specified namespace, which can lead to confusion and bugs.
1 std :: cout << "Hello , World ! " << std :: endl; // include namespace
1 using namespace std; // Don l t do this
2 cout << "Hello , World ! " << endl;
2.6 Indentation
Code should be indented appropriately, e.g. the body of blocks of code (functions, loops, etc) should be indented. Indentation should be done consistently thoughout all of your source code.
This makes the code clearer.
2.7 White space
White space should be used between operators and parameters:
1 double average = ( number1 + number2 ) / 2 . 0; // clear
2
3 double average =( number1 + number2 )/2 . 0; // not as clear
Blank lines should be used to seperate sections of code. However, you should not have large gaps of multiple blank lines scattered throughout your source code or inconsistent spacing.
2.8 Curly brackets
The opening curly bracket (e.g. for a loop) can either be placed on the end of the opening line or on the line below. The closing curly bracket should line up with the start of the start of the opening statement, e.g.:
1 if (x) {
2 // ... some code ...
3 for (int i = 0; i < QTY; ++i) {
4 // ... some code ...
5 }
6 }
7
8 // or
9
10 if (x)
11 {
12 // ... some code ...
13 for (int i = 0; i < QTY; ++i)
14 {
15 // ... some code ...
16 }
17
18 }
2.9 Comments
Comments should be used to describe sections of code which are unclear. They shouldn’t be used on every line or to duplicate obvious code. For example:
1 // Generate 、QTY l random numbers between MIN and MAX ( inclusive ) 2 for (int i = 0; i < QTY; ++i) {
3 values [i] = rand () % (MAX_MIN + 1) + MIN;
4 }
But do not include pointless comments, e.g. just duplicating code rather than describing something which isn’t already in the code:
1 int x = 0; // integer variable called x initialized to zero 2 x = 5; // assign 5 to x
3 x++; // increment x
Comments should also be used before functions, classes and at the start of each source code file.
3 Variables
3.1 Naming
Variables names should be clear and descriptive (but not overly long). Very short variable names should be limited to small sections of code and only for standard and clear uses, e.g. an index variable i in a for loop.
Variable names should be lower-case (with either underscores or camel-case to separate words). Initial capitals should be used for class names and all upper-case for constants.
1 // these are clear
2 const double PAGE_WIDTH = 21 . 5;
3 int tab_ stop = 4;
4
5 // not clear
6 const double pw = 21 . 5;
7 int T = 4;
3.2 Global variables
You normally shouldn’t have global variables and should never have more than a few of them. If you often have global variables in your source files or have many of them, rethink your software design.
3.3 Local variables
Local variables should be clearly named using lower-case letters. The scope of the variables should be limited to the area they are being used, e.g. variables only used in a loop should be limited to the body of the loop.
Local variables should be initialised either when they are defined, e.g.:
1 double total = 0;
Or nearby when the value is to be set by » (or similar), e.g.:
1 int qty;
2 std :: cout << " Enter the qualtity : " ;
3 std :: cin >> qty;
When defining a pointer variable, the * should be placed with type, not the variable name:
1 Node * left; // OK
2 Node * right ;
3
4 Node * middle ; // Not like this
3.4 Constants
Variables which shouldn’t change in a program should be defined as constants (using const). Constants should have upper-case names. You should never use define to define constants in C++. Example:
1 const double CLOCK_RADIUS = 5; // OK
1 # define CLOCK_RADIUS 5 // Don l t do this
3.5 Magic numbers
Magic numbers should not be included in your program. Instead you should assign variables (normally constants) with the values to make it clear what they are for.
4 Functions
4.1 Length
Functions (including member functions) should perform a single task and should not be excessively long. If a function is longer than 50 lines, you should consider breaking it into smaller functions or re-writing it.
4.2 Naming
Function names should be clear and descriptive of what task the function performs.
4.3 Parameters and return values
Parameter names should be clear and descriptive. When a single value is returned from a function this should be done using the return value rather than a void function which updates a reference parameter.
However, it is acceptable to update reference parameters when multiple values are returned, or when it makes sense to update the parameter, e.g. a function which sorts the elements of a vector.
4.4 Comments
There should be a comment before the function explaining what task it performs. Listing the parameters and return value, e.g.
/*
Calculate the area of a circle from the radius .
@param radius the radius of the circle
@return the area of a circle with the given radius
*/
double cirle_ area (int radius )
{
return M_PI * pow(radius , 2);
}
The @return should be omitted for void functions.
Classes
Classes should be declared such that any classes are declared before they are used (e.g. inside another class).
Note: normally your classes should be declared in separate header file(s).
5.1 Layout
Classes should be laid out as follows:
class /*ClassName */
{
private :
/* members (data)*/
/* private member functions */
public :
/* constructors */
/* destructors */
/* public member functions */
};
Access modifiers
Almost always all member variables of classes should be private. If your design requires public member variables, think very carefully about why. You should probably rethink your design.
5.3 Naming
Class names should be lower-case with an initial capital letter. Class, member and member function names should all be clear and descriptive.
Members and member functions should not be prefixed with the class name.
6 Control flow
Control flow constructs, e.g. for loops, should be used in a clear and standard way.
Statements such as break, continue, goto etc. should be used very sparingly, almost always a loop can be redesigned in a clearer way without using break. If you find you are using them regularly, rethink your design.
There are almost no good uses of goto, so do not use it in your code.
Only use a switch statement over if/else if/else if the fall though behaviour is desired for some reason. If you find all (or most) of your cases have break statements if would be clearer and less likely to introduce bugs.
2022-06-22