Monday, 15 April 2013

Expressing your thinking in code comments

Comments are sometimes warning signals

When you feel the need to add a comment to a piece of code it is sometimes a signal that the code is getting too complicated. It's generally better to fix the underlying design problem than write a comment to explain the mess. As soon as code starts to become complex it is very easy to descend into a negative spiral.

However, some explanatory comments can be very helpful

I have found a lot of value writing comments to explain the rationale for a design and possible future directions that I might forget or that others will find useful. I've got a brain like a sieve and I used to find that I frequently ended up rewriting code I'd previously written because I couldn't remember the direction the design was going in or how it fits together with other pieces. A real waste of time. The comments have almost completely stopped that, but they can cause a new problem: I sometimes find it hard to resist the temptation to start implementing the future-direction ideas I'm explaining in the comment.