All looked good... until you adviced to add comments. Good code doesn't need comments because it's self explaining, if your code is more readable with comments add them... or try to write better code
I couldn't agree more... Ultimately the comment will deviate from the code so will become a lie!
Your code should be your comment (there may be a very rare exception but it should be extremely rare like one comment per year!)
Indeed, that's the main point: people rarely update the comments when the code gets changed, so the comment becomes misleading.
But it's not the only reason... most times, comments are a smell that some piece of code is too complex. Of course, the problem is the complex code, not the comments... but if you feel the need of commenting, better refrain and try to refactor it instead.
About when to comment... in my case, I do it when I write ugly code purposely. It may be due to a performance tweak, ugly but needed, or because the cleaner version generates an unexpected problem. Both of them happens rarely, but may happen, and then better advice the next one against trying to refactor (or be very careful).
Thanks for reading the post and your comments. I appreciate a good thoughtful discussion. Although I never suspected that that point would be controversial.
Goodness of code is a subjective measure and something not easy to quantify. So saying that code doesn't need documentation, if it's good code is somewhat of a hard sell. In similar vein then someone can say good code doesn't need unit tests because it's good code and ergo bug free.
Having said that, I will say that writing good comments is an skill and art on to itself. Simply describing what the code is doing is not good commenting. Describing why the code is taking the approach it has taken can be illuminating for someone who is reading the code and wondering about the choices the coder made in his implementation.
I have a constructive suggestion... paste here a piece of code which benefits from your comments, and I'll try to write the uncommented version. You'll decide which version is better ;-)
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.