DEV Community


Discussion on: Comments Are The Only "Code Smell"

vaclavhodek profile image

Great post. I completely agree that comments should not say WHAT the code does (such comments just duplicate the code), but WHY the code is here or WHY is it written that way, HOW it is supposed to work or WHEN it is supposed to be used.

You described WHAT and WHY.

HOW - For complex problems, briefly describe the logic behind. Not the actual two or three lines, but overall concept. Imagine something more than just a = b * 1.07, where several other methods are called, etc. With proper comment, you may not need to study it deeply. Also, HOW helps with writting tests and debugging.

WHEN - Describe appropriate use case. When it should and when it shouldn't be used. Let's say that you have method that is consuming a lot of time (which may be correct behavior) and it shouldn't be called in UI thread. Of course, only add such comment when there is a possibility of misusing the method.

bytebodger profile image
Adam Nathaniel Davis Author

Good points. I could quibble that "how" can often be accomplished by writing cleaner code. But that's not always the case.

I especially agree with "when". Sometimes you open a code file and there's a function/method there that doesn't seem to be called from anywhere within that file, and you literally can't imagine when it would ever need to be called. In those times, it's tempting to consider "cleaning" it up - by removing it. But it can be extremely helpful to have a comment there that explains, "this only gets called by a cronjob that's launched nightly from the client's environment".