Hacker News new | ask | show | jobs
by salmonellaeater 1633 days ago
One that's missing: comments should explain why a piece of code exists or is written in a certain way (and implicitly, when it can be changed or removed). This overlaps with "explain unidiomatic code in comments", but there can be idiomatic code whose purpose isn't obvious.
3 comments

+1 for this. It also links to my #1 rule for comments: why not. It applies when:

1. There's a chunk of code that, on first reading, could be clearer/simpler/more idiomatic.

2. There's a good reason not to use the obvious approach, and do something else instead (maybe performance).

Then comment to explain why the obvious path wasn't taken. No matter how well written, code alone can never explain "why not". I've found this invaluable, even looking back at my own code.

“Why not” is one of the top reasons to write a comment. It should be discussed more. Many times I've encountered a piece of code which could have been much simpler or idiomatic. Upon rewriting, I discovered that it didn't work for some obscure reason. If there's no comment explaining “why not”, many others (including future me) could lose time trying to do the same.
Man, I've been bit a few times with this. I'll read code and think, "Why the hell did they do that?" Later, when I'm almost done re-writing it, I see the edge case they were working around.

At the very least, comment these situations.

I think "why not" is one of those things which definitely does not belong in comments, if you regularly write up such justification, your code becomes mostly comments. Even more so than "positive" comments, "negative" comments belong in the commit message.

Possibly unless your entire codebase is literate, and code is secondary to comments.

honestly it needs both, but if you only put it in 1 place put it in code.

During the development you are mostly likely looking at commits, or PRs, so that makes sense.

But if its long living piece of code, people will get you your code via following function/method chains or just browsing the source not commits. While you can use git blame, and then figure out the commit, and then read last few commit messages, putting comment on code is easier on everybody.

I once worked in a codebase full of such comments, they were all like

// Adding this because XYZ said so

Sounds like a plain-language version of "git blame"!
I've also seen it where every comment was just who made the code change and the date. "John K. 10/13/1994"
When I started many aeons ago, when I did not know what I am doing, so I tempted to documented the language itself:

inc al ; add one to al register