Hacker News new | ask | show | jobs
by Waterluvian 2623 days ago
Commit messages are a poor place to document code because they don't stay with the code. If the code isn't obvious, comments work wonders and often make the commit message more focused on documenting commit history not actual code.
3 comments

I agree that when writing confusing code, it is best to add a comment to explain it. However, in cases where the line isn't commented being able to `git blame` a section/line and read the commit message it was part of to understand the context for it can be invaluable at time.
That's a good point. I think git blame is underutilized in my world.
These are two different things.

A coment in code describes the state of the code as it is. A commit message describes a change in the code, a delta.

A comment in the code can do both, and it should. You should explain why your code is the way it is, not just what it does. Anybody can see what code does by just reading the code.
There's still a distinction between describing why the code is the way it is, and why it evolved the way it is over time. The latter is what commits capture.
Commit messages are great for explaining the order in which things happened and talking about changes that apply to disparate pieces of code.

I would still argue that comments should explain why code has changed over time -- comments should provide context for someone editing the code, which can include descriptions of what the code used to do, why it has changed, why it hasn't changed (what was already tried and why it wasn't good enough), what else would be impacted by a change, and information about the quality of the code (is it a quick hack, or has it been optimized extensively?)

Naturally you don't need to supply all of this, and if the code is changing very frequently it might be easier to put that stuff in a commit message. (It also helps when you use small, pure functions, because they tend to not need much context to understand.)

> Commit messages are a poor place to document code because they don't stay with the code.

They actually do stay with the code only as long as the code is present in the code base. The code can be updated independently of its associated comment, but the associated commit message will change.

They stay with the code as long as the code is absolutely untouched, which often is a lot shorter than a comment about code remains relevant. Code gets moved, reformatted, ... without details about it becoming stale.
Unless you have large chunks of code moved around wholesale, you can usually track all commits that touched a particular line of code. I've done that while debugging codebases that were over a decade old. And seeing those commits was incredibly helpful, despite the code itself being heavily commented.