This article was written by José M. Aguilar in Spanish on his excellent blog Variable Not Found, and was translated, edited and republished here by Timm Martin (and Google Translator) with permission from Mr. Aguilar.
Following are 13 tips on how to comment your source code so that it is easier to understand and maintain over time.
1. Comment each level
Comment each code block, using a uniform approach for each level. For example:
- For each class, include a brief description, author and date of last modification
- For each method, include a description of its purpose, functions, parameters and results
Adopting comment standards is important when working with a team. Of course, it is acceptable and even advisable to use comment conventions and tools (such as XML in C# or Javadoc for Java) to facilitate this task.
2. Use paragraph comments
Break code blocks into multiple “paragraphs” that each perform a single task, then add a comment at the beginning of each block to instruct the reader on what is about to happen.
// Check that all data records
// are correct
foreach (Record record in records)
{
if (rec.checkStatus()==Status.OK)
{
. . .
}
}
// Now we begin to perform
// transactions
Context ctx = new ApplicationContext();
ctx.BeginTransaction();
. . .
3. Align comments in consecutive lines
For multiple lines of code with trailing comments, align the comments so they will be easy to read.
const MAX_ITEMS = 10; //
maximum number of packets
const MASK = 0x1F; // m
ask bit TCP
Some developers use tabs to align comments, while others use spaces. Because tab stops can vary among editors and IDEs, the best approach is to use spaces.
4. Don’t insult the reader’s intelligence
Avoid obvious comments such as:
if (a == 5) // if a equals 5
counter = 0; // set the counter to zero
This wastes your time writing needless comments and distracts the reader with details that can be easily deduced from the code.
5. Be polite
Avoid rude comments like, “Notice the stupid user has entered a negative number,” or “This fixes the side effect produced by the pathetically inept implementation of the initial developer.” Such comments do not reflect well upon their author, and you never know who may read these comments in the future: your boss, a customer, or the pathetically inept developer you just insulted.
6. Get to the point
Don’t write more in comments than is needed to convey the idea. Avoid ASCII art, jokes, poetry and hyperverbosity. In short, keep the comments simple and direct.
7. Use a consistent style
Some people believe that comments should be written so that non-programmers can understand them. Others believe that comments should be directed at developers only. In any event, as stated in Successful Strategies for Commenting Code, what matters is that comments are consistent and always targeted to the same audience. Personally, I doubt many non-developers will be reading code, so comments should target other developers.
8. Use special tags for internal use
When working on code as a team, adopt a consistent set of tags to communicate among programmers. For example, many teams use a “TODO:” tag to indicate a section of code that requires additional work:
int Estimate(int x, int y)
{
// TODO: implement the calculations
return 0;
}
Tag comments don’t explain code; rather they seek attention or deliver a message. But if you use this technique, remember to follow up and actually do what the message is asking.
9. Comment code while writing it
Add comments while you write code and it’s fresh in your memory. If you leave comments until the end, it will take you twice as long, if you do it at all. “I have no time to comment,” “I’m in a hurry,” and “The project is delayed” are all simply excuses to avoid documenting your code. Some developers believe you should write comments before code as a way to plan out your ultimate solution. 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. Write comments as if they were for you (in fact, they are)
When it comes to commenting code, think not only about the developers who will maintain your code in the future, but also think about yourself. In the words of the great Phil Haack:
“As soon as a line of code is laid on the screen, you’re in maintenance mode on that piece of code.”
As a result, we ourselves will be the first beneficiaries (or victims) of our good (or bad) comments.
11. Update comments when you update the code
There is no point in commenting correctly on code if the comments are not changed with the code. Both code and comments must move in parallel, otherwise the comments will actually make life more difficult for developers who maintain your code. Pay special attention to refactoring tools that automatically update code but leave comments unchanged and hence obsolete in the same instant.
12. The golden rule of comments: readable code
One of the basic principles for many developers: Let your code speak for itself. Although one suspects this movement is led by programmers who do not like to write comments, it is true that self-explanatory code can go a long way toward making code that’s easier to understand and can even render comments unnecessary. For example, the code in my Fluid Interfaces article shows how clear self-explanatory code can be:
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, comments are not needed and would likely violate tip #4. To facilitate readable code, you might consider using proper names (as described in the classic Ottinger’s Rules), ensure correct indentation, and adopt coding style guides. Failure to comply with this tip may result in comments that seem to apologize for bad code.
13. Share these tips with your colleagues
Although tip #10 shows how we ourselves benefit immediately from good comments, these tips will benefit all developers, especially in the context of team working together. Therefore, feel free to share these commenting tips with your colleagues to create code that is easier to understand and maintain.
Article published on March 14, 2008
If you like this article, please share it: |
March 17th, 2008 at 9:04 pm
I would add one more tip that I’ve found very useful.
The code should explain how. The comments should explain why.
#12 comes tantalizingly close to this.
March 17th, 2008 at 9:58 pm
Nice article, my own thoughts on commenting:
http://3poundmass.wordpress.com/2007/07/26/coding-guidelines-commenting/
http://3poundmass.wordpress.com/2007/08/22/if-the-code-and-the-comments-disagree-then-both-are-probably-wrong/
March 17th, 2008 at 10:02 pm
Or, better yet, don’t do comments and make the code speak for itself rather than writing bad code that needs instantly-obsolete comments:
http://www.chadmyers.com/Blog/archive/2007/11/18/1-common-mistake-involving-code-commenting.aspx
March 17th, 2008 at 10:23 pm
I agree with most of the points made here to a T.
One thing I can’t stand is the whole “write code better” or “code better” arguments going back and forth. From working in the Insurance industry, I’ve got my self elbows deep in complex calculations. No matter how much verbosity you use with your variables and how ‘well’ you write it, comments are absolutely 100% necessary.
*hangs head* I’m sometimes guilty of jokes and profanity from time to time… but… I… *sigh* no excuses. 🙂
March 17th, 2008 at 10:54 pm
@Aaron: Complex algorithms and low-level munging, when justified and otherwise unavoidable would qualify for heavy commenting, in my opinion even though I’m pretty rabidly anti-Commenting (with exceptions for things like //TODO that tools can pick up and use).
March 18th, 2008 at 12:46 am
[…] M. Aguilar has put together a very sensible list of 13 Tips to Comment Your Code. Translated and republished in English by Timm […]
March 18th, 2008 at 12:51 am
Remember, the most useful comment is the comment that does not have to be written!
Never sacrifice code readability for performance unless the benchmarks tell you that you must. A fast-running, but convoluted and bug-filled algorithm is far worse than a slow-working, easy to maintain reliable one. I’m not advocating writing slow code, but CPUs keep getting faster and compilers keep getting more efficient. Complicated code will ALWAYS be hard to debug.
Obviously if you have to loop over your slow code 10,000 times, do what you must to make it work and document it as little as necessary. Code can be tested, however comments cannot be tested, and there is nothing worse for a developer than comment-rot, i.e. software has been changed, but the comments do not reflect the changes.
Use the most lines of code that make sense, write the fewest comments you can reasonably get by with.
March 18th, 2008 at 4:05 am
[…] 13 Tips to Comment Your Code – Some excellent advice about commenting, translated from an original article in Spanish. […]
March 18th, 2008 at 7:39 am
Great article, it’s good to know how to comment your code, especially for large projects…
March 18th, 2008 at 10:44 am
An insightful article! I’ve written a response: http://itscommonsensestupid.blogspot.com/2008/03/one-single-tip-to-comment-your-code.html
March 18th, 2008 at 10:53 am
I have a habit of removing the word “the” in my comments. They seem useless to me.
Like your example above:
“As soon as a line of code is laid on the screen, you’re in maintenance mode on that piece of code.”
“As soon as a line of code is laid on screen, you’re in maintenance mode on that piece of code.”
March 18th, 2008 at 4:00 pm
[…] 13 Tips to Comment Your Code (tags: code programming reference tips development) […]
March 19th, 2008 at 6:43 am
[…] 13 Tips to Comment Your Code […]
March 21st, 2008 at 6:04 am
[…] să-ţi comentezi şi să-ţi organizezi codul. De multe ori este foarte dificil să înţelegem codul scris de […]
March 22nd, 2008 at 5:21 am
Good Job!
I have translated it with Chinese.
But,I have a question.
“There is no point in commenting correctly on code ”
I donot know its meaning.I cann’t translate it.Would you explain it ? Thanks.
March 22nd, 2008 at 7:47 am
[…] tips on how to comment your source code so that it is easier to understand and maintain over […]
March 24th, 2008 at 6:50 pm
[…] 13 Tips to Comment Your Code – DevTopics – еще разок по граблям… […]
April 1st, 2008 at 4:30 am
[…] (more…) […]
April 20th, 2008 at 4:38 pm
(a) say what the code is INTENDED to do, not what it literally does,
(b) make it so that you could understand how the program works if you lost all the code and only had the comments to work from,
(c) make all comments non-technical – e.g. don’t waste time referring to variables by name,
(d) comment everything, or at least use TODO when prototyping to allow you to come back and fill in all your missing comments later
May 1st, 2008 at 3:35 pm
I like it! Kind regards/ PeTter http://www.oakleafnow.com
May 8th, 2008 at 10:50 am
[…] reasons, is not a valid excuse nowadays. Management: fine, we outsource the WHOLE team to India.https://www.devtopics.com/13-tips-to-comment-your-code/Science jobs and vacancies from NaturejobsAs the Medical Dictionaries and coding manager you report […]
June 16th, 2008 at 2:43 pm
“9. Comment code while writing it”
This is the most useful tip in my opinion. If you write comments afterwards you may have a hard time remembering why you coded it the way you did (even if its the right way).
July 5th, 2008 at 6:04 pm
Real programmers don’t comment, if the code was hard to write, it should be hard to read!
July 22nd, 2008 at 3:19 am
[…] 代码注释的13个秘诀。 […]
July 24th, 2008 at 11:58 am
[…] M. Aguilar 原文链接:13个代码注释的小技巧 […]
August 31st, 2008 at 1:51 am
[…] […]
September 9th, 2008 at 10:25 pm
[…] ‘NERDs use real editors (VIM Flame flame…) and Comment the code’. This plugin helps comment code in almost all languages you program in. The way: […]
September 28th, 2008 at 11:09 pm
Thanks
October 3rd, 2008 at 3:31 am
[…] Commenting Code August 3, 2008 13 Tips to Comment Your Code […]
November 17th, 2008 at 10:15 am
Your site is a much needed addition to my life. THANK YOU!
November 18th, 2008 at 4:08 am
This is a very beautiful website, I have enjoyed my visit here very much. I’m very honoured to sign in your guestbook. Thanking you for the great work that you are doing here.
December 17th, 2008 at 6:27 am
[…] 本文发表在作者José M. Aguilar的博客Variable Not Found,后来由Timm Martin翻译成英文发表在DevTopics上。我在真见的blog那里看到,将其翻译过来share给大家,共同学习。有翻译不当之处,望大侠斧正。 […]
February 26th, 2009 at 12:58 pm
This is very interesting and very useful for beginners as well.
February 27th, 2009 at 10:59 am
[…] Martin在获得Aguilar先生的授权下,对该文章进行翻译、修改,并且在DevTopics上发布。 […]
June 14th, 2009 at 9:06 am
[…] : Click here Possibly related posts: (automatically generated)If the code and the comments disagree, then both […]
July 27th, 2009 at 4:31 pm
Good post =D
Definitely a Coding 101 that most people overlook. Even I’m guilty of it… it took my first big project to learn how blowing off documentation is a recipe for disaster…and block-box coding.
Comments before code saves me hours if not days. Because after I finish one section sometimes I’m so into the previous section that I forget what the intentions of the previous codeblock where =P
September 30th, 2009 at 1:11 pm
[…] the code is trying to do, so therefore comments should describe WHY you are doing it. Also, a good article by my friend José M. Aguilar provides 13 tips on how to comment your […]
October 2nd, 2009 at 5:14 am
Lovely. Made my day (which is saying something)
November 5th, 2009 at 9:57 pm
I don’t like scripts that are commenting much since I found out that they are too slow
November 24th, 2009 at 10:39 pm
[…] 13 Tips to Comment Your Code […]
December 8th, 2009 at 1:15 pm
[…] 13-tips-to-comment-your-code […]
December 17th, 2009 at 3:57 am
In response to all those who say things like ;
“Or, better yet, don’t do comments and make the code speak for itself”
What a load of garbage. !! For professional companies and programmers, comments are a must. Code needs to be maintained and the original developer is not going to be there forever, and if they are, they probably won’t remember what the heck they wrote a function or class for anyway two years down the track.
As an employer, or company CIO, or owner of a piece of code that needs to be updated / maintained, the last thing you want is to have a new developer sitting crawling through code unnecessarily trying to read and interpret someone else’s style and determine what a piece of code is doing, when all they needed to do was read the Brief, and the Date it was done, and any Updates that were added and Why.
Laziness is no excuse to not be professional and think about those coming along behind you that may need to review what you have done. A simple few lines of comment could save a great deal of time, money, and grief.
January 22nd, 2010 at 10:10 am
Mostly, the urge to write a comment serves as an indicator that your code needs to be improved.
How the code in tip 2 could be made comment free:
check_data_records();
perform_transactions();
And the code in tip 3:
const MAX_NUMBER_OF_PACKETS = 10;
const TCP_BITMASK = 0x1F;
April 20th, 2010 at 10:36 am
Good article, but what about using phpDocumentor and others for other languages ?
August 20th, 2010 at 4:13 am
An interesting article. I have written an article about Code Commenting in Context which might be of interest to your readers http://mauriceonsoftware.blogspot.com
September 14th, 2010 at 3:27 am
goood….
November 14th, 2010 at 1:01 am
Awesome article, I love commenting code and I yet need to further refine that skill.
But for
const MAX_ITEMS = 10; // maximum number of packets
const MASK = 0x1F; // mask bit TCP
I don’t think there’s a need to comment the meaning for the variable if we can just name it clearly..Why not call it a TCP_BIT_MASK 🙂
November 15th, 2010 at 11:26 am
kk, you are almost repeating in comment 47 what I was saying in comment 43
December 1st, 2010 at 8:56 am
[…] […]
February 2nd, 2011 at 1:03 am
[…] 原文:13 Tips to Comment Your Code […]
May 24th, 2011 at 2:49 am
Well..as I said..to my mind the best way how to let producers know about our thoughts
June 30th, 2011 at 8:48 am
I don’t like scripts that are commenting much since I found out that they are too slow
June 30th, 2011 at 10:27 am
so, I love commenting code and I yet need to further refine that skill.
June 30th, 2011 at 11:21 am
Scripts that are commented are running too slow?
Did you really get a measureble difference?
Scripts that are commented are slow… to read
July 11th, 2011 at 11:30 am
I like this web site its a master peace ! Glad I found this on google .
July 17th, 2011 at 11:43 pm
Pay special attention to refactoring tools that automatically update code but leave comments unchanged and hence obsolete in the same instant.
July 29th, 2011 at 3:16 am
[…] 这篇文章是由José M. Aguilar在他卓越的博客中以西班牙语的形式首发,其后Timm Martin在获得Aguilar先生的授权下,对该文章进行翻译、修改,并且在DevTopics上发布。 […]
August 9th, 2011 at 4:11 pm
What I hate is people who try to code their own job security into their work.
They never want anybody else to understand it!
August 24th, 2011 at 3:54 am
Another tip: when you need to fix a bug, also fix any existing comments if any of them are unclear or misleading. Also take the opportunity to add more comments to explain things better if you found any of the code hard to understand while tracing the bug, of course make sure you do understand the code before commenting it.
August 24th, 2011 at 3:59 am
Show me a snippet of well commented code and I can make it a lot clearer/understandable without comments. Dont forget to do this!
August 24th, 2011 at 4:01 am
Also when the code uses published example code – e.g. examples from microsoft or codeproject, codeguru etc – add url to the original code as a comment. Similarly for ideas and concepts, add urls or references to the code comments. Even if it is easy to find it again, still adding the url makes it quick to maintain the code in the future, if you need to go back to the source, and only takes a moment or two – general guide if you needed to search for something on google to do the coding, chances are it is worth putting the url into the code comment.
September 20th, 2011 at 7:49 am
Great article, it’s good to know how to comment your code, especially for large projects…What I hate is people who try to code their own job security into their work.
They never want anybody else to understand it!
October 9th, 2011 at 11:32 pm
fantastic just awesome, you guys also like this like 10 best practices to following while writing code comments
October 17th, 2011 at 12:22 pm
I should definitely say I’m impressed with your blog.
I had no trouble navigating through all the tabs as well as related info.
The site ended up being truly simple to access. Excellent job..
Excellent Post.. I enjoy some of content in the post.. please keep it up..
i want same like this from you..
February 25th, 2013 at 6:44 am
[…] 13 Tips to Comment Your Code […]
May 5th, 2013 at 3:57 pm
Finally! While we can agree that being a powerful speaker is all well and good, but at some point you have to “get something done”.
March 18th, 2014 at 9:14 am
Hello,
I am working with software firm and here I am working with one of oldest project and I found too much comments and among then there many comment are unnessary so my question is.
Is unnessary comment can reduce performance or create any problem in existing application?
Can anyone please help me on same ?
Thanks in Advance…
March 23rd, 2014 at 12:07 pm
@Mr. F M: Comments are processed at compile time and do not affect program performance.
January 26th, 2015 at 11:21 pm
[…] code can be. For more reading, you can check out these small articles on commenting tips here at DevTopics and at […]