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.


J. B. Rainsberger said...

I use SMELL and REFACTOR comments. SMELL when I've identified the problem, but haven't thought about or decided on an improvement. REFACTOR when I've identified an improvement, but don't want/need to do it right now. My REFACTOR comments sound like your FUTURE comments.

Improving all design everywhere represents a phase of learning that everyone goes through on the way to becoming proficient designers. I worry sometimes that when we say "the design doesn't have to be great everywhere", without adding this extra bit of context, then many people take that as an excuse not to learn, and learning remains ever the bottleneck.

David Peterson said...

Thanks, I like these tags. I think FUTURE still has a place:

TODO = We need to do this.

SMELL = There's a problem with the design, but we haven't tried to solve it.

REFACTOR = We have a suggested refactoring but have currently postponed it.

FUTURE = There are no real problems with the design as it is, but the design could go in this direction.

J. B. Rainsberger said...

I like the distinctions. Thank you for the ideas.

Andreas said...

It's a small advice with no extra effort. I really like such things :)

One thing I always wished for is that you could place comments not only IN the code, but BESIDES the code. So my flow of reading the code is not disturbed by default.

Also I always wanted comments with rich formatting.

What I want to say with that: while languages like C# and Java greatly evolved, comments did not.