Column introduces

For programmers, I believe you ever have such experience, to change other people’s code, got such a task each time, the in the mind has a bitter could not say ah, so crustily skin of head, but there is no any comments, see a function hundreds of lines of code, the heart is more tend to collapse, thought also is to rewrite it again?

The reasons that, on the one hand, because is not familiar with the business logic might be in the original, on the other hand, actually more because the code before writing is too bad, not familiar with the business logic, we find products, looking for a colleague on the comb will be clear, but it was too bad code will cost increase our workload, and after you have modified, Heart or ten thousand not at ease, for fear of changing a new problem.

Therefore, how to write a more elegant, more maintainable code, becomes very important, if you want to make your code more elegant and tidy, from the name, function, annotations, format, and other aspects to form a good habit, therefore, this column code tidy way – the theory and practice Is from the name, function, comments from theory to actual combat summarizes many ways, such as, Hopefully we can have a clearer understanding.

Two words should be emphasized here:

  1. We write code is to the people, is to see our program apes, not to show the machine, therefore, when we write code to often think, we write the code, if the others look at whether can more clearly understand the meaning of the code, if you feel not so good understanding, does that mean we can further optimize the code, Does that mean we need to add some comments? Anyway, it’s all about making the code readable.
  2. Written code is good, and the technical ability itself is not a positive correlation, that is to say, it will write good code, more is to form a good habit, and from the aspects of attitude to attach importance to this matter, and the technical ability itself has no strong correlation, the relationship between the technical ability itself is also very important, of course, it can addition to our code can be used to better design pattern to organize the code.

The column appears below:

  1. Clean code: Named
  2. Comments on code cleanliness
  3. [Code clean way] function
  4. [Clean Code] Format (to be released)
  5. Objects and Data Structures (to be released)
  6. Error Handling (to be released)
  7. Unit Testing for Clean Code (to be released)
  8. Iteration (to be released)

Note: This column will continue to focus on code cleanliness in more depth in the future. Please like and follow 😊😊😊

Theory of article

I believe that in our usual development, more or less will add some code comments, used to explain the meaning of the corresponding code fragment, elegant comments will certainly help the code to understand, but here I want to emphasize two points:

  1. Annotation is essentially in order to make up for our direct express intention of ambiguity in code, its purpose is to serve the code, as a result, we focus on the core of the remained code, if can express meaning in elegant code clear, there is no need to use comments, at the same time, at the time of writing code, we also should do as much as possible with a concise and clear code logic, Instead of making up for bad code with lots of comments.
  2. Comments also need to be maintained specially. With the continuous iteration of requirements, comments may also need to be updated constantly. If they are not maintained, the longer the time goes by, the more the meaning of comments is different from the meaning of the latest code, which may cause ambiguity

In summary: comments, don’t beautify bad code, so let’s take a look at some of the good and bad comments you might encounter in normal development.

Good comment

What are good comments? Or where do we need to write comments?

Legal information

Sometimes, company code specifications require the preparation of legal annotations, such as: copyright, copyright, etc., generally need to add the relevant legal information annotations at the head of the file. Or we usually related to open source some of their own tools or libraries, can add such comments in the file header, this is also recommended.

For example, take a look at the React source file:

Comments for the public API

Sometimes, for example, a method may have some obscure parameters and return values. In this case, we can also add comments to explain the meanings of the parameters and return values. For example: various methods in the LoDash source code:

Note: General public methods in the library or write some tools, we must make the corresponding notes plus, so others in the call this tool when you wrote, to be able to better understand how to use, or in the project, we want to abstract a common component, also need to put each prop, The meaning of event is explained clearly through annotations.

Of course, not only the public method, if we are in normal business development, if some method logic is complicated, then we should first consider whether we can optimize the code logic as much as possible, and then consider whether it is necessary to add some comments.

TODO comment

Through TODO comments, you can record the list of functions that have not yet been implemented in a project in the form of TODO comments.

Warning role

During development, some code logic may lead to certain consequences, and we also need to add comments to explain, so as to warn programmers who see this code.

In fact, it’s not just a warning, but in any case in the code, if you’re sure that the logic is good enough, but you still need to explain it, you can use comments to explain or emphasize it.

Bad comments

Comments are not taken seriously

Function getTastList() {//... }Copy the code

Most of us have written this comment before, but the above code makes two errors:

  1. Extra note: The getTaskList method is already clear from its name, which is to get a list of tasks. There is no need to add comments, the role of comments is to make up for the lack of code expression, not every piece of code to add comments, on the contrary, can be expressed clearly with code, there is no need to add comments.
  2. Misleading comments: If you choose to add comments, take them seriously. They work. Don’t make comments ambiguous or unnecessary.

This is just to emphasize that we must take comments seriously and write them as completely and clearly as possible. Otherwise it is likely to backfire.

Comment everywhere

It is not recommended to add comments wherever possible, regardless of whether it is necessary or not. The maintenance of comments is also costly. On the contrary, we should only use the code to express the code, and do not use comments as much as possible.

Log comment

Sometimes, some files may be modified so frequently that all the changes are added to the comments, which is not necessary because it will become more and more redundant over time.

Comment out code

This we must have done, some functions or code may be temporarily hidden, so directly to the corresponding code comment out, for their own, may be more convenient, but for others, when others see a code comment out, there must be a question? Is this code still functional, can delete, etc.? And the more code you annotate, the worse your overall code quality will be.Therefore, if there is a function that needs to be hidden temporarily, we can delete the corresponding function directly. In fact, it is also very easy to find back, from the history of Git, etc.

Non-local comment

This means that when we write comments, we must make sure that we describe the code closest to it, not the code in the current place.

Too many comments

Comments have too much information, and no one wants to read them. Not only the code, but also the comments should be concise and illustrative.

Summary: whether the above is good or bad notes, may be our usual development, may encounter, may also be their own writing, we through this section of learning, at least know which notes are good, which is bad, in the future, we may avoid writing these notes. To sum up in one sentence; Don’t use comments if you can express them in elegant code, and if you must, maintain and write them carefully.

Standard article

【 must 】 use /*… */ Make multi-line comments

// bad case
// getNumber() return a new number
// @param {Number} number
// @return {Number} number
function getNumber(number) {
  return number;
}
​
// good case
/*
* getNumber() return a new number
*/
function getNumber(number) {
  return number;
}
Copy the code

“Must”/ * *... * /Block-level multi-line comments with style (with two * in the first line) can only be used with JSDoc.

The first line of a multi-line comment uses a single *. This allows us to organize the content of the comment in a custom format, but the first line of a double * can only be used in Jsdoc. JSDoc is a tool that generates API documentation for javascript applications, libraries, and modules based on comments in javascript files. More on its use later.

// good case /** * getNumber() * @description: Description * @params {type} parameter name Must * @params {type} parameter name Optional * @returns {type} */ function getNumber(number) {return number; }Copy the code

Extension: When we write some common libraries or functions, we can recommend using JSDoc, which can help us to generate comment content in a more standardized way.

[Recommended] Use // for single-line comments

In addition, there are two points to note:

  1. Single-line comments are typically placed on a new line above the line that needs to be commented.
  2. It is recommended that a blank line precede the comment unless it is on the first line of the block.

Note: When you look at the following code, you will probably have a question like this: Under a lot of code comments are useless, named itself has been very good to explain the meaning, there is no need to add a comment, ha, ha, ha, yes, what you said is very right, also means that you have mastered the theory article content, and the following case is from the perspective of code specification, see comment on where more appropriate, and how the annotation format specification, The exact content of comments, and whether they are needed, is not the concern of this section.

// bad case const username = 'kobe'; // good case // username const username = 'kobe';Copy the code
// bad case function getNumber(number) { console.log('get number... '); Const num = number; return num; } // good case function getNumber(number) { console.log('get number... '); Const num = number; return num; } // good case function getNumber(number) {// Get number console.log('get number... '); const num = number; return num; }Copy the code

Start all comments, single or multiple lines, with a space.

// bad case //username: const username = 'kobe'; // good case // username const username = 'kobe';Copy the code
// bad case
/*
*getNumber() return a new number
*@params {Number} number
*@return {Number} number
*/
function getNumber(number) {
  return number;
}
​
// good case
/*
* getNumber() return a new number
* @params {Number} number
* @return {Number} number
*/
function getNumber(number) {
  return number;
}
Copy the code

[Recommended] Use // FIXME: to comment on current problems

That is, if you find some possible problems in your code, or need to revisit them, you can use // FIXME: XXX to comment.

// good case function getNumber(number) {// FIXME: return number; }Copy the code

Use // TODO: Comment on problems that are not yet implemented or to be solved

// good case function getNumber(number) {// good case function getNumber(number) {// Good case function getNumber(number) { const status = 0; return number; }Copy the code

Practical article

How to add comments, as well as the basic format of comments and other content, we have been clear in the specification part, the actual combat part, we mainly focus on the actual project development, where the need to add comments.

Public API adds comments

Whether it’s Vue or React, the project will definitely have a special utils folder to maintain custom utility methods. These methods should be commented as much as possible. J sdoc is recommended for adding comments. The second is that there must be a components directory to maintain common components in the project, and any props, events, etc. defined in that component should also be commented.

Comments are added to each module file header

Here refers to, in the usual business project development, will be split into a number of different modules, at the same time, due to the type of project, such as electricity, different types, such as medical will involve a lot of professional term, therefore, Suggestions in each module file head using a multiline comment, to illustrate what is the current module module, and contains which child module, etc. Of course, this point is my personal development habits, we can decide according to the actual situation.

/* * Permission management module: * 1. Permission list * 2. Add permission * 3. */ /...Copy the code

At the same time, in a single file, there may be multiple module variables, we try to organize the same module variables together, and then add a uniform comment, etc.

Logically complex blocks of code require comments

In the project, will always have that kind of logic is more complex scenarios, such as the back-end to return to a more bad data format, you need to do more data conversion operations, but also according to different situation to do adaptation process, etc., in short, is very complex, at this time, we can also, by using the method of adding comments explain further.

There is also some code logic that is important, or you want to emphasize it, in this case, you can also add comments to emphasize it.

The VScode annotation plug-in is recommended

Here, recommend two:

  • Better Comments: Features the ability to change the color of the Comments to represent different situations
  • KoroFileHeader: Features the ability to quickly add comments and function comments to the file header.

For details, please refer to the official website.

conclusion

Now that you’ve seen this section, I’m sure you have a better understanding of annotations and how to do them. All in all, right

  1. The core is code quality. If your code is clear, you don’t need comments
  2. Even if you want to add notes, it is necessary to add accurate, clear and complete notes.
  3. You also learned about common annotated scenarios.
  4. Introduces the common vscode annotation plug-in.

Next, everyone in the project, step by step according to the above points to apply to the actual project development, gradually develop their own habits.