While comments are painful to write, they are essential to ensure code readability The following rules describe how and where to comment Of course, keep in mind that comments are important, but the best code itself should be self - documenting Meaningful type names and variable names are far better than ambiguous names to be interpreted with comments
Your comments are for code readers: the next person who needs to understand your code Be generous. You may be the next person!
7.1. Comment Style
Use / / *, or. Unified / / *
//Or / * * /; But / / more commonly used We should ensure unity in how to annotate and annotation style
7.2. File Comments
Add a copyright notice at the beginning of each file, followed by a description of the file content
Legal notice and author information:
Each file should contain the following items, in turn:
- Copyright notice (e.g. Copyright 2008 Google Inc.)
- licence. Select the appropriate license version for the project (for example, Apache 2.0, BSD, LGPL, GPL)
- Author: identifies the original author of the document
If you make significant changes to the original author's document, add your information to the author's information In this way, when others have questions about the document, they can know who to contact
Document content:
Immediately after the copyright license and author information, each file is annotated to describe the content of the file Usually H file should give a brief description of the function and usage of the declared class cc files usually contain more implementation details or discussion of algorithm skills. If you feel that these implementation details or discussion of algorithm skills are difficult to understand H file is helpful. You can move the comment to h. And in cc indicates that the document is in h. Don't simply in h and Copy notes between cc This deviates from the practical significance of the note
7.3. Class annotation
The definition of each class should be accompanied by a note describing the function and usage of the class
// Iterates over the contents of a GargantuanTable. Sample usage: // GargantuanTable_Iterator* iter = table->NewIterator(); // for (iter->Seek("foo"); !iter->done(); iter->Next()) { // process(iter->key(), iter->value()); // } // delete iter; class GargantuanTable_Iterator { ... };
If you think you have described this class in detail at the top of the document, it doesn't matter if you want to simply say "see the top of the document for a complete description", but make sure there are such comments
If the class has any synchronization preconditions, the documentation describes them If the instance of this class can be accessed by multithreading, pay special attention to the documentation to explain the use of relevant rules and constants in multithreading environment
7.4. Function Comments
Comments at the function declaration describe the function; The function implementation is described at the definition
Function declaration:
Comments are placed before the declaration to describe the function function and usage Notes use narrative ("Opens the file") rather than directive ("Open the file"); Annotation is only to describe the function, not to command what the function does In general, annotations do not describe how a function works That's part of the function definition
Contents of comments at function declaration:
- Function input and output
- For class member functions: whether the object needs to maintain reference parameters during function call and whether these parameters will be released
- If the function allocates space, it needs to be released by the caller
- Whether the parameter can be NULL
- Whether there are performance hidden dangers in the use of functions
- If the function is reentrant, what is the synchronization premise?
Examples are as follows:
// Returns an iterator for this table. It is the client's // responsibility to delete the iterator when it is done with it, // and it must not use the iterator once the GargantuanTable object // on which the iterator was created has been deleted. // // The iterator is initially positioned at the beginning of the table. // // This method is equivalent to: // Iterator* iter = table->NewIterator(); // iter->Seek(""); // return iter; // If you are going to immediately seek to another place in the // returned iterator, it will be faster to use NewIterator() // and avoid the extra seek. Iterator* GetIterator() const;
But also avoid wordy or obvious explanations There is no need to add "returns false otherwise" in the following comments, because it has been implied:
// Returns true if the table cannot hold any more entries. bool IsTableFull();
When commenting the constructor / destructor, remember that the reader knows what the constructor / destructor is for, so comments like "destroy this object" are meaningless Indicate what the constructor did to the parameter (for example, whether it took pointer ownership) and what the destructor cleaned up If it's all unimportant content, omit the comments directly It is normal for destructors to have no comments before them
Function definition:
When defining each function, the function and implementation points of the function shall be explained with notes For example, talk about the programming skills you use, the general steps of implementation, or explain the reason why the first half needs to be locked and the second half doesn't Don't start from h file or function declarations elsewhere It is OK to briefly restate the function function, but the annotation should focus on how to implement it
7.5. Variable Comments
Usually, the variable name itself is enough to explain the purpose of the variable In some cases, additional notes are also required
Class data member:
Each class data member (also called instance variable or member variable) should be annotated for its purpose If the variable can accept warning values such as NULL or - 1, it must be explained For example:
private: // Keeps track of the total number of entries in the table. // Used to ensure we do not go over the limit. -1 means // that we don't yet know how many entries the table has. int num_total_entries_;
Global variables:
Like data members, all global variables should be annotated to explain their meaning and purpose For example:
// The total number of tests cases that we run through in this regression test. const int kNumTestCases = 6;
7.6. implementation comments
Comment on the clever, obscure, interesting and important parts of the code
Comments before code:
Clever or complex code snippets should be preceded by comments For example:
// Divide result by two, taking into account that x // contains the carry from the add. for (int i = 0; i < result->size(); i++) { x = (x << 8) + (*result)[i]; (*result)[i] = x >> 1; x &= 1; }
Line comment:
Add comments at the end of the line where it is more obscure Comment in the two spaces at the end of the line For example:
// If we have enough memory, mmap the data portion too. mmap_budget = max<int64>(0, mmap_budget - index_->length()); if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock)) return; // Error already logged.
Note that two comments are used here to describe the function of this code and to prompt that the error has been logged when the function returns
If you need to comment on multiple lines in succession, you can align them for better readability:
DoSomething(); // Comment here so the comments line up. DoSomethingElseThatIsLonger(); // Comment here so there are two spaces between // the code and the comment. { // One space before comment when opening a new scope is allowed, // thus the comment lines up with the following comments and code. DoSomethingElse(); // Two spaces before line comments normally. }
NULL, true/false, 1, 2, 3...:
When you pass NULL, Boolean, or integer values into a function, you should annotate the meaning, or use constants to let the code know the meaning For example, compare:
Warning
bool success = CalculateSomething(interesting_value, 10, false, NULL); // What are these arguments??
And:
bool success = CalculateSomething(interesting_value, 10, // Default base value. false, // Not the first time we're calling this. NULL); // No callback.
Or use constants or descriptive variables:
const int kDefaultBaseValue = 10; const bool kFirstTimeCalling = false; Callback *null_callback = NULL; bool success = CalculateSomething(interesting_value, kDefaultBaseValue, kFirstTimeCalling, null_callback);
not allow:
Be careful never to use natural language translation code as comments Assume that the code reader is better at C + + than you, even if he / she may not know your intention:
Warning
// Now, check the b array and make sure i exists, // The next element is i+1 ... // My God? A collapsing note
7.7. Punctuation, spelling and grammar
Pay attention to punctuation, spelling and grammar; Good notes are much easier to read than bad ones
A comment is usually written as a complete statement with the correct case and ending period Shorter comments (such as comments at the end of the code line) can be selected at will, and the consistency of style should still be paid attention to The complete statement is more readable, which can also indicate that the annotation is complete rather than some immature ideas
Although it's embarrassing to use commas when others point out that semicolons should be used, clear and readable code is still important Correct punctuation, spelling and grammar will help
7.8. TODO comments
Use TODO annotations for temporary, short-term solutions, or code that is good enough but still imperfect
TODO comments should use a fully capitalized string TODO, followed by your name, email address, or other identification in parentheses Colons are optional The main purpose is to make the person who adds comments (who can also request more details) look up according to the standard TODO format Adding TODO comments doesn't mean you have to fix it yourself
// TODO(kl@gmail.com): Use a "*" here for concatenation operator. // TODO(Zeke) change this to use relations.
If TODO is added to "do something one day in the future", you can attach a very clear time "Fix by November 2005") or a clear matter ("Remove this code when all clients can handle XML responses")
7.9. Deprecated comments
Mark an interface point as deprecated by DEPRECATED comments.
You can write a fully capitalized DEPRECATED comment to mark an interface as DEPRECATED. Comments can be placed before the interface declaration or on the same line.
After the word "DEPRECATED", leave your name, email address and parentheses.
Just marking the interface as DEPRECATED will not make everyone abandon it by coincidence. You have to take the initiative to correct the callsites yourself or find a helper.
The revised code should no longer involve discarding interface points, but actually use new interface points. If you don't know where to start, you can consult with the party who marked the discard note.
Notes of the translator (Yule Fox)
- As for annotation style, many C + + coders prefer line annotation. C coders may still have a special preference for block annotation, or use block annotation when commenting large sections in the file header;
- File notes can show off your achievements, but also to poke a basket, others can come to you;
- Notes should be concise and comprehensive, and do not procrastinate and redundant. The simplification of complex things and the complexity of simple things should be despised;
- For Chinese coders, it is a problem to annotate in English or Chinese, but anyway, annotation is to make others understand. Is it to show off your mother tongue or foreign language level other than the programming language;
- Notes should not be too messy, and proper indentation will make people happy to read However, there is no need to specify which column comments start from (I always like this when writing code myself). Under UNIX/LINUX, it can also be agreed whether to use tab or space, and I prefer space;
- TODO is very good. Sometimes, comments are really to mark some unfinished or unsatisfactory places. In this way, you can know what else to do and save the log