K
kevin cline
Dave said:Sometimes splitting code over separate functions help, and sometimes it
doesn't. Sometimes in order to understand the code I need to see it all in
one place; get it all in my head at once. For example, a variable may be
set up in one block and used in another, and these may be coupled such
that the blocks are hard to understand in isolation.
Convert the first block into a function returning the value, then pass
it into a second function. If the first block computes multiple
values, then that data should probably be collected into a class.
You need to see how
it is used before you understand why it is set up in that particular way,
or vice-versa.
The idea that the function names should be the comments sounds fine, but I
don't find it works in practice. I like my comments to be written in plain
English, which is too wordy for function names. Verbose function names are
less readable than (reasonably) terse ones.
Here's an example to clarify:
/// Return true if this list has no members.
bool MyList::empty() const {
return head_ != NULL;
}
The comment is eight words rather than one. It explains what "empty"
means;
If you had named the function "isEmpty" instead of "empty", you could
probably live without the comment. Empty is rather a poor name, since
"Empty the trash" means to make the waste container empty. To find out
if the container is empty, we say "If the wastebasket is empty ..."
I am reading other people's code there often seems to be a lot of
information in the author's mind that didn't make it into the code,
including a special vocabulary. Comments can help correct that.
Better naming works wonders, but first one has to see a program with
consistently good naming. In my experience, few programmers have seen
such a program.
Even if the function name is sufficient (which admittedly is probably the
case with such a standard name as "empty"), there is often more to say:
/// This is guaranteed O(1) where size() may be O(N).
bool MyList::empty() const {
return head_ != NULL;
}
I never suggested that a function should not have a comment describing
it's purpose or performance. I merely suggested that blocks that are
large enough to require commenting are large enough to be extracted
into a separate function.