Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Refactoring with C++

You're reading from   Refactoring with C++ Explore modern ways of developing maintainable and efficient applications

Arrow left icon
Product type Paperback
Published in Jul 2024
Publisher Packt
ISBN-13 9781837633777
Length 368 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Mr. Dmitry Danilov Mr. Dmitry Danilov
Author Profile Icon Mr. Dmitry Danilov
Mr. Dmitry Danilov
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. Chapter 1: Coding Standards in C++ 2. Chapter 2: Main Software Development Principles FREE CHAPTER 3. Chapter 3: Causes of Bad Code 4. Chapter 4: Identifying Ideal Candidates for Rewriting – Patterns and Anti-Patterns 5. Chapter 5: The Significance of Naming 6. Chapter 6: Utilizing a Rich Static Type System in C++ 7. Chapter 7: Classes, Objects, and OOP in C++ 8. Chapter 8: Designing and Developing APIs in C++ 9. Chapter 9: Code Formatting and Naming Conventions 10. Chapter 10: Introduction to Static Analysis in C++ 11. Chapter 11: Dynamic Analysis 12. Chapter 12: Testing 13. Chapter 13: Modern Approach to Managing Third Parties 14. Chapter 14: Version Control 15. Chapter 15: Code Review 16. Index 17. Other Books You May Enjoy

Why coding standards are important

Coding standards are important for several reasons. First and foremost, they help to minimize technical debt. Technical debt, also known as “code debt,” is a metaphor that describes the cost of maintaining and modifying code that is not well designed or well written. Just as financial debt incurs interest and requires ongoing payments, technical debt incurs additional costs in the form of the time and effort needed to maintain and modify poorly designed code.

Technical debt can accumulate in many ways, such as through hacky or quick-fix solutions to problems or by ignoring best practices or coding standards. As technical debt accumulates, it can become increasingly difficult and time-consuming to modify and maintain the code, which can negatively impact the efficiency and effectiveness of a development team.

In order to manage technical debt carefully, it is essential to try to avoid accumulating too much of it, as it can become a significant burden on a development team. Strategies for managing technical debt include regularly refactoring code to improve its design and maintainability, following best practices and coding standards, and actively seeking out opportunities to improve the quality of the code. Overall, managing technical debt is an important aspect of good code design and development and can help to ensure that code is efficient, reliable, and easy to work with.

Coding standards help to ensure the quality and consistency of code. By establishing a set of guidelines and conventions for writing code, coding standards help to ensure that code is well written, easy to read, and easy to understand. This makes it easier for others to maintain and update the code and helps to prevent errors and bugs.

In addition, they help to improve the efficiency of code. By following established conventions and best practices, programmers can write code that is more efficient and performs better. This can save time and resources and help ensure that code is scalable and can handle large amounts of data and traffic.

Furthermore, coding standards promote collaboration and teamwork among programmers. By establishing a common set of guidelines and conventions, coding standards make it easier for teams of programmers to work together on a project. This allows better communication and coordination and helps to ensure that everyone is on the same page and working towards the same goals.

Coding standards often promote the interoperability and portability of code. By following a standardized set of conventions, code written by one programmer can be easily understood and used by another programmer. This allows code to be more easily integrated into larger projects and helps to ensure that it can be used on a variety of different platforms and operating systems.

The C++ programming language is probably one of the richest languages in terms of features. It started as C with classes, providing object-oriented support with high performance and almost complete compatibility with C; later on, template metaprogramming was introduced, and Stepanov and Lee developed the Standard Template Library, nowadays known as the C++ Standard Library. Modern C++ (C++11 and newer versions) provides extensive support for multiple programming paradigms, including procedural, object-oriented, generic, and functional programming. It offers features such as lambda expressions, range-based for loops, smart pointers, and type inference that enable functional programming techniques. Additionally, C++ provides support for object-oriented programming concepts such as inheritance, encapsulation, and polymorphism. It also offers template metaprogramming, which enables generic programming and allows compile-time optimizations. Furthermore, C++ provides concurrency support with features such as threads, atomic types, and futures, making it easier to write concurrent and parallel code. This flexibility is key to the strength of the language but often leads to problems with maintainability.

A developer has to understand the concepts of the paradigms we’ve mentioned, how to use them together, and how they eventually affect the performance of the code. This is when coding standards can help to explain the complexity of the code base.

All these factors make coding guidelines the bare minimum that a modern C++ project should have to attain a quality standard.

Code convention

Contrary to languages such as Python, Go, Java, and many others, C++ does not have a common code convention.

There are several popular coding conventions for the C++ programming language. Here are some common conventions that are widely followed:

  • Naming conventions: Naming conventions specify how to name variables, functions, classes, and other code elements in a descriptive manner. For example, variables may be named using lowercase letters, with words separated by underscores, such as total_cost or customer_name. Class variables often have prefixes or suffixes to distinguish them from other variables, such as m_user_count or user_count_. Functions may be named using camelCase, with the first letter of each word (apart from the first word) capitalized, such as calculateTotalCost or getCustomerName. Classes may be named using PascalCase, with the first letter of each word capitalized, such as Customer or Invoice.
  • Commenting: Commenting conventions specify how to write and format comments in code. Comments are used to provide explanations and documentation for code and should be clear and concise. It is often recommended to use inline comments to explain specific lines of code, as well as block comments to provide an overview of a code block or function.
  • Formatting: Formatting conventions specify how to format code for readability and consistency. This may include conventions for indentation, spacing, line breaks, and other elements of code layout. For example, it is common to indent code blocks, such as those inside a for loop or if statement, to visually indicate the structure of the code. Formatting policy often covers asterisk (*) and ampersand (&) alignment in pointers and references (e.g., int* ptr versus int *ptr or Socket &socket versus Socket& socket), curly braces position (same line, next line, or context dependent). This book covers aspects of automated formatting in Chapter 13.
  • Coding style: Coding style conventions specify how to write and structure code for clarity and readability. This may include conventions for variable declarations, control flow, and other elements of code structure, such as how variables are passed to functions (by value, reference, or pointer) and the usage of specific language features, such as exceptions and goto operators.

It is important to note that there may be variations in coding conventions between different organizations and teams. It is important to follow the conventions that your team or organization establishes or to define your own conventions if none are specified.

It can be tedious to develop a coding convention; some companies prefer to use an existing one and adapt it to their needs. In the C++ programming language, there are several popular code standards that are widely followed by developers. These standards aim to improve the readability, maintainability, and overall quality of C++ code.

One common code standard for C++ is the C++ Core Guidelines (https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines), which were developed by Bjarne Stroustrup, the creator of C++, and a group of experts from industry and academia. The guidelines cover a wide range of topics, including naming conventions, commenting, formatting, and coding style.

Another popular code standard for C++ is the Google C++ Style Guide (https://google.github.io/styleguide/cppguide.html), which is used by many software companies, including Google. The guide provides guidelines for naming conventions, commenting, formatting, and coding style, as well as recommendations for using specific C++ features and libraries.

In addition to these widely followed standards, there are also many other code standards that have been developed by individual organizations and teams, for example, LLVM Coding Standards, WebKit, and Mozilla’s style guides.

If a project conforms with a specific code convention, it is easier to read it, and as a bonus, the code base becomes more grepable. Consider needing to find the places where a variable called request_id is assigned. It can be easily achieved via the grep utility:

$ grep -rn "request_id = " .
./RequestHandler.cpp:25: request_id = new_request_id;
./RequestHandler.cpp:122: request_id = request.getId();

Code reviewers used to spend hours catching and commenting on inconsistencies with code format during peer review. Luckily, today we have tools such as Clang-Tidy and Clang-Format that allow us to ensure the consistency of the code format automatically via code editors and continuous integration (CI). We will dive deeper into their configuration later in this book in Chapter 10.

Language features limitations

C++ is a powerful language; as we know, great power comes with great responsibility. It is not easy for engineers, especially those who have not spent decades writing C++ code, to grasp the complexity of the language. As a result, some companies decide to limit the features used in their projects. The limitations may include a ban for multiple inheritance, usage of exceptions, and minimal usage of macros, templates, and specific third-party libraries. Additionally, the regulations may come from the use of legacy libraries. For example, if most of the code does not support C++ exceptions, it might be a bad idea to add them to new pieces of code without a prior understanding of the outcome.

General guidelines

It is always a good idea to have general guidelines for a project. The guidelines often cover the preferred way of working on the project:

  • Usage of raw pointers, if allowed
  • How values are returned from getters and provided to setters (by value or reference)
  • Use of code comments:
    • Are comments allowed in general?
    • Usage of strategic and tactical comments
    • Comment style: free, Doxygen, and so on

Coding standards are necessary to help ensure code quality, consistency, interoperability, portability, efficiency, and collaboration. By following coding standards, programmers can write better code that is easier to understand, maintain, and use and works better and more efficiently.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image