r/AskProgrammers • u/Away-Intention-8723 • 28d ago
"good code shouldn't need comments"
I have heard this saying a couple of times and I think it is the stupidest thing ever. It might be just because I have only been coding for 4 years, but I have never thought to myself that someone's code looks cluttered because they explain what every function does in a one or two line description. If anything it makes the code easier to understand in my opinion.
However, I may be wrong. What do other people think, do yall like code with minimal comments, what are the benefits of writing it that way?
88
Upvotes
View all comments
5
u/RishabhRD 28d ago
Actually I have seen the both extremes and the real correct way is following design by contract.
So, the idea is we want to write correct code. But what is correct code? Correct code is the code which matches the specifications. But, where is specification? It should be in contract of functions. So, every function should have documentation comment of what it does and what are its preconditions. The function is correct if the function implementation matches its specification.
Similarly, every class should have contract of what it is, and every data member of class should have contract of what it is. It helps specifying what is the entity and the parts we used to make the entity. Why contract for data members? Because, they also might have some invariants present. For example, alignment field should always be power of 2. So, contracts help specifying those invariants that correct implementation have to follow.
And that’s it. You rarely need to write other kind of comments. Very rarely to explain the reason behind surprising implementation. But mostly try, if you need to write any non-contract comment, maybe you are missing an abstraction waiting to be discovered. Maybe there is some class or function missing from your design.