Writing Comments – Beginner’s Guide to Writing Comments

commentslanguage-agnostic

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.

Best Answer

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

Related Topic