HACKER Q&A
📣 MarcellusDrum

What is your take on comments in a program?


I've been reading about the subject, and found out that people have a lot of varying opinions about this. Some say "clean code should have no comment", some use comments only when absolutely necessary, some day to document every function in details, and some day to use "why" comments, not "how" comments.

What is your take on this?


  👤 ktpsns Accepted Answer ✓
What I don't like is code where comments explain obvious things. Code should be speaking for itself.

This is an easy demand for pure administrative code ("high level" or how you want to call it) in an expressive language. Once it comes to the heart of the matter, such as a challenging algorithm which is hard to follow, I like extensive comments about the meaning of variables, etc.

Interestingly, people comment trivial stuff but don't comment the complex ones. That's a natural phenomena called Parkinson's law of triviality.


👤 alpaca128
I mainly comment in two situations:

When I wrote some weird code due to non-obvious reasons and want to clear up the reasoning; this makes later considerations easier.

Or when I had difficulties understanding the meaning of a snippet and want to make it easier to read and understand in the future.

I get why many people say comments are bad, but that doesn't mean you should never use them. And the "why" comments are definitely the most helpful ones in my opinion, I agree; one can easily look at the expressions and function calls and understand what's happening, but sometimes I want to know why the code adds 1 to some index, and a single short comment can clear that up. And if the reasoning was incorrect then that comment also tells you what to throw away.


👤 krapp
Speaking only from personal experience on personal projects, I have screwed myself up far more often by not writing comments, or deleting comments prematurely in order to "clean up" the codebase, than I have by writing too many comments.

I disagree that code should never have comments. There's no such thing as perfectly self-documenting code of more than trivial complexity, the intended means of documentation for code is comments. That's what they're there for, they're a tool, use them.

Beyond that, it's entirely a matter of style and personal preference.


👤 kgraves
As a manager who frequents HN a lot, I really don't understand this 'why' and 'how' in comments and programmer reluctance to use them, all I see is just code comments, like notes.

Could one explain or provide examples these in a way I can understand?


👤 mytailorisrich
Common sense approach: add comments where it helps to understand the code.

Commenting that i++ increments the index adds nothing. Commenting that sleep(n) is there because there must be a delay between a and b because x and y is useful.