Hacker News new | ask | show | jobs
by spinningslate 1633 days ago
+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.

1 comments

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