In Practice

The following example illustrates these commenting principles. Consider the following snippet of C++ code. Idiomatic criticisms aside, it is not at all clear what’s going on.

for (int i = 0; i < wlst.sz(); ++i)
k(wlst[i]);

Yuck. There’s some room for improvement here, so let’s improve. The code can be made less cryptic by applying sensible layout rules and adding a few comments:

// Iterate over all widgets in the widget list
for (int i = 0; i < wlst.sz(); ++i)
{
    // Print out this widget
    k(wlst[i]);
}

Much better! Now it’s entirely clear what the code snippet is supposed to be doing. I’m still not entirely happy, though. With appropriate function and variable names, we no longer need any comments at all, since the code describes itself: ...

Get Code Craft now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.