27

Is there a definitive guide to writing code comments, aimed at budding developers?

Ideally, it would cover when comments should (and should not) be used, and what comments should contain.

This answer:

Do not comment WHAT you are doing, but WHY you are doing it.

The WHAT is taken care of by clean, readable and simple code with proper choice of variable names to support it. Comments show a higher level structure to the code that can't be (or is hard to) show by the code itself.

comes close, but it's a little concise for inexperienced programmers (an expansion on that with several examples and corner cases would be excellent, I think).

Update: In addition to the answers here, I think this answer to another question is highly relevant.

Cameron
  • 468
  • 3
  • 10
  • I think we are quickly moving to a world where people don't comment any more. For better of (more likely) for worse. Agile. – MK01 Nov 14 '11 at 04:50
  • 1
    @MK: If that's the case (I tend to agree more with [this answer](http://stackoverflow.com/questions/390797/are-comments-necessary-for-a-programming-language/390807#390807)), then a guide explaining how *not* to write comments, and why they should be avoided, would be just as useful. As a matter of fact, the more different viewpoints, the better. – Cameron Nov 14 '11 at 04:54
  • I think small comments to improve speed of code reading a very helpful and will always be. I don't fully buy the "stale comment" reasoning, even if they are stale, they would have historic value. I used to work on a code base which occasionally had detailed comments here and there and never was I really bitten by the comment being out of date problem. – MK01 Nov 14 '11 at 15:15
  • see also: [“Comments are a code smell”](http://softwareengineering.stackexchange.com/q/1/31260) – gnat Nov 08 '16 at 07:21

6 Answers6

40

You should be aware of the greatest weakness of comments: they grow stale. That is, as code changes, developers rarely update comments to stay in sync with the code. This means, that you can never trust them and still end up reading the code. For this very reason, your code should be self documenting. You should be choosing your function and variable names in such a way that the code reads like prose.

So don't document WHAT the code is doing. Self-documenting code should take care of that. Document WHY you are doing it. The WHY's are usually business rule related or architecture related and won't change often and go stale as fast at the WHATs. Document edge cases. Document exceptions. Document design decisions. And most importantly document those design decisions you had considered, but decided not to implement (and document WHY you decided against using them).

  • 2
    The last one is very important. Sometimes there is a bug/side-effect with implementing the obvious solution. Documenting why you chose to go with some other solution prevents the next developer from reintroducing the bug when they "fix" you seemingly poor solution. – CaffGeek Nov 14 '11 at 16:23
  • 2
    Another point, my first job considered comments as important as code. Try to get into the habit of reading comments as well as the code when you peer review, and try to insist that the comments be up-to-date whenever possible. This helps avoid the comments going stale and keeps the business rules, etc. documented in your code up-to-date. – Eric Hydrick Nov 14 '11 at 21:12
10

You should read Robert C. Martin's Clean Code book. It nicely explains that if you need comments, most likely you are not coding properly. Ideally, your code should be "self commenting." The Clean Coder book explains how to do this, so that comments are not necessary, and it described well how to do comments in situations where it is necessary. (Such as explaining a complex mathematical formula)

Bob
  • 846
  • 7
  • 16
  • Although I wouldn't so much want a complex mathematical formula *explained* as I would want it *written out* in proper mathematical notation (possibly TeX), with an explanation of its significance and source. If you don't understand the formula then you shouldn't be messing with the code that uses it to calculate some value anyway, since you are exceptionally likely to screw up and introduce (subtle or not) bugs. – user Nov 14 '11 at 12:20
  • Code can only say _how_, not _why_ or _why not_. You need comments for that. –  Feb 18 '12 at 04:26
7

Code Complete, as mentioned, has various guidelines on writing comments. In short, it's PDL and can be summed up as:

  1. Describe your intent, not what the code is doing. Avoid describing implementation details unless you are using some trick or you are using custom-implementations. For example, using shifting bits to divide, using pointer arithmetic to access class members or using a custom memory allocator for some pooled objects.

  2. Write the pseudo code (i.e, the comments) first, then write the in real code after you have finished describing your routine/method/function. The language used is high-level yet specific, so it can be rather verbose

  3. Have an idea of what your code is doing even before writing the code

  4. Have comments as close as to the actual code

The goal is to avoid long winded unrelated comments that may be outdated, but to have comments reflecting the intent and purpose of the code. Using a high level pseudo code also helps to clarify your thinking before writing the implementation.

There's a link at GameDev.net [which explains PDL][1], in case you don't want to track down the book.

Extrakun
  • 939
  • 1
  • 8
  • 14
  • 5
    _Write the pseudo code (i.e, the comments) first_. I couldn't disagree more. There is no better way to ensure comments won't match the code. New coders (and the asker specifically asked for a beginners guide) will hack and refactor functions a hundred times before they're happy with them, code will be moved around rapidly, re-written, re-purposed and at the end, they may have an elegant working solution, but it will look nothing like their initial pseudo code. Will the comments get moved and updated as they get the code to work? You can bet your sweet bippy they won't. My two cents. – Binary Worrier Nov 15 '11 at 16:16
  • 1
    Also, pseudo code comments will tell you what the code is supposed to do. The code should tell you that. Pseudo code will not tell you why the code is doing it. -1 dude, sorry, but I can't agree with the second point, times have changed. – Binary Worrier Nov 15 '11 at 16:18
  • 1
    Not to argue, but more of explanation - the pseudo code is to explain the intent of the code you have written. Meaning, the comment is not about implementation details (Such as "Add x to the top of the stack") but rather about what the code is supposed to do (such as "Make the window appears in front of everything else"). As you have rightly pointed out, you need to move comments with the code. I disagree with the code can tell you what the code is doing - all the time. Even if, a helpful/accurate comment (if I manage to write it well!) goes a long way. In the end, still IMHO. – Extrakun Nov 17 '11 at 08:36
  • 3
    A method or function called `showWindowOnTop(window)` will always be better than a comment of the same nature, all of this is outdated and bad advice in 2012. 1) Function/Method names describe intent, 2) pseudo code is hollow exercise with modern tool chains 3) Tests tell you what the code is supposed to do before you write it, 4) well named code is better than comments that don't match poorly named code –  Feb 18 '12 at 04:34
6

I just follow one simple and common principle: Your comments should not say what code is doing, but why it is doing it. Martin Fowler Article and Book on Re-factoring and Code Complete book has loads of information, but regrettably it is not in a summarized form to my knowledge.

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
Shahzeb
  • 310
  • 1
  • 4
  • 7
1

My suggestion would be to write some code without any comments whatsoever, and then walk away from it. Come back to it in a year and read it. The part that you don't understand easily is the part you should've commented.

Kevin
  • 1,341
  • 8
  • 12
  • 1
    Hah, yes ;-) This isn't particularly helpful advice, though -- perhaps this should have been a comment? – Cameron Nov 15 '11 at 06:39
  • the part that you don't understand you should have written in smaller better named parts. The main reason comments are put into code is functions/methods are way to long and should be many smaller self documenting pieces. –  Feb 18 '12 at 04:37
0

I really like how Evan Todd summarizes his view on the only useful comment categories (quoting from his blog):

  • Comments explaining why, rather than what. These are the most useful.
  • Comments with a few words explaining what the following giant chunk of code does. These are useful for navigation and reading.
  • Comments in the declaration of a data structure, explaining what each field means. These are often unnecessary, but sometimes it's not possible to map a concept intuitively to memory, and comments are necessary to describe the mapping.
Cameron
  • 468
  • 3
  • 10