Code comments you don't know, but code comments

Source: Internet
Author: User

Code comments you don't know, but code comments

What kind of code is good code. This is actually a matter of opinion, and there is no uniform standard in the industry. I carefully reviewed my evaluation code methods and summarized five evaluation indicators.

  • Scale
  • Execution efficiency
  • Occupied Space
  • Readability
  • Scalability

These five dimensions have strong or weak associations with each other. You can refer to this system for rough comparison between any two codes, but there is no absolute comparison between them.

1. Scale the scale here refers to the size of the code, that is, the number of lines of code included in the program that solves the same problem. From this perspective, the smaller the code size, the better. The smaller the size, the higher the complexity of the code, and the lower the readability.

There is an interesting situation where beginners and technical experts are both very different in terms of code scale. However, their demands are completely different.

1.1 beginners pursue simplicity

The simplest way for beginners to evaluate code is to look at the code size. They always think that programs with fewer lines of code are simpler. Some people often ask why I have to write more than 20 lines of code for the solution, but there are only a dozen lines of code on the Internet. So let me talk about the dozens of lines of code. I can only say that the dozen lines of code come from introduction to algorithms. I need to use four ~ It is not guaranteed to be thorough in five sections.

In the field of programming, it is often simple and not easy to understand. It may contain more advanced and complex ideas. These are difficult for beginners.

for (k = 0; k < n; k++) {     for (i = 0; i < n; i++)     {         for(j = 0; j < n; j++)         {             if (D[i][j] > D[i][k] + D[k][j])             {                 D[i][j] = D[i][k] + D[k][j];                 P[i][j] = P[i][k];             }     } }

This is a classic algorithm used to calculate the distance between any two points in the matrix. It is called Floyd and has only six lines of code. When I participated in the ACM competition that year, I memorized this code. Later I have not carefully studied the principle of this algorithm, and I will only use it now. In most cases, it is not the optimal algorithm.

1.2 of the top cattle are pursuing peace of mind

The reason why Daniel pursues a small number of lines of code must be to improve execution efficiency, however, there are also some people who have not developed good habits for many years and are also known as "Daniel" by using their own experience to save some time writing. I have seen this Code:

typedef struct _tagNode{    int m_nID;    int m_nSN;    int m_nMode;    int m_nCode;}Node;Node arrNodes[100];

This code should have been written to define a data structure and the result was written as follows by a "Daniel:

int arr[100][4];

The nine lines of code are converted into one line to reduce the workload. Of course, for beginners, such a two-dimensional array may not be able to handle. I have also seen more exaggerated code:

int arr[100][50][30][5];

The person who writes this line of code is still a "Daniel" with many years of work experience. This four-dimensional array is inspired by the storm. It's just a bitter trap, but a colleague who later took over his work.

In this way, the pursuit of code scale is not advisable.

2. execution efficiency

In a sense, the first requirement on the program should be execution efficiency. Most people talk about the relationship between execution efficiency and runtime space, as well as the relationship between execution efficiency and readability.

2.1 change time with Space

As the cost of hardware equipment is getting lower and lower, more and more industries advocate the concept of space-for-time design. Some places where the calculation workload can be reduced by recording intermediate data become the preferred optimization point.

The most classic algorithm that uses this idea is bucket sorting:

void main(){    int arr[10] = {2, 5, 15, 18, 7, 10, 13, 11, 9, 0};    int arrSort[20] = { 0 };    for (int i = 0; i < 10; i++)    {        arrSort[arr[i]]++;    }    for (int i = 0; i < 20; i++)    {        if (arrSort[i] > 0)        {            printf("%d ", i);        }    }}

This code is sorted by a one-dimensional array subscript with a space of 20. It features a large array of sorting ranges.

2.2 cannot sacrifice readability

The underlying programmers like bitwise operations, so they often optimize simple calculations with bitwise operations, such

int a = 10;int b = a / 2;

Change

int a = 10;int b = a >>1;

Due to the physical characteristics of bit operations, the following code is indeed more efficient. However, many people may not be able to respond to this writing method.

3. Occupied Space

For some special industries, such as embedded development, you must pay attention to space saving during programming. Because the RAM of embedded devices is generally relatively small. At this time, the bucket sorting method is not allowed. In addition, there are strict restrictions when applying for heap space.

In embedded development, such code is often used:

#define NEED_MAX 800int* p = new int[NEED_MAX];if (p == NULL){    return -l;}delete[] p;

If you have no embedded experience, you will certainly ask, after applying for a space, this code will be released without having to do anything. Isn't it enough to draw a picture. In fact, this is a fault-tolerant Code to ensure that the system has enough space for subsequent code execution.

If you think about it, it is very poor. When the program runs, it suddenly finds that the memory is not enough and you have to stop it.

4. Readability

For the Chinese software industry that advocates code standards, readability has become an important factor that cannot be ignored. Pay attention to the Code style, standard naming, function design, and comments.

In some companies, code standards are considered to be the first element of code evaluation. The programmer of tie's project flow, a piece of code with poor readability is likely to mean a disaster tolerance for the project.

For beginners, the code specification element must be very important. If you miss this golden period of good habits, it will be difficult to change it later.

There are some bad habits in the industry that have been followed for a long time, because the pursuit of program execution efficiency causes readability loss, the loss of readability in order to reduce the number of lines of code, the loss of readability in order to catch up with the duration, and even the loss of readability. Driven by these ideas, many bad code habits are generated.

void Swap(int& a, int& b){    a = a ^ b;    b = a ^ b;    a = a ^ b;}

This is a function that implements the variable exchange function. It uses the features of the ^ operation to complete the exchange action without the third variable. Some companies may even take this exam. However, it has no advantages in terms of execution efficiency or input efficiency. Maybe the only role is to be brilliant. I suggest you write this statement honestly:

void Swap(int& a, int& b){    int t = a;    a = b;    b = t;}

In today's compilation technology, this code can be optimized to a very high performance.

Another example:

 g_nScore = student.GetScore() >= p->m_pNext->m_nScore ? student.GetScore() : p->m_pNext->m_nScore;

This sentence should be written as follows:

if (student.GetScore() >= p->m_pNext->m_nScore){    g_nScore = student.GetScore();}else{     g_nScore = p->m_pNext->m_nScore;}

Although there are no functional issues, the following method helps developers to clarify their own logic.

If you carefully read the code specification document of any company, you will find that it has the most important guiding ideology, that is, to improve code readability and to sacrifice some other benefits.

5. scalability

Scalability is very important for some large projects with a long life cycle. But there is a dead enemy of scalability: The amount of code. Take a closer look at the 23 classic design patterns. None of them increase the amount of code exponentially.

Among many senior programmers, it is often because of the use of design patterns. The focus of these arguments is the conflict between the amount of code and scalability. Actually, there are no specific rules, depending on the specific project. The specific problem analysis is king.

6. Considerations for beginners

For beginners, which indicators should be the most important? I think, of course, it is readable.

When beginners learn programming, the most important thing is that they can use programming languages to implement simple algorithms. Others are not important. Sometimes, the early pursuit of four other indicators will lead you astray.

In the face of a variety of solutions to a question, you have to choose which one to study first. Is that the least code function? Is that the shortest time? Is that the one with the least open space? Or the most scalable one. These are none. They should be the most readable.

The readable code is generally not the shortest one, but it must be the easiest one to learn. After you have mastered a correct solution, you will have a bottom in your mind. Then you will be more confident in understanding other solutions, and the motivation for learning will come quietly.

Many new students are afraid of programs with a large amount of code. The so-called large amount of code is less than 30 or 40 lines of code, so they are nervous when they see it. In fact, when you sit down and read the sub-functions in units, you will find that it is just a simple stack of several homework solutions, and it is not difficult to understand. On the contrary, many programs that seem simple and have only a dozen lines of code are often a big pitfall. Once you get in, you can't climb it with your own skills.

Many beginners may not understand what I said. Remember, I believe that after you finish a certain number of exercises in the near future, you will understand what I am talking about today.

 

If you have any questions during the learning process or want to obtain learning resources, join the learning exchange group.
639368839. Let's learn C/C ++ together!

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.