Monday, December 15, 2008

No Comment!

Comments - a contentious subject

Every developer has horror stories of the monster codebase without comments, or worse yet, the one with misleading comments.

And last July I saw this - Jeff Atwood advocating coding without comments.  When I see these sorts of articles, I wonder how many multi-developer. multi-process systems the authors have worked on.  While I agree that it's hard to work on code with bad comments, if the code has seen several developers, the comments may be all that exists to explain why things are being done.

Jeff's example is relatively trite - code that implements math functions is almost by definition clear in intent.  If you have a function that implements business logic for a niche industry that will not have a clear meaning to a new developer, or a seasoned one that has been away from the code.  And that's the reason comments are necessary - no matter how good the other documentation may be, the developers will be in the code first, so that's where you need to have the most info useful to programmers.

So when you are coding, add comments that explain the logic behind the code.  Most of it might be doable with correctly-named function names, and variables, but some things are not so easily explained and need a paragraph or two to get that across.

Not this:

a++; // increment a

But this:

a++;  // the hardware uses 1-based numbering




Technorati Tags --
, , ,
HTTP

2 comments:

Brian Tkatch said...

I think there are three types of comments, what, why, and how.

What: On top of the code. List the purpose, the parameters, and if the logic is complex, the basic approach that will be taken.

Why: Explain at each assertion, assumption, exit point, or variable reset why they are being done then.

How: When a particular step of the What is being implemented, explain this is where it is being done (like an HTML anchor), or this is how it is being done.

In all cases, the name of a subroutine can also act as a comment. But if it isn't obvious, explain it. One minute explaining something while "in it" can save tens of minutes, if not hours, when not "in it".

Dixie Software Ninja said...

I'm not convinced the "how" part is necessary except in very rare cases.

I'm also not a big fan of function headers that are longer than 3 sentences. In my experience, the parameters' names give the necessary info