Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Pasting again my 4 reasons to leave a code comment:

1. An odd business requirement (share the origin story)

2. It took research (summarize with links)

3. Multiple options were considered (justify decision)

4. Question in a code review (answer in a comment)

And the article on how/what/why in code: https://max.engineer/maintainable-code



I’d also add:

- The code is not self describing for some reason (eg duffs device, complex math, non obvious cases, etc)

- The code is correct but it looks intuitively wrong. This comes up every few thousand lines for me, where some conditional looks redundant or twisted up for some reason - like maybe there’s weird choices to keep the borrow checker happy. I leave a note to myself because next time I read that code I’ll want to “fix” it.

- Internal function preconditions / invariants. Eg, “this method must only be called while the XXX mutex is held” / “this code can only be reached when YYY is true because <reason>”. Sometimes these checks can be cheaply expressed in assertions, but not always. And sometimes you need comments as well to describe the nuances of what’s going on.

Rereading my comment, maybe these are all examples of comments used to support code that’s not self describing. I’ve been programming for about 30 years now. I don’t think self describing code is always possible or desirable. I prefer fewer, longer functions with comments than digging through dozens of tiny functions spread everywhere. Large functions are usually easier to write and to read.


I agree with this, and some of this does come up in code review questions (point #4). Sometimes you can already predict a question or predict a mistake someone is likely to make, especially knowing your colleagues/context. In those cases a preemptive comment makes sense, but only if you couldn't somehow define that mistake/misconception out of existence in the code itself.


If the code doesn't speak for itself...


…then I would suggest altering the code to speak for itself. If you can't do that any further, refer to the 4 reasons to leave a comment.


And those meaningful relevant comments will be invisible in between those useless comments that were added to satisfy some tool that counts them.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: