Considering Maintainability

Avoid Compiler Macros

Compiler definitions and macros are replaced by the preprocessor before the compiler is ever run. This can make debugging very difficult because the debugger doesn’t know where the source came from.

  1. // Bad Idea
  2. #define PI 3.14159;
  3. // Good Idea
  4. namespace my_project {
  5. class Constants {
  6. public:
  7. // if the above macro would be expanded, then the following line would be:
  8. // static const double 3.14159 = 3.14159;
  9. // which leads to a compile-time error. Sometimes such errors are hard to understand.
  10. static constexpr double PI = 3.14159;
  11. };
  12. }

Consider Avoiding Boolean Parameters

They do not provide any additional meaning while reading the code. You can either create a separate function that has a more meaningful name, or pass an enumeration that makes the meaning more clear.

See http://mortoray.com/2015/06/15/get-rid-of-those-boolean-function-parameters/ for more information.

Avoid Raw Loops

Know and understand the existing C++ standard algorithms and put them to use. See C++ Seasoning for more details.

Never Use assert With Side Effects

  1. // Bad Idea
  2. assert(set_value(something));
  3. // Better Idea
  4. [[maybe_unused]] const auto success = set_value(something);
  5. assert(success);

The assert() will be removed in release builds which will prevent the set_value call from every happening.

So while the second version is uglier, the first version is simply not correct.

Properly Utilize ‘override’ and ‘final’

These keywords make it clear to other developers how virtual functions are being utilized, can catch potential errors if the signature of a virtual function changes, and can possibly hint to the compiler of optimizations that can be performed.