Example of coding principle------C + + programming principles and Practice (Advanced article)

Source: Internet
Author: User

Coding principles:

    • General principles
    • Pretreatment principles
    • Naming and layout principles
    • Class principle
    • function and expression principles
    • Hard real-time principle
    • Key System Principles

(Hard real-time principles, Key system principles only for hard real-time and critical system programming)

(The strict principle is identified with a capital letter R and its number, and the recommendation principle is identified with the lowercase letter R and its number, for the former programmer must strictly abide by, while the latter can occasionally be non-compliance)

1. General principles

R100: The code size of any function and class should not exceed 200 lines (not including comments).

Reason: Long functions and classes are more complex and therefore difficult to understand and test.

R101: Any function and class should be fully displayed on one screen and complete a single logical function.

Cause: If a programmer can see only part of a function or class, it is likely that the wrong part is missing. If a function tries to complete multiple functions, it can be large and complex compared to a single-function function.

R102: So the code should comply with ISO/IEC 14882:2011 (E) C + + standards.

Cause: Expansion amount on the ISO/IEC 14882 standard may be distorted, undefined, and may affect portability.

2. Pretreatment principle

R200: Do not use macros other than #ifdef and #ifndef for source control.

Cause: Macros do not follow the definition domain and type rules, and make the code less legible and unreadable.

R201: #include can only be used to include header files (*.h).

Cause: #include the declaration used to access the interface rather than the implementation details.

R202: So the #incldue statement should precede any non-preprocessing declaration.

Cause: If the # include statement is in the middle of the program, it is most likely ignored by the person reading the program, and it can easily result in inconsistent parsing of the names in different parts of the program.

R203: Header file (*.h) should not contain definitions of very variable variables or non-inline, non-template function definitions.

Cause: The header file should contain interface declarations rather than implementation details. However, constants are often seen as part of the interface; For performance reasons, some very simple functions should be used as inline functions (and therefore should be placed in the header file), whereas the current compiler requires that the full template definition be placed in the header file.

3. Naming and layout principles

R300: Indentation should be used, and the indentation style should be consistent in one source file.

Reason: Readability and code style.

R301: Each new statement has a different line.

Reason: readability.

Example:

int a=7;x=a+7;f (x,9);    Violate
int a=7;x=a+7;f (x,9); That's right

Example:

if (p<q) cout<<*p;    violation if (p<q)    cout<<*p;    That's right

  

R302: The name of the identifier should be descriptive.

Identifiers can contain common abbreviations and word-head thumbnails.

If x, Y, I, J are used in a customary way, it can be considered descriptive.

Use the Underline style (number_of_elements) instead of the word-head thumbnail style (numberofelement).

Do not use Hungarian nomenclature.

The naming of types, templates, and namespaces begins with uppercase letters.

Avoid too long a name.

Examples: Device_driver and Buffer_poor.

Reason: readability.

Note: the C + + standard stipulates that identifiers that begin with an underscore are reserved for use by the language implementation and therefore should be banned in the user program.

Exception: Calling a certified library, names from the library can be used.

R303: Identifiers cannot differ only in the following ways:

    • The case is different;
    • Only the difference underlines;
    • Only the letter O, the number 0 or the letter D between the substitution;
    • Only the letter I, the number 1 after the letter l between the substitution;
    • Just a replacement between the letter S and the number 5;
    • Only literal z and Word 2 are replaced;
    • Just the letters with N and the letter H are replaced directly.

Example: Head and head//violation

Reason: readability.

R304: Identifiers cannot contain only uppercase letters and underscores.

Example: Blue and Blue_cheese//violation

Cause: The identifiers for all uppercase letters are widely used for macro names and may be used in an # include file in a certified library instead of the client program.

Exception: The macro name is used to protect # include without being duplicated.

4. function and expression principles

R400: The identifier for the inner loop and the identifier for the outer loop should not have the same name.

Reason: Readability and code style.

Example:

int var=9; {int Var=7;++var}    Violation: VAR duplicate name

  

R401: The scope of the declaration should be as small as possible.

Cause: Keep the variables initialized and used as close as possible to reduce the likelihood of confusion, freeing the variables that leave the scope from their resources.

R402: So the variables are initialized.

Example:

int var;    //violation: VAR not initialized

Cause: Uninitialized variables are often the source of the error.

Exception: If an array or container immediately accepts data from the input, it does not have to be initialized.

Note: Many types, such as vectors and strings, have default constructors to complete initialization.

R403: Type conversions should not be used.

Cause: Type conversion is the source of the error.

Exception: Dynamic_cast can be used.

Exception: A new style of type conversion can be used to convert a hardware address into a pointer, or to convert a void* obtained from outside a program, such as a GUI library, to a pointer of the appropriate type.

R404: The built-in array type should not be used in the function interface, that is, if a function argument is a pointer, it must point to a single element. If you want to pass an array, you should use Array_ref.

Cause: Arrays can only be passed as pointers, and the number of elements cannot be attached to them, but can only be passed separately. Also, the implicit array-to-pointer conversion and the conversion of derived classes to the base class can cause memory errors.

5. Class principle

R500: For classes that do not have a common data member, declare it with class. For classes that do not have private data members, declare with a struct. Do not define classes that have both common data members and private data members.

Reason: clarity.

r501: If a class contains a destructor or a member of a pointer/reference type, you must define it appropriately or disallow (that is, you cannot use the default version) to copy the constructor and copy assignment operators.

Cause: Destructors typically release resources. For classes with destructors or pointers and reference types, the default copy semantics is almost impossible to "do the right Thing".

R502: If the class contains a virtual function, it must have a virtual destructor.

Cause: Virtual functions can be used through the base class interface, and functions that access objects through the base class interface may delete the object, and the derived class must have some mechanism (destructor) to clean up the work.

R503: Constructors that accept a single argument must be explicitly declared.

Cause: Avoid strange implicit type conversions.

6. Hard real-time principle

R800: Exceptions should not be used.

Cause: The exception is unpredictable.

R801:new can only be used when initializing.

Cause: not predictable.

Exception: You can allocate memory from the stack with addressable new.

R802: You should not use Delete.

Cause: Unpredictable and may cause fragmentation.

R803: dynamic_cast should not be used.

Cause: Unpredictable (assuming that the normal method is used).

R804: Standard reservoir should not be used, except Std::array

Cause: Unpredictable (assumed to be implemented in a normal way).

7. Key System Principles

R900: Increment and decrement operations cannot be used as sub-expressions.

Example:

int x=v[++i];    Violate

++i;
int x=v[i]; That's right

Cause: It may be missed out.

R901: Code should not rely on precedence rules under algorithm expression precedence.

Example:

X=a*b+c;    That's right

Example:

if (a<b| | C<=d)    //violation: parentheses (a<b) and (C<=d) should be added

Cause: The code written by a poorly-C + +-based programmer often has a situation of priority confusion.

Principles and Practice of C + + programming (Advanced article)

Example of coding principle------C + + programming principles and Practice (Advanced article)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.