[C++ Study Notes]: Maintainability

Avoid using compile macros

Macros are replaced by the preprocessor before compilation, making debugging very difficult because the debugger has no way of knowing where the source code comes from.

// Bad Idea
#define PI 3.14159;

// Good Idea
namespace my_project {
  class Constants {
  public:
    // if the above macro would be expanded, then the following line would be:
    //   static const double 3.14159 = 3.14159;
    // which leads to a compile-time error. Sometimes such errors are hard to understand.
    static constexpr double PI = 3.14159;
  };
}

Avoid using Boolean values ​​as function parameters

When reading the code, Boolean values ​​do not provide any additional meaning. You could create a standalone function with a more meaningful name, or pass a more meaningful enumeration value.

Avoid using naked loops

Understand and understand existing C++ standard algorithms and put them into practice.

  • Reference cpppreference[2]

  • Watch C++ Seasoning[3]

Consider []the call to a potential code smell, indicating that the appropriate algorithm is not being used where needed.

Never use anything that has side effectsassert

// Bad Idea
assert(set_value(something));

// Better Idea
[[maybe_unused]] const auto success = set_value(something);
assert(success);

It will be deleted in the release version assert()and set_valuecannot be called.

Although the second version is uglier, it's still better than the first buggy version.

Correct use of "override" and "final"

These keywords make it clear to other developers how a virtual function can be used, catch potential errors if the signature of a virtual function changes, and potentially hint to the compiler what optimizations can be performed.

Guess you like

Origin blog.csdn.net/Jiangziyadizi/article/details/129372769