[C++] [Naming Convention] What is your code style? (Camel case, underscore, Pascal, constant, etc.)

Foreword:

        In C/C++, the naming rules of class names, interface names, variable names, and function names are relatively free, and developers can choose an appropriate naming method according to their own preferences. However, in order to keep the code readable and maintainable, we usually follow some naming rules.

        For example, camel case naming, underscore naming, Pascal naming, constant naming, etc. In addition, some common code writing styles (such as {}) and two programming habits that affect code execution are extended at the end of this article (using const type &, with NULL=p).

1. Common nomenclature

1. CamelCase nomenclature

        CamelCase is a relatively common naming rule for variable names and function names. Its naming method is to capitalize the first letter of each word and lowercase the other letters (the first letter of the first word is lowercase). For example:

int myNumber;
void doSomething();

        This is a more readable naming method, making variable names and function names clear and easy to understand.

2. Underscore nomenclature

        Underscore nomenclature is a  _ nomenclature that separates words with underscores. It can increase the readability of variable names and function names, especially when the variable names and function names are relatively long, it is easier for people to understand. For example:

int my_number;
void do_something();

3. Pascal nomenclature

        Pascal nomenclature is a naming method that capitalizes the first letter of each word. It is similar to CamelCase, except that each word in PascalCase must be capitalized. For example:

class MyClassName {
  // ...
};

class MyInterfaceName {
  virtual void doSomething() = 0;
};

4. Hungarian nomenclature

        Hungarian notation is prefixed with the data type, followed by a word describing the purpose of the variable. For example:

int iCount;
float fPrice;
char cFirstChar;

This naming method is more readable, but as the complexity of the code increases, the naming length will greatly increase.

5. Dash nomenclature ( not recommended )

The dash nomenclature is similar to the underscore nomenclature, except that dashes are used  - instead of underscores  _.

let first-name = "John";
let last-name = "Doe";

        Note that using the dash nomenclature can also sometimes lead to less readable code, since it is used as a syntax symbol for the minus sign in some languages ​​and environments. Therefore, when choosing a naming convention, you need to consider its readability and understandability, as well as the habits and norms of the specific language and environment.

6. All caps nomenclature

This way of naming is to put the whole name in capital letters, for example:

MY_VARIABLE = "some value"
# 使用全部大写字母来表示一个变量名,但这不是常量

MY_LIST = [1, 2, 3]
# 使用全部大写字母来表示一个列表变量名

7. Constant nomenclature

        All-caps nomenclature and constant nomenclature are essentially the same, converting each letter of an identifier to uppercase to represent a constant. When naming constants, one of the above two naming methods can also be used, for example:

const int MAX_NUMBER = 100;
const double PI = 3.1415926;

        No matter which naming method is used, the naming should be clear, easy to read and understand, and help to improve the readability and maintainability of the code. When writing code, you should follow the naming rules to keep the code consistent and clean.

Second, the customary use in C/C++

1. Class name and interface name

        In C++, class and interface names should be clear, readable and understandable, usually using Pascal nomenclature. Because class names and interface names are an important part of the code, they represent specific objects or concepts, and should be described in the form of nouns or verbs + nouns. For example:

class MyClassName {
  // ...
};

class MyInterfaceName {
  virtual void doSomething() = 0;
};

        It should be noted that class names and interface names should be as concise as possible, and describe clear and clear concepts, while avoiding the use of long names. In addition, in order to maintain the consistency of naming, class names and interface names can also use other naming methods, such as camel case naming method or underscore naming method.

2. Function name

In C++, function names should be clear, readable and understandable, usually using camelCase or underscore naming.

The naming rule of CamelCase is to capitalize the first letter of each word. For example:

void myFunction();
void doSomethingWithData();

The naming rule of underscore nomenclature is to  _ connect words with underscores. For example:

void my_function();
void do_something_with_data();

        It should be noted that no matter which naming method is used, the function name should be clear, easy to read and understand, and the function of the function can be expressed in forms such as verbs or nouns. At the same time, the function name should also conform to the naming convention and style of the code to maintain the consistency of naming.

3. Variable name

In C++, variable names should be clear, readable and understandable, usually using camelCase or underscore naming.

The naming rule of CamelCase is to capitalize the first letter of each word. For example:

int myVariable;
float myFloatVariable;

The naming rule of underscore nomenclature is to  _ connect words with underscores. For example:

int my_variable;
float my_float_variable;

        It should be noted that no matter which naming method is used, the variable name should be clear, easy to read and understand, and the meaning and function of the variable can be expressed in the form of nouns or adjectives. At the same time, the variable name should also conform to the naming convention and style of the code to maintain the consistency of naming.

4. Enumeration naming

Use the Pascal nomenclature to name the enumeration name; use the constant nomenclature to name the enumeration value.

Here are some examples of enum names:

enum DayOfWeek {    // 一周的日
  SUNDAY,
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY
};

3. Recommendation, extension and extension

Recommended code style display:

  • The class name/interface name adopts the Pascal naming method;
  • Function names are named in camel case;
  • Variable names are named with underscores;
  • Constants use constant naming
class MyClass { // 类名使用帕斯卡命名法
public:
    void myFunction(); // 函数名使用驼峰式命名法
private:
    int my_variable; // 变量名使用下划线命名法
    const int MY_CONSTANT = 100; // 常量名使用全大写字母,单词间使用下划线分隔
};

        In fact, I personally think that as long as you are used to it (you can see the name and know the meaning), it is fine, and I did not say which one you must use; but this situation is not recommended, the style often changes (in fact, it is scribbled, for example, the name of the function in a program appear in several different styles).

extension:

Observe the following two styles of code, pay attention to the difference in the use of {}.

Code 1:


    if (something_is_true) 
    {
        // do something
    } 
    else 
    {
        // do something else
    }

Code 2: 


    if (something_is_true) {
        // do something
    } else {
        // do something else
    }

Thinking: see which one do you prefer to use? (Still the same, mixing is not recommended!) 

Extension:

         The above are all style issues. In fact, the essence does not affect the code execution (it only affects people's mood, especially when looking at other people's code). The following two cases are extended. This is not only a matter of code style, but may also affect the execution results of the program.

Case 1:

        Add const when passing parameters to prevent accidental modification of the original value.


void process_string(const string &str) {
  cout << "The length of the string is: " << str.length() << endl;
}

        Using parameters in a function  const string & can improve the efficiency and performance of the program, but the input string cannot be modified because the parameter is passed by reference.

Case 2:

        There is a coding habit in C language that puts the constant in front of the comparison expression, so if you write == as = (assignment operator), the compiler will report an error.

int *p = NULL;
if (p == NULL) {
  printf("p is null\n");
}

// 或者用 Yoda 表达式
if (NULL == p) {
  printf("p is null\n");
}

        Of course, when using C++11 and above, it is recommended to use the nullptr keyword instead of the NULL pointer constant. (C++11 and above, you don't need to pay attention to this habit.)

Summarize:

        This article mainly shares some common naming style habits (such as camel case naming method, underscore naming method, Pascal naming method, constant naming method, etc.), and recommends class names, interface names, function names, variable names and constants in C/C++ to readers The common naming style, and some common code writing styles (such as {}) are extended, and finally two programming habits that affect code execution are extended.

        I hope this article can bring some help to readers. At the same time, enthusiastic code friends are welcome to provide their own opinions and share them in the comment area!

Guess you like

Origin blog.csdn.net/crr411422/article/details/131020036