Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

The art of comments: (rave from the grave)

by BrowserUk (Patriarch)
on Jul 07, 2005 at 01:47 UTC ( [id://472994]=perlmeditation: print w/replies, xml ) Need Help??

Update: No more input requested.

I just read a belated reply to a 3 year old thread, and whilst I vaguely recall a few mentions on the subject more recently, I found the thread interesting.

Rather than rehash the debate about what makes for good and bad commenting, I wonder if anyone would care to link to one or two examples of what they consider to be "good commenting". Prefereably Perl to keep it on topic, but an one or two particularly good examples of other languages might make for an interesting comparison.

A (few) remarks about why you think that the example you link is good would be interesting also, but it's not a requirement.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
  • Comment on The art of comments: (rave from the grave)

Replies are listed 'Best First'.
Re: The art of comments: (rave from the grave)
by brian_d_foy (Abbot) on Jul 07, 2005 at 05:07 UTC

    Besides the other sorts of comments people are likely to mention, I like the WTFWIT (WTF Was I Thinking) sort. Often times we write odd code to get around some special case or problem (real or imagined), but then we completely forget about what that problem was later. For instance, a remote system might return an odd result because it had a bug, and that bug has disappear. Or, more commonly, the "my brain is mush" explanation

    # the remote side is supposed to use semicolons, but in # this one case we tickle a bug in blah blah blah that # makes it use tabs so change the tabs to semicolons $foo =~ tr/\t/;/;
    OR
    # i know there is a better way to do this, but it's 3 am # and I'm an idiot

    I don't put these into the category of "good documentation", but I find them useful so I can think about what the programmer was going through when he was typing that stuff. It's completely subjective material that reminds us that programming is a human endevour. Anything that can help the maintenance programmer see what the original author was thinking is helpful :)

    And, as one of my early programming mentors said in his coding standards "All clever-ass tricks must be explained in the comments for us less clever types."

    </code>
    --
    brian d foy <brian@stonehenge.com>
Re: The art of comments: (rave from the grave)
by jhourcle (Prior) on Jul 07, 2005 at 02:50 UTC

    Good commenting is a purely subjective concept -- good for who?

    Like any form of documentation, without knowing who the intended audience is, it's impossible to say what makes good comments for them. For instance, there's detailed commenting (POD or other more detailed comments, which are good for long-term maintainers or folks who may make use of your work in other projects, but placing it all inline can possibly make it more difficult to follow the flow of the code.

    I'd propose that well written code can be self-commenting. If you select good variable, package, and subroutine names, that clearly describe their purpose in an unambigous manner, you can signficantly cut down on the amount of comments necessary.

    Take, for example, the same two equivalent functions:

    That's not to say that comments never help -- I add comments all the time, but I'd rather make the code clear on its own, rather than add comments so the code can be understood. I see no point in obfuscation for the sake of obsfucation. (It might be obscure, because it's odd logic, or you're doing something strange to deal with a specific problem condition, or even for the sake of tuning, but just trying to keep someone from understanding your code results in you not understanding your own code a few months down the road).

    Update: added readmore tags

Re: The art of comments: (rave from the grave)
by magnus (Pilgrim) on Jul 07, 2005 at 09:06 UTC
    As someone who has had to support 8,000 line perl scripts with single line comments every 300 or so lines in Italian, I can say that for me, more comments are better than less comments, in general...

    I've found myself having to support so many other people's scripts (AWK, Shell, Perl, etc) that my most beloved comment is the "explination" comment block which basically states what the next block of code is supposed to do, why and even the expected output (an extra special point if they put in their thought processes)... I know for some, this is too much commenting, but when you are supporting a script that no-body's done anything with for two years and no-one has any idea of what was behind the programming, these type of comment blocks can save DAYS of rehashing, esp. if there are multiple calls to other scripts and exported veriables...
    # # This next block was actually put in because # Joe Manager needed to see the output as a # webpage and not as a text mail. (Fair enough.) # The output (amid the html code) should look # something like: # # Logins User-ID Real Name # ------------------------------------ # 8 3rtulla Arthur Tulla #
    My opinion is that good scripts are maintainable by people who know less than you about the code, don't want to learn (necessarily) to program in that language and need to update or change that script quickly. Good commenting is how this can easily be acheived.

    okay, after re-reading this posting, i see it has a heavy sysadmin bent... my hand is revealed... =)

    magnus

      I like these types of comments as well, but I also find that lots of programmers tend lie in these comments. The comment may have been accurate at one point, but a small API change altered the behaviour of the function, yet the comment was never updated. I have seen this is my code (*blush*) as well as in others, and it can really throw you off.

      Here is a maxim that I usually go by: The farther away a comment is from the code it tries to explain the less reliable it is.

        yes, i agree... for me, it is a balance between updated code and updating/revising comments... and commenting blocks is trickier than lines, as, as you say, it can become fast impossible to tell just what is being commented on and what isn't... and too many line comments makes the code almost unreadable...

        magnus
Re: The art of comments: (rave from the grave)
by displeaser (Hermit) on Jul 07, 2005 at 12:51 UTC
    Hi,

    one piece of code on which I liked because imho it was well commented is config::inifiles: http://search.cpan.org/src/GCARLS/Config-IniFiles-2.39/IniFiles.pm.

    I liked it because it,
    A: dosnt over comment so can see whats happening and it's not obscured.
    B: Most of the comments explain something either the code or pod dosnt, ie it compliments it and explains whats happening further.

    Just my 2 cents

    Displeaser.

      Thankyou for the link!

      I know thankyous can be frowned upon, but in this case as you're the first person to actually do what I was hoping for, I think it is warrented. :)


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
Strategy in Comments, Tactics in Code
by halley (Prior) on Jul 07, 2005 at 12:55 UTC
    One, I have a rule I teach to any programmer under my supervision: strategy in comments, tactics in code. Tactics are what you do to get something done. Strategy explains what you want done. In warfare, an officer focuses on strategy: "secure that hill!" "pick the best two devices!" "find the local minimum!" Don't mention the tools you use to get that job done, soldier, unless you're being fiendishly clever. Comments should be in natural human language, while the code should just accomplish those tasks.

    Two, I have a technique I teach to any new programmer, whether they're under my supervision or not: write the comments first. Programming courses always talk about writing pseudocode: why write it on scratch paper, just to throw it away?

    sub process_ring_packet { # if we have a prior server registered, # if this packet was received from the prior, # if this server created this packet originally, # kill the packet, it's completed the trip. # scan the packet for all object references. # dispatch packet to object mentioned which we control. # if any object references remain unhandled, # if we have a next server registered, # send the packet to the next server. }
    Once the pseudocode is written in human terms, then fill in your actual code in whatever computer language is being employed. Note that I didn't say HOW to do each of the tasks in the comments. I just wrote what needed to get done.

    Lastly, as others have indicated, the actual code should not be too clever for your teammates to understand at a glance. Use clear concise words for variable names, without abbreviating them unnecessarily. Use the idioms they're familiar with. Use the language they're familiar with. You shouldn't need any # swap $x and $y comments to explain basic tasks or idioms. If you really find a clever but unusual trick, or you need to hack out something that's not obvious, then you can mention it.

    I have taught my editors to highlight tags like #REVIEW: #TODO: #BUGBUG: #HACK: so I can see areas that need more attention. Review things which may or may not be right or done in the best way. List things that are definitely undone but needed. Mark areas where known bugs are located, even if the fix isn't in there yet; give bug tracking numbers if appropriate. Mark code which is overly clever to get around dumb library limitations or which save a lot of processing in obscure ways.

    --
    [ e d @ h a l l e y . c c ]

      Two, I have a technique I teach to any new programmer, whether they're under my supervision or not: write the comments first. Programming courses always talk about writing pseudocode: why write it on scratch paper, just to throw it away?
      That leads to the archetypical example of bad comments:
      $counter ++; # Increment the counter.
      Pseudocode gets replaced, not supplemented. It's thrown away because there's something better: the real code. Comments are not a replacement for pseudo-code.
        I probably wouldn't use the word "increment" in daily conversation, so I also wouldn't write # Increment the counter. Incrementing is tactics, not strategy.

        I also didn't mention, but probably should, that right-comments are typically tags (#REVIEW #HACK etc.). Note how the pseudocode is indented as you might expect will be necessary while writing up the code.

        If a line of actual code is very close to the English description, which does occasionally happen when writing literate code, then the explanatory pseudocode can be removed. Let literate code speak for itself.

        --
        [ e d @ h a l l e y . c c ]

      Again, I was really after live examples rather than wisdom.

      Not that your wisdom isn't good, just that I was hoping for a variety of opinions back by examples.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
        (1) You asked for examples of what we think are good comments; you didn't specify that they had to be live code published on the web but I guess that's all you wanted to see. With your followup, your tone sounds more like "show me that all the wisdom isn't just hot air, prove to me that people really bother to comment properly."

        (2) The pseudocode example I gave was directly taken from my real code; the actual code between the comments would not have contributed much to the discussion so I returned it to pseudocode form. Sorry, but 99.99% of the code I write is not published on the web, nor will it be.

        (3) You're welcome to browse http://search.cpan.org/ under Authors: HALLEY for three really small examples. Fair warning: these examples are so small and simple that the comments are almost entirely POD, not # form. Perhaps someday the example I illustrated will be published, since it's a meaty and tightly-knit component library of over 30 packages, and it has a LOT of weird code that needs commenting.

        --
        [ e d @ h a l l e y . c c ]

        The problem is that it's difficult to find the ideal comment. It's easier to discuss what makes a good comment, or what doesn't, than to find a file that contains all good comments.

        It's much easier to come up with a contrived example, than to point to a file, and say 'the comments on lines 1873 to 1904 are great... of course, the rest of them suck'.

        We can't easily link to modules or such on CPAN, as they're bound to change, and so when someone comes back and reads this thread a month from now, the links might make no sense.

        If you're really in the mood for specific code -- I'll insert it here:

        The thing is -- there's a mix of good and bad comments. There's stuff in there that I said was bad (redundant comments), there's stuff that Forsaken mentioned (writing the logic in comments, then fleshing out the code), there's end-user documentation in pod, there's comments hidden from the pod, there's the comments that brain_d_foy mentioned (WTF Was I Thinking).

        By my quick count, it's almost 1300 lines total (blanks included), with about 400 lines being pod, 200 non-pod related blank lines, and 350 lines of comments. (leaving about 400 lines actually containing something useful ... although half of those are just for legibility)

        Update: blah...fixed typo in first line (does or _doesn't_)

Re: The art of comments: (rave from the grave)
by mugwumpjism (Hermit) on Jul 07, 2005 at 02:01 UTC

    To contrast and compare, why not use the old perl5db.pl as the antithesis of good commenting style.

    $h=$ENV{HOME};my@q=split/\n\n/,`cat $h/.quotes`;$s="$h/." ."signature";$t=`cat $s`;print$t,"\n",$q[rand($#q)],"\n";
Re: The art of comments: (rave from the grave)
by Forsaken (Friar) on Jul 07, 2005 at 12:40 UTC
    I actually code the other way around. I do for example something like this:
    sub foo { #takes 2 arguments, a scalar(number between x and y) and a hashref #make the scalar jump through a hoop #make a copy of the hash referenced by the hashref #set the hashref on fire #multiply each value in the newly created hash by the scalar #return a reference to said newly created hash }
    And the next step is to actually turn said train of thought into code, which would yield something like this:
    sub foo { #takes 2 arguments, a scalar(number between x and y) and a hashref my($scalar, $hashref) = @_; unless(($scalar =~ /^\d+$/) && ($scalar >= 7) && ($scalar <= 25) && +ref($hashref) eq 'HASH')) { print "you're an idiot!\n"; return; } #gee, maybe i could be a little more informative here? #make the scalar jump through a hoop make_jump_through_hoop($scalar); #make a copy of the hash referenced by the hashref my %newhash = %{$hashref}; #set the hashref on fire set_on_fire($hashref); #multiply each value in the newly created hash by the foreach my $key (keys(%newhash)) { $newhash{$key} = $newhash{$key} * $scalar; } #return a reference to said newly created hash return \%newhash; }
    So in this case(usually when I'm doing something really complicated(for me anyway)) code follows comment, not the other way around.


    Remember rule one...
Re: The art of comments: (rave from the grave)
by Limbic~Region (Chancellor) on Jul 07, 2005 at 20:08 UTC
    BrowserUk,
    95% of the code I develop is written for monks here at the Monastery or for strangers on #perl in IRC. I almost never comment code and very rarely receive questions as to how the code works. I think this because of a handful of reasons:

    • I use variable names that aid in understanding the code
    • I use function names that aid in understanding the code
    • I present the code in small digestible chunks
    • The person reading the code already knows what it is supposed to do and only has to figure out how

    There are a few instances when it has been necessary to comment my code. This is either because the approach to solving the problem is not obvious to the individual seeking assistance or because their level of competency warrants them.

    This is not to say that everyone reading the thread is able to understand it as there are rare occasions when clarification is requested. The best example of my own commented code I could find was that of Perl6 and are probably mostly superfluous due to the text description, which is what POD is for afterall.

    Cheers - L~R

    While my one public module is documented using POD, it does not contain comments.

      Limbic~Region. In part, my reason for asking for links of what people found to be good examples was an attempt to discover whether anyone ever found somebody elses comments good, rather than just their own (idea of what would make) good commenting.

      My own contention is that:

      1. many people have high ideals with regard to commenting.
      2. these rarely coincide.
      3. almost noone sticks to their own ideals.
      4. almost noone has ever seen an exampe of someone elses commenting that (sufficiently) complies with their own ideals for them to hold it up as an example.
      5. that even those rare pieces of code that start out containing good commenting, lapse into the melee of unmaintaind, out-of-date, and irrelavent over time.

      That's not to say that there aren't good uses for comments. Just that over time, they become less good.

      Personally, if find it easier to write the code than a (good) comment about it.

      Historically I've found that if I don't understand the code, the associated comments rarely help and often hinder. Indeed, if I want to work out what a compex piece of code is doing, especially if it is my intention to modify that code, I found that deleting the comments and reading the code is the only way (for me).

      Occasionally, if the commenting is detailed enough, it serves to show up a distinction between what the author thought they were coding and what they actually coded--which I guess serves a purpose, but any commenting that is detailed enough for that to be true, will usually be described as "over-commented", even by those that encourage commenting.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.

        I'd agree with this: I rarely include comments in my own code (though I put a lot of effort into making the code itself self-documenting). Similarly - and maybe because of this - I rarely look at the comments when looking at other people's code, and find it a substantial hindrance if there are too many, or if they are placed in such a way that it is difficult to look past them at just the code.

        Hugo

Re: The art of comments: (rave from the grave)
by Anonymous Monk on Jul 07, 2005 at 10:01 UTC
    I don't think "what is a good comment" is a good question. Comments seen in isolation mean nothing. Comments reflect code, and how one should use comments always depend on the code that's being commented. I think that the better the program is, the less comments it needs. A perfect program needs no comments at all.
      Comments reflect code, and how one should use comments always depend on the code that's being commented.

      Which is exactly why I didn't ask "What is a good comment", but "Please point to an example or two of what you consider to be well commented code".

      Unfortunately, noone has yet responded to that request.

      There *must* be some well commented code out there somewhere surely?


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
      A perfect program needs no comments at all.
      I disagree on this. Readability should be one of the main target of a perfect program, and comments are an important part of it. Good comments let you better understand the main blocks, the purpose of the different functions (even "private" methods, whose commenting is useful to let someone hack on it) and basically leave the possibility to modify the code. To add new features, of course, because it's perfect.

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.

        A perfect program needs no comments at all.

        I disagree on this. Readability should be one of the main target of a perfect program, and comments are an important part of it.

        I think the point is that a "perfect program" is so inherently clear that comments are unnecessary. Of course, there's no such thing, but the point is that, in the opinion of some, comments are often (ab)used as a substitute for clear programming.

        the lowliest monk

      How does the code, by itself, describe the reason why the code was written that way?

      How does the code, by itself, describe the business needs that that section of code is supposed to fulfill? How does the maintenance programmer tell if those business needs have changed?

      How do I use a programming language, in and of itself, to signal that a given, efficient but obscure algorithm is correct, and that the "obvious solution" is not the right one?

      As a real world example, one of my friends worked on an open source game. He was repeatedly annoyed by people trying to "simplify" a complex section of code, by consistantly making simplifying assumptions that initially appeared correct, but simply weren't true for all cases.

      How did he fix the code? He put in three formal proofs of algorithm correctness, documented the underlying assumptions that the would-be optimizers consistantly missed; and carefully listed all the criteria that a refactored solution would require in order to be complete.

      People stopped breaking the code after that; because there was enough information in the comments to force them to realize what the code actually did, and why it needed to be written the way it was...

        How does the code, by itself, describe the reason why the code was written that way?

        Lots of ways. Good naming of files/instances/classes/variables. Good well structured acceptance/unit test suites. Good well factored code.

        How does the code, by itself, describe the business needs that that section of code is supposed to fulfill?

        Acceptance tests are one way. Good well structured, well named code is another.

        How does the maintenance programmer tell if those business needs have changed?

        How do comments help here?

        How do I use a programming language, in and of itself, to signal that a given, efficient but obscure algorithm is correct, and that the "obvious solution" is not the right one?

        Have a test suite that fails for the obvious, but wrong, solution? Make the complex code easier to understand so that the traps are easier to spot?


        Okay, I admit it, I'm playing devil's advocate a bit. But only a little bit. Comments are not always a bad thing - especially if you lack a decent test suite.

        However, there is a very bad tendency for people to use comments as the weapon of first resort when tricky code is encountered. Something isn't obvious - just add a comment.

        A much better attitude in my opinion is to use comments as a last resort. Before that I will spend time trying to make the code clearer, separate responsibilities better, add explanatory tests, etc.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://472994]
Approved by Tanktalus
Front-paged by coreolyn
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-18 19:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found