Coding Standard

Identifying all the components contributing to a well-designed program can be challenging. The following list serves as a starting point and is used to evaluate class projects. While there may be some exceptions, they are not typical and should not overshadow the general guidelines. Consider how these guidelines apply when reviewing a program rather than focusing on potential exceptions. The checklist will be extended as the semester progresses.

Files and Directories

Only source files belong in the repository:

Generated files do not belong in the repository:

Generated files take up a lot of file space and prevent others from easily cloning and building the repository.

Overall Program

Indentation

Spacing

Code Explanation
Single space after start of comment
Single space after keywords of statements
Single space before operators See above
Single space after operators See above
No space between call name and argument list
No space before statement-end semi-colon

Naming

Statements

Functions

Parameter Types

Use the following tables for type T:

Direction Primitive Object
IN T const T&
OUT, IN/OUT T& T&

Examples:

Return Types

For free functions:

Type Application Example
T Return copy of a local variable
T Return copy of a parameter
const T& Return a read-only reference to a parameter

Comments

The following applies to all comments except file header comments.

std::string

Prefer the default and methods common to a container:

Prefer   Explanation
By default a std::string is an empty string
A std::string is a (specialized) container. Prefer container methods over comparison. One exception might be in a set of if statements (such as a nested if) that compares the string to other literal strings.
Prefer container method to assignment

std::string_view

Prefer std::string_view if referring to an existing string or part of a string.

One of the problems with const std::string& parameter is that it makes a copy of a literal c-string.

Declaration Call Memory
void f(const std::string& s); std::string s; f(s); Refers to the existing string
void f(const std::string& s); f("abc"); Creates a std::string copy

The string type std::string_view was an addition to C++ in C++17. It allows you to efficiently refer to parts of a pre-existing std::string or a c-string char* without making a copy. It has many of the same methods as the std::string, and when the memory for the string already exists, it just refers to it, and no copies are made:

Declaration Call Memory
void f(std::string_view s); std::string s; f(s); Refers to the existing string
void f(std::string_view s); f("abc"); Refers to the existing string

The IN parameter of a std::string_view is passed by value instead of const reference as it consumes only a small amount of memory.

Debugging Output

Write debugging/tracing messages to std::cerr, not std::cout:

std::cerr for error output