3 ms·
"how" or "what" is a purely describing what is happening. // Initialization of foo initFoo(); // Send first Bar Message SendFirstBarMsg(); Descriptive comm
by seren 7y ago
"how" or "what" is a purely describing what is happening.
// Initialization of foo
initFoo();
// Send first Bar Message
SendFirstBarMsg();
Descriptive comments have usually low value because it can be (re)deduced by reading the code. But I rather read a code with too much comments that none.
On the other hand, the "why" is explaining the reasoning why it is done that way. And usually it can have been the result of bug fix, long investigation, or architectural choice so this is precious (and costly) knowledge.
initFoo();
// first Bar Message should be sent after foo init, otherwise it can create a rare race condition when bar message is received before foo is ready.
SendFirstBarMsg();
In the second example, the information about race condition is not immediately available just by reading that part of the code. This is also a (rather light) safeguard that if someone refactor the code at some point, it won't recreate a bug that had already been found.
My example is a bit contrived, but this is the idea, and that is why for me, the "why" is really important, because this is your team knowledge and experience you are distilling inside the code.
Most developers are reluctant to use the first kind of descriptive comments because, at a point, it adds more clutter, this is mostly redundant information. If you have meaningful variables and method names, this kind of comment should be superfluous.
Another rule of thumb is that code is usually written once, and will be read 10, 100 or 1000 times by other people (depending on the context or the longevity of the code base), so in my opinion, code and comments should be optimized for the long term, and for easy comprehension, because this is where most time time will be spent on the code.
To address op point "clean code should have no comment", even if you have the cleanest code base ever, you have not guarantee that down the line the people that are going to maintain it in 5 years, will be as proficient as the original writer. And additionally, these people won't have access to why it was written that way, (maybe after trying something else that did not work) so it is really important to provide them with some clues.