| I personally have four reasons for writing comments. If a comment does not fall squarely into one of them, I try to omit it: 1) Why the code is doing what it's doing. What's the motivation? Why is a check necessary? What's the context? 2) High-level overview. 20 lines of code may speak for themselves, but a quick sentence can easily summarize it. I love well-summarized code. "Do X with the Y unless it's Z" is a really fast read. (Function names obviously provide this sort of explanation, but sometimes a name is not obviously not always sufficient.) 3) Stubs / future notes. Sometimes you need to leave something stubbed out. If you have thoughts on what they code will need to be, leave a note about it. This is easily removed later. 4) Quirks. If the code does something that is not obvious, note that. Non-obvious side-effects, bugs, etc. Don't discover something painful, then leave the next person (possibly a future you) to re-learn that same painful lesson. Code does stuff. Comments describe the code. Comments should not re-describe what the code does, they should be about the code and the code's context itself. |
1 & 2 are both better solved with method abstraction. Comments describing what code is doing is always a code-smell to me. If you have 20 lines of code that is non-obvious, think about extracting it to one or more well-named methods.