Precision in Comments

 

As I was writing some code for the CScout refactoring browser today, I reflected on the importance of writing precise and clear comments.

Initially my code wasn't commented at all.

if (!((*call)->get_visited() & fun->second->get_visited()))
	continue;

As I considered the code somewhat tricky (note the bit-AND operation), I decided to add a comment.

// Print an edge if the functions were visited on the same tour
if (!((*call)->get_visited() & fun->second->get_visited()))
	continue;

I then realized that the code didn't print anything, and that I was talking about exactly two functions, so I made the comment more precise.

// Create an edge if both functions were visited on the same tour
if (!((*call)->get_visited() & fun->second->get_visited()))
	continue;

Having spent that effort, it struck me that the comment's logic was the opposite of what the code did, so I rephrased it again.

// No edge unless both functions were visited on the same tour
if (!((*call)->get_visited() & fun->second->get_visited()))
	continue;

Finally, as I was writing this blog entry I realized that I still hadn't clarified that I was testing bitmasks, i.e. that the bit-AND operator wasn't a mistake, so I fixed that as well.

// No edge unless both functions were visited on the same tour
// as indicated by the corresponding bitmasks.
if (!((*call)->get_visited() & fun->second->get_visited()))
	continue;

Comments have to be at least as precise as code. This can be difficult, because comments are not compiled and executed. Therefore, writing beautiful comments is more difficult than writing beautiful code.

Comments   Toot! Share


Last modified: Wednesday, April 8, 2009 12:18 am

Creative Commons Licence BY NC

Unless otherwise expressly stated, all original material on this page created by Diomidis Spinellis is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.