Eliza Programmer Dead I'm Busy Compiling…
Mar 14


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;    // mask 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.

Popularity: 19% [?]


Copyright © 2007-8 Tiwebb Ltd. All rights reserved. This material may not be published, broadcast, rewritten or redistributed without explicit permission from Tiwebb Ltd.

kick it on DotNetKicks.com      

24 Responses to “13 Tips to Comment Your Code”

  1. Ferruccio Barletta Says:

    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.

  2. cxfx Says:

    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/

  3. Chad Myers Says:

    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

  4. Aaron Saray Says:

    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. :)

  5. Chad Myers Says:

    @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).

  6. Finds of The Week - March 16, 2008 » Chinh Do Says:

    […] M. Aguilar has put together a very sensible list of 13 Tips to Comment Your Code. Translated and republished in English by Timm […]

  7. Eric Says:

    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.

  8. Reflective Perspective - Chris Alcock » The Morning Brew #55 Says:

    […] 13 Tips to Comment Your Code - Some excellent advice about commenting, translated from an original article in Spanish. […]

  9. hosting reviews Says:

    Great article, it's good to know how to comment your code, especially for large projects…

  10. Ngu Soon Hui Says:

    An insightful article! I've written a response: http://itscommonsensestupid.blogspot.com/2008/03/one-single-tip-to-comment-your-code.html

  11. Denny Ferrassoli Says:

    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."

  12. links for 2008-03-18 « that dismal science Says:

    […] 13 Tips to Comment Your Code (tags: code programming reference tips development) […]

  13. Interesting Finds: 2008.03.19 - Yuanjian Says:

    […] 13 Tips to Comment Your Code […]

  14. X3 Studios Blog » Blog Archive » Cum să devii un programator mai bun Says:

    […] să-ţi comentezi şi să-ţi organizezi codul. De multe ori este foarte dificil să înţelegem codul scris de […]

  15. sunfly Says:

    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.

  16. Bookmarking the web - w12/2008 Says:

    […] tips on how to comment your source code so that it is easier to understand and maintain over […]

  17. Куй железо пока горячо, а ссылки пока есть… « Блог Серёжи Борзова Says:

    […] 13 Tips to Comment Your Code - DevTopics - еще разок по граблям… […]

  18. ArticlesPR » Blog Archive » 13 Tips to Comment Your Code Says:

    […] (more…) […]

  19. Lee Says:

    (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

  20. Peter Oakleaf Says:

    I like it! Kind regards/ PeTter http://www.oakleafnow.com

  21. coding manager job Says:

    […] reasons, is not a valid excuse nowadays. Management: fine, we outsource the WHOLE team to India.http://www.devtopics.com/13-tips-to-comment-your-code/Science jobs and vacancies from NaturejobsAs the Medical Dictionaries and coding manager you report […]

  22. developer tips Says:

    "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).

  23. wiiplayer12 Says:

    Real programmers don't comment, if the code was hard to write, it should be hard to read!

  24. 今天看到的好文 - cnblogs.com Says:

    […]     代码注释的13个秘诀。 […]

Leave a Reply