« Test-driven development rhythm guide | Main | J2MEUnit in 10 minutes »

January 24, 2005

Code comments: explanation vs. justification

I was recently asked, "When is it ok to add code comments?”. We then talked about explanation vs. justification.

Code should be self-explaining. What the code does, should be obvious by reading the code. If you have to add comments to the code, to explain what it does, then it is a code smell.

On the contrary, you may add comments to answer the question: "why does the code do what it does?". It is ok to add code comments, when, you have to justify some special scenarios or awkward business rules.

I got to admit, I hardly add comments to my code. By using test-driven development, my code usually talks to me: lots of small self-explaining methods with lots of tests keeps us all happy. Patterns like specification pattern can also be used in these special conditions.

Posted by gunjan at January 24, 2005 03:20 PM

Comments

Post a comment




Remember Me?

(you may use HTML tags for style)