DEV Community

CoderGears
CoderGears

Posted on

10 Essential Best Practices for Writing High-Quality C++ Source Code

Writing high-quality code is critical to the success of any software project, as it affects the reliability, performance, and maintainability of the code. In this blog post, we will discuss 10 essential best practices included in CppDepend for writing clean and efficient C++ source code. These best practices cover various aspects of coding, such as naming conventions, error handling, memory management, and more. Whether you are a beginner or an experienced programmer, following these best practices will help you write better C++ code and make your projects more successful.

1– Use descriptive and meaningful variable names: When naming variables, choose names that describe the purpose of the variable and are meaningful to the reader. This makes your code easier to read and understand.

#include <iostream>
​
int main()
{
    // GOOD EXAMPLE
    int userAge = 25;
    const int kDaysInWeek = 7;
    std::string firstName = "John";
​
    // BAD EXAMPLE
    int a = 25;
    int b = 7;
    std::string c = "John";
}
Enter fullscreen mode Exit fullscreen mode

2- Write readable code: Use proper indentation, whitespace, and comments to make your code easier to read. Additionally, break up long lines of code into smaller, more manageable blocks.

// GOOD EXAMPLE
for (int i = 0; i < 10; i++)
{
    cout << i << endl;
}
​
// BAD EXAMPLE
for(int i=0;i<10;i++)cout<<i<<endl;
Enter fullscreen mode Exit fullscreen mode

3- Use object-oriented programming: C++ is an object-oriented language, so make use of its features, such as classes and objects, to organize and structure your code.

#include <iostream>
#include <fstream>
​
int main()
{
    // GOOD EXAMPLE
    std::ifstream file("data.txt");
    if (!file.is_open())
    {
        std::cerr << "Error: Failed to open file." << std::endl;
        return 1;
    }
​
    // Read and process file data here
​
    file.close();
    return 0;
​
    // BAD EXAMPLE
    std::ifstream file("data.txt");
    // Read and process file data here
    file.close();
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

4- Avoid using global variables: Global variables can cause problems in larger projects, as they can easily be modified from different parts of the code. Instead, use local variables within functions and classes.

// GOOD EXAMPLE
void printSum(int x, int y)
{
    int sum = x + y;
    cout << "The sum is: " << sum << endl;
}
​
// BAD EXAMPLE
int sum;
​
void printSum(int x, int y)
{
    sum = x + y;
    cout << "The sum is: " << sum << endl;
}
Enter fullscreen mode Exit fullscreen mode

5- Make use of error handling: Make sure to handle errors and exceptions in your code, such as division by zero, invalid input, or out-of-bounds array access.

// GOOD EXAMPLE
int main()
{
    int dividend, divisor;
    cout << "Enter dividend: ";
    cin >> dividend;
    cout << "Enter divisor: ";
    cin >> divisor;
    try
    {
        if (divisor == 0)
        {
            throw runtime_error("Division by zero.");
        }
        cout << "Result: " << dividend / divisor << endl;
    }
    catch (runtime_error &err)
    {
        cout << err.what() << endl;
    }
    return 0;
}
​
// BAD EXAMPLE
int main()
{
    int dividend, divisor;
    cout << "Enter dividend: ";
    cin >> dividend;
    cout << "Enter divisor: ";
    cin >> divisor;
    if (divisor == 0)
    {
        cout << "Division by zero." << endl;
        return 1;
    }
    cout << "Result: " << dividend / divisor << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

6- Keep functions short and simple: Functions should be short and focused, with a single purpose. If a function becomes too complex, consider breaking it down into smaller, more manageable functions.

// GOOD EXAMPLE
int add(int x, int y)
{
    return x + y;
}
​
// BAD EXAMPLE
int addAndMultiply(int x, int y)
{
    int sum = x + y;
    int product = x * y;
    cout << "Sum: " << sum << endl;
    cout << "Product: " << product << endl;
    return sum;
}
Enter fullscreen mode Exit fullscreen mode

7- Avoid hard-coding values: Instead of hard-coding values into your code, store them in constants or variables that can be easily changed. This makes your code more flexible and maintainable.

#include <iostream>
​
const int kDataSize = 100;
​
int main()
{
    // Good example
    int data[kDataSize];
    for (int i = 0; i < kDataSize; ++i)
        data[i] = i;
​
    // Bad example
    int data[100];
    for (int i = 0; i < 100; ++i)
        data[i] = i;
}
Enter fullscreen mode Exit fullscreen mode

8- Use standard libraries: C++ provides a rich set of standard libraries, including the Standard Template Library (STL), that can be used to perform common tasks. Making use of these libraries can simplify your code and improve performance.

// GOOD EXAMPLE
#include <iostream>
#include <string>
​
int main()
{
    std::string name;
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}
​
// BAD EXAMPLE
#include <iostream>
#include <string.h>
​
int main()
{
    char name[100];
    std::cout << "Enter your name: ";
    std::cin.getline(name, 100);
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

9- Keep code modular: Break your code into smaller, independent modules that can be easily tested and reused. This makes your code more maintainable and easier to modify.

// GOOD EXAMPLE
if (temperature > 30)
{
    cout << "It's hot outside." << endl;
}
else
{
    cout << "It's not hot outside." << endl;
}
​
// BAD EXAMPLE
if(temperature>30)cout<<"It's hot outside."<<endl;
else cout<<"It's not hot outside."<<endl;
Enter fullscreen mode Exit fullscreen mode

10- Document your code: Make sure to add comments to your code to describe its purpose, usage, and any assumptions that have been made. This makes it easier for others to understand your code and for you to remember how it works in the future.

#include <iostream>
​
// Good example
​
/**
 * Calculates the factorial of a given number.
 *
 * @param num The number to calculate the factorial of.
 * @return The factorial of the given number.
 */
unsigned long long factorial(unsigned int num)
{
    unsigned long long result = 1;
    for (int i = 2; i <= num; ++i)
        result *= i;
    return result;
}
​
// Bad example
​
unsigned long long f(unsigned int n)
{
    unsigned long long r = 1;
    for (int i = 2; i <= n; ++i)
        r *= i;
    return r;
}
Enter fullscreen mode Exit fullscreen mode

By following these best practices, you can write high-quality C++ source code that is easy to read, understand, and maintain.

Download CppDepend for free and see if your code is well-maintained!

Top comments (0)