University of Leeds

Code Style

Introduction

Code style is a hugely important aspect of coding which is often neglected by novices. Indeed, a cursory glance at how code is written will often tell you if it has been written by a professional or a novice.

Professional programmers stick to very strict code style guidelines and indeed, are often forced to by their employers. Ensuring that all employees use the same coding style means that they can all easily read each others code.

The Google C++ Style Guide is popular and will form the basis of the style used in this module, which you are encouraged to adopt and follow. This will make you into a better and more professional programmer.

End of lines and files

When writing code in the IDE, you should not put any trailing white-spaces at the end of a line of code. After you have typed the last character, which in many cases will be a semi-colon ; you should directly press return to start a new line without adding in any random spaces.

This also applies at the end of the file. The last character in the file is usually a } to mark the end of a function. There should be no spaces or blank lines at the end of the file. Code is often profiled to see how many lines long it is and random blank lines at the end of files can alter the count.

1
2
3
4
5
6
int main() {

  // Code here

  return 0;
}

Tabs and indentation

When indenting your code (e.g. in if statements or for loops), you should use spaces instead of a tab character. The Google Style Guide recommends using 2 spaces. Most IDE's can be configured to emit spaces instead of tab characters when the tab key is pressed.

Horizontal whitespace

It is usual to leave a space around an operator.

1
int sum = 0;

When creating expressions, it is usual to leave spaces between operators and literals/variables.

1
int c = sum * 4 + 5;

Opening braces should always have a space before them as shown in the examples below. However, note that this isn't the case when declaring the size of an array using square brackets.

1
2
3
4
5
for (int i = 0; i < 10; i++) {

int main() {

int array[5] = {1, 2, 3, 4, 5};

As we can see in the examples above, there is usually no space before semi-colons ; and no space inside empty brackets e.g. main(). When it comes to conditionals, there is a space after the key word and spaces around else e.g.

1
2
3
4
5
if (n < 0) {
  std::cout << "Negative\n";
} else {
  std::cout << "Positive\n";
}

When using for loops, there is always a space after the semi-colons.

1
for (int i = 0; i < 10; i++) {

When commenting, there is a space between the forward slashes and the start of the comment.

1
// this is a useless comment

Leave two spaces after the semi-colon and before the start of the comment.

1
int z = 0;  // variable to store top score

Vertical whitespace

You should minimise the amount of vertical whitespace (e.g. blank lines). Use only one blank line between functions and do not start or end a function with a blank line. Blank lines inside functions to split up code into different sections can make code more readable, but do this sparingly as having too many means less lines of code are visible on the screen at once, making de-bugging and reading code more difficult. At the end of the day, it is a balance and you should keep these points in mind.

The example below shows too much vertical whitespace.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
int calc_sum(int a, int b) {

    int sum = a+b;
    return sum;

}


int calc_product(int a, int b) {

    int product = a*b;
    return product;

}

The code should instead be formatted like so:

1
2
3
4
5
6
7
8
9
int calc_sum(int a, int b) {
    int sum = a+b;
    return sum;
}

int calc_product(int a, int b) {
    int product = a*b;
    return product;
}

Examples

Taking into account the white space rules introduced previously, some examples of how to properly structure and style loops and conditionals are below.

1
2
3
for (int i = 0; i < 10; i++) {
    sum += i;
}

1
2
3
4
while (i < 10) {
    std::cout << i << std::endl;
    i++;
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
if (grade > 70) {
  std::cout << "Class I\n";
} else if (grade > 60) {
  std::cout << "Class II.i\n";
} else if (grade > 50) {
  std::cout << "Class II.ii\n";
} else if (grade > 40) {
  std::cout << "Class III\n";
} else {
  std::cout << "Fail\n";
}

However, judicious use of blank lines inside a long chain of if..else statements may help readability.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
if (grade > 70) {
  std::cout << "Class I\n";

} else if (grade > 60) {
  std::cout << "Class II.i\n";

} else if (grade > 50) {
  std::cout << "Class II.ii\n";

} else if (grade > 40) {
  std::cout << "Class III\n";

} else {
  std::cout << "Fail\n";
}

Naming

It is very important to have a consistent naming style for variables, classes and functions. Variable names should be descriptive, in lower-case with underscores connecting multiple words e.g.

1
double price_of_item = 0.99;

Functions should also be in lower-case with underscores connecting multiple words. The name should be descriptive.

1
calc_average_score();

Classes should also start with a capital letter with a capital letter for each word, whereas objects are named in the same manner as variables.

1
MyClass my_object;

Class private member variables are named in the same manner as standard variables with a preceding underscore.

1
int _member_variable;

Pre-processor defines should be in upper case.

1
#define PI 3.14159265359

Filenames should be in lowercase with underscores between words. The .cpp extension is used for C++ programs and .h for header files

my_source_file.cpp

my_header_file.h

Comments

C++ style comments // are much more common and are preferred over C-style block comments /* */.

1
// This is a useless comment

Note the space between the forward slashes and the start of the comment.

There should be comments at the top of each file with useful information about the contents of the file.

1
2
3
4
// Program to calculate the sum of the first n prime numbers
// Author: Craig A. Evans
// Company: University of Leeds
// Date: 1st June 2018

Using descriptive variable names makes code self-documenting and removes the need for pointless comments.

1
int z = 0;  // Variable to store top score

A better approach would simply be

1
int top_score = 0;

All function declarations should have comments immediately preceding it, explaining what the function does and what are its inputs and outputs. This is not required for completely trivial and simple functions.

Code that is non-trivial should always be commented to let the reader know what is does. It is common to have lines of comments before a block of complex code, and additional end of line comments for any non-obvious lines of code that require extra explanation. Again, having well-written code can help to make it self-documenting and removes the need for (pointless) comments.

1
2
3
4
// check if all lives lost and if so, call game over function
if (x == 0) {
  func();
}

1
2
3
if (lives_left == 0) {
  game_over();
}

Functions

Functions should be used to break up code into smaller, more manageable chunks. This allows code to be more easily de-bugged, tested and maintained. There is no formal limit to the length of a function, but once it gets to between 20 and 40 lines, you should consider splitting it up into further, smaller sub-functions.

Function names should be descriptive, as already mentioned. There should be no blank lines at the start and end of a function. For a simple one-line function like the one below, it can be defined on a single line.

1
2
3
int product(int a, int b) {
  return a*b;
}

1
int product(int a, int b) { return a * b; }

ClangFormat

There are many tools available that help developers format their code according to particular coding styles. One such tool is ClangFormat.

When ClangFormat is installed on a machine, it can automatically reformat code in accordance with several common styles, including Google's. Several websites also exist that host ClangFormat and allow you to paste in unformatted code. These online tools then automatically re-format your code to a style of your choosing, from which it can be pasted back into your editor.

Packages also exist for Atom and Visual Studio Code editors that enables ClangFormat to automatically format code from within the editors themselves. A code formatted is installed by default in VS Code C/C++ extension.

Summary

You should take care when writing code and get into the habit of applying clear and consistent styling to your code. It really is important and puts you on track to becoming a professional software engineer.

Writing poorly structured and inconsistently-styled code is a very distinctive signature of a novice programmer. It demonstrates that the developer is lazy, cuts corners and does not take pride in their work.

If you worked for a company and were in charge of hiring a graduate software engineer, which one of these would you employ?