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 t examples in limited space in lecture slides.

2    Layout

2.1    Comment block

Each file should start with a comment block introducing the le, 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  /*

      foo . cpp

     Author :  John  Smith  <JS@mdx . ac .uk >

      Created :   1/7/2018

     Updated :  23/5/2020

6  */

2.2    Header guards

Header files should also have header guards wrapping the whole le. An upper-case, unique name (normally the le 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 les. When including your headers you should only give the name of the header le, not a directory structure (which will not be the same on another machine, e.g. when marking your coursework). Fore example:

 # include  <vector >

 # include   " products .h"  //  just  the  header   file  name

 # include  <vector >

 # 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.:

 double  vector_ dot_product (std :: vector <double >  vector1 ,

                                                            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.

 std :: cout  <<  "Hello ,  World ! "  <<  std :: endl;  //  include  namespace

 using  namespace   std;  //  Don l t  do  this

 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.:

 if   (x)  {

    //   ...   some  code   ...

    for   (int  i  =  0;  i  <  QTY;  ++i)  {

        //   ...   some  code   ...

    }

 }

7

 //  or

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:

 //  Generate   、QTY l  random  numbers  between  MIN  and  MAX   ( inclusive ) 2  for   (int  i  =  0;  i  <  QTY;  ++i)  {

    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:

 int  x  =  0;  //  integer  variable  called  x  initialized  to  zero 2  x  =   5;  //  assign   5  to  x

 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.

 //  these  are  clear

 const  double  PAGE_WIDTH  =  21 . 5;

 int  tab_ stop  =  4;

 //  not  clear

 const  double  pw  =  21 . 5;

 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 les 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 dened, e.g.:

 double  total  =  0;

Or nearby when the value is to be set by » (or similar), e.g.:

 int  qty;

 std :: cout  <<  " Enter  the  qualtity :  " ;

 std :: cin  >>  qty;

When dening a pointer variable, the * should be placed with type, not the variable name:

 Node *  left;  //  OK

2  Node *  right ;

3

 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

 # 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 le(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 modiers

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 prexed with the class name.

6    Control ow

Control ow 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 nd 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 nd all (or most) of your cases have break statements if would be clearer and less likely to introduce bugs.