Tips for 13 code comments
This article is written by Jos é M. aguilar was first published in Spanish in his excellent blog. After that, timm Martin translated and modified the article with the authorization of Mr. Aguilar and published it on devtopics.
The following 13 tips Make your code easy to understand and maintain for a long time.
1. Perform different levels of codeNote
For different levels of code blocks, you must use a uniform method.Note. For example:
- Each class must contain a brief description of the author and the last modification time.
- Each method must contain the purpose, function, parameters, and returned results of this method.
When you are in a team, use a setNoteStandards are very important. Of course, using a comments Convention and tool that everyone recognizes (such as C # xml comments and Java javadoc) can push this task to a certain extent.
2. Use paragraphsNote
First, the code block is divided into multiple "sections", each section executes a single task, and then added before each "section" starts.Note, Tell the person who reads the code what the next code is
// Check that all records are correct
Foreach (record in Records)
{
If (Rec. checkstatus () = status. OK)
{
...
}
}
// Start processing now
Context CTX = new applicationcontext ();
CTX. begintransaction ();
...
3. AlignmentNoteLine
For those written at the end of a rowNoteThe Code should be aligned with the comment line to facilitate reading.
const MAX_ITEMS = 10; //
maximum number of packets
const MASK = 0x1F; // m
ask bit TCP
Some developers use tab to alignNoteAnd other people will use spaces to align. Because tabs are different in different editors and integrated development environments, the best way is to use spaces to align comment rows.
4. Do not insult the reader's wisdom
To avoid uselessNoteFor example
If (A = 5) // if A is equal to 5
Counter = 0 // set
Counte is set to 0
This is not a waste of time writing.NoteAt the same time, it is also distracting readers.
5. Be polite
Avoid courtesyNote,
For example, "note that some stupid users will enter a negative number", or "correct the side effects caused by silly code written by cainiao engineers ". Such annotations do not exist for the person who writes comments to the code.
At the same time, you will never know who will read the comments in the future. Your boss, a customer, or a silly engineer who has just been counted by you.
6. straightforward
Do notNoteToo much nonsense. Avoid selling ASCII art in comments, writing jokes, making poems, and being too lengthy. In short, annotations are kept simple and straightforward.
7. Use a unified style
Some people thinkNoteIt should be understandable to non-programmers. Others think that comments are only intended for programmers. In any case, as stated in successful strategies for commenting code, the most important thing is that the annotation style needs to be unified and always oriented to the same readers. In my opinion, I doubt whether non-programmers will read the code, so I think the comments should be written for programmers.
8. Use special labels internally
When you work in a team, using a set of consistent labels can help different programmers communicate. For example, many teams use the "Todo" label to indicate a piece of unfinished code.
int Estimate(int x, int y)
{
// TODO: implement the calculations
return 0;
}
TagNoteIt does not explain the code. They seek attention or pass information. However, if you use this technology properly, remember to follow up this code and complete the task of passing the label.
9. Add code while writingNote
When you write code and remember it, addNote. If you do not add comments after the project is completed, you will get twice the result. "I don't have time to write comments", "My time is tight", and "The project has been delayed" are common excuses for not writing comments. Some engineers find that the best solution is "comment first ". For example:
public void ProcessOrder()
{
//
Make sure the products are available
//
Check that the customer is valid
//
Send the order to the store
//
Generate bill
}
10. Think of yourselfNoteReader (in fact)
When you are writing codeNoteIn the future, we will not only consider how to maintain your code, but also imagine if you are the author of the comments. Phil haack once said:
"Once a line of code is knocked into the file, you have to start to maintain that line of code ."
Therefore, we are good (or bad) ourselves)NoteThe first beneficiary (or victim ).
11. Update the code.Note
IfNoteWithout updating the Code, the comments will be meaningless. Code and comments must be synchronized. Otherwise, comments only make the code maintenance developer more painful. Note that some refactoring tools will automatically update the code, but the comments are not automatically updated, so the comments will expire naturally.
12. The code with good readability isNoteJinke Yulu
For many developers, a basic principle is to allow the code to describe itself. Although some people suspect that this is caused by dislike of writingNoteThe programmer advocates a movement, but the code that does not need to be explained has great advantages. These codes are easier to understand and even make comments unnecessary. For example, in my article fluid interfaces, we will show you what code is clear without explanation.
Calculator calc = new Calculator();
calc.Set(0);
calc.Add(10);
calc.Multiply(2);
calc.Subtract(4);
Console.WriteLine( “Result: {0}”, calc.Get() );
In this example,NoteIt becomes unnecessary as it violates the 4th skills. To write readable code, you need to use the appropriate naming method (described in the classic ottinger's rules) to ensure proper indentation and adopt the encoding style guidance. If the Code does not follow this technique, the comments look like an apology for your own bad code.
13. share these skills with your colleagues
Although we have learned from 10th tips that we are goodNoteBut these skills are very helpful for all developers, especially when the entire team has the same consensus. Therefore, sharing these skills with your colleagues allows us to write code that is easier to understand and maintain.