Inspired by Skipper’s belief in self documenting code I thought I might start dropping in some little tidbits I generate as I go about my code slinging day.
Today’s little gem is this —
bool
Clause::visit(visitor const& v, int depth) {
return ! (! _d || ! v(depth, *this) || ! this->visit_children(v, depth));
}
The Clause class is a unit in an expression. The visit method takes a function object v and invokes it on the clause and every nested clause (as long as the function object returns true), an implementation of the standard visitor pattern. I have split this method in to two, visit and visit_children because in some cases I do want to visit on the children of a clause and not the clause itself. The _d is a member variable of the class (I use the leading ‘_’ as my typographic indicator for member variables) which holds the actual data in the class. I would argue that even if you know all of this, and you are familiar with C++, the purpose of this code is not immediately obvious. I would say a short comment about the thought processes that lead to this code would be appreciated by anyone else trying to figure it out.
I will admit that well chosen method names can help but they’re hardly sufficient.
AOG:
I’m afraid I wasn’t being very clear that day.
To be clearer: I agree, no matter how well written, some code cannot be self-documenting.
However, the higher level a language (SQL, where I did most of my work, being much higher level than C), the easier it is to write code to which comments will likely not add any clarity. Just as with English, some people write better than others: compare Derrida with Sowell.
There is a problem with comments that doesn’t really affect you. Far too often (where programmers are not so conscientious) the comments are part of the draft code, but don’t reflect changes, meaning code and comments diverge over time, which can make comments counter-productive.
| Bret Wednesday, 03 February 2010 at 11:26 |
”…compare Derrida with Sowell.”
I never thought I’d see those 2 names that close together. :-)
Speaking of notes on code, Jean S. has a long post on a specific example at Climate Audit, “The Mannian Hockey Stick and the Milankovich Cycle.”