Clean code - Why comments in your code are discouraged?

A guide to writing clean code without any comments to explain it.

Clean code - Why comments in your code are discouraged?

Comment in a code is like an extra organ which although attached to a body but has no function, much like a vestigial organ. Writing software is very much similar to writing a novel or a story. If you have the idea, you can choose your words to write the script and the reader will benefit by just reading it without any external help or explanation required. Similarly, a good and clean code is written in such a way that it doesn't need any external factor like comment for elaborating more. Consider the below code which is written with a lot of comments added to it. I will explain the intent of the code later because that's how a developer will read it, once the software becomes legacy and goes into maintenance.

The intent of the function is to calculate net income based on the gross income and income tax rate provided in the variables respectively. Till this, it looks fine and the comment also serves the purpose. What if we want to modify this formula to calculate income tax based on the income slabs, for eg; if a person is having a package of 100000 and the country or state in which he\she is living has slabs for tax like below.

  • Income <= 20000, Tax = 0%
  • Income >= 20000 & <= 50000, Tax = 10%
  • Income >= 50000 & <= 100000, Tax = 20%
  • Income >= 100000, Tax = 30%

With the above rule in place, generally, we may want to overload our function and have this formula taken care of. But let's take, for example, if a developer is modifying the above code with the logic mentioned, then, in that case, he also needs to consider the comment that has been mentioned above the logic.

Basically, the job is to maintain the code, but instead of writing meaningful code, a developer might end up maintaining a comment. Code variables or names should be written in such a way, just by reading it, people should understand, where exactly this fits into this small code of the software. It can happen also that even after modifying the code, we forgot to update the comment for eg, the below code roughly takes care of calculating the net income based on the tax slabs. But somehow modifying the comment is missed and it might give wrong information about the logic being written as the logic and the comment are contradicting each other.

This example is a very small analogy to the real-world problems that a software product solves. In a more complex code or algorithm, in the long run, slight misinformation can lead to some serious bugs if not maintained and refactored regularly and consciously. Hence the takeaway from this article is to use comments for API documentation or copyright comments, but not on the logic that's inside it.

Thanks for reading!!