Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Another commenting question,

by scottstef (Curate)
on Mar 15, 2001 at 21:09 UTC ( [id://64709]=perlmeditation: print w/replies, xml ) Need Help??

I know it is improper to not comment enough- the programmers i work with have that to a science. I know it is improper to put garbage comments in code. Is it a bad thing to comment in an almost 1:1 ration. Meaning comment each sub, variable etc. I guess the real question/meditation is at what level do you comment for? Do you comment for someone:
at your skill level?
above your skill level?
a junior programmer?
or for that #@$@$!#@*#! new jr sysadmin that doesn't know perl. And will gate keep the code from the servers?
Btw I am learning perl because i am that #@$@$!#@*#! jr sysadmin that has to put stuff on the servers.

Replies are listed 'Best First'.
Re: Another commenting question,
by footpad (Abbot) on Mar 15, 2001 at 21:36 UTC

    My thoughts:

    • Comment for two people: the person you want take over your code and one person in the whole world you would most hate to maintain your code.

    • If you use something "elegant," document it. Either in comments or supporting material.

    • If you use something taken from somewhere else, cite it and make sure copies are saved in the project folder.

    • Explain the idea, not the action. I can tell that a loop increments or sets certain values. I may not know why that's necessary.

    • Document business rules and data structures very carefully. Discuss requires relationships, indices, validations, ranges, and dependencies.

    • Explain the purpose of your programs, your subroutines, and how variables are intended to be used. Include discussions of non-supported parameters, values, and data types.

    • Carefully explain hacks and workarounds, just in case the problem being worked around eventually gets fixed.

    • Describe build processes and dependencies very carefully...just in case your manager (or an intern) needs to re-compile after you've left.

    • Update your comments as you maintain your code.

    • Spell check your comments and fix typos.

    • Include contact information as appropriate. If it's a business project, include telephone numbers and email addresses of the development manager and the project sponsor.

    • Cross-reference to other documentation as appropriate. If there's a specification, refer to it. If you're fixing a bug, include the bug number, your initials, and a very breif description of what was changed.

    When finished, ask yourself if you would find the available information adequate if you were handed the project cold, off the street. If not, you need more.

    I've mentioned previously that I tend to over-comment. However, I believe that far too much information is lost during the development of a project. Information that must be re-discovered during each development phase. This unnecessaily increases the cost and burden of maintenance. A 1:1 ratio may be extreme to some, but it's better than 0:1.

    Keep in mind that it's very easy to keep a text editor open while you're coding. Use this to collect tidbits for external documentation.

    --f

    Update: danger pointed out that I accidentally wrote "too little" when I meant "too much." Oops.... :-} Fixed.

Literate Perl? (was Re: Another commenting question)
by danger (Priest) on Mar 16, 2001 at 01:34 UTC

    I'd been thinking of doing a little blurb about Literate Programming and a thread on commenting seemed an appropriate place to bring it up.

    Literate Perl ... who'da thunk it?

    It's easy to be Perl literate---just invest a lot of time and hard work, read the camel start to finish (including the index), code 'till you bleed, and get some corrective lenses. Before you know it you'll be writing heavily punctuated, twisted loops and chains that solve the world's problems in 13 lines of code...and you'll know deep inside exactly why your particular solution is the best possible solution and you'll be justifiably proud of your accomplishments.

    The next thing you'll find yourself experiencing is STCMDE. STCMDE (pronounced: ess tee see em dee eee) stands for Standard Time Cummulative Memory Dilution Effect and occurs with alarming frequency among programmers who actually find themselves revisiting code they wrote Some-Time-Ago (STA). STA is a relative value representing the amount of time-passed required to accumulate enough memory dilution to find yourself saying 'What the heck was I thinking when I wrote that!?". For many STA may be measured in weeks, months, or for a very few, even years. For myself, STA can often be measured in days or even hours.

    The first thing you might notice when reviewing code you wrote STA is that your comments (if you used any) are somewhat inadequate---you realize that you wrote these comments while holding the overall design in your head in perfect clarity (you were writing the code at the time after all), but now that your mental model of the design has slipped into the abyss of STCMDE, you realize that your little comments are about as helpful as a string around your finger, or that unrecognizable name and phone number you found scribbled on the back of a matchbook cover from Fred's Bar and Dance Emporium where you vaguely recall spending some of last Saturday night.

    Of course, being Perl Literate, you can almost certainly decipher and re-discover the brilliant algorithmic design you incoporated into your $world->solve_problems() method. However, this takes time and energy.

    One simple solution to this problem is more verbose commenting. But verbose commenting can sometimes clutter up the code affecting readability, and often, even verbose comments for a particular subroutine don't express design ideas --- when the solution is clear in our mind we tend to think of the implementation and design as being obviously derivable from the code itself and that we'll only need reminders about the routine's interface and not its implementation.

    Another problem with verbose commenting is that it is limited to text---expressing equations or diagrams is not always an easy ASCII option, but such extras can often be helpful in documenting algorithms, datastructures, business rules, and data flow.

    Of course, there can and does exist stellar code which contains virtually no comments, but is readable---and grok-able---because attention was paid to code design, layout, structure, variable naming conventions and other details, and perhaps because the complexity was not overly taxing. But even with the best exemplars of such code, wouldn't you also like to read the author's own design notes, diagrams, and other such paraphenalia (even if, or especially if that author is you?). Just because algorithm X is perfectly clear and understandable doesn't tell you why X was chosen over the seemingly better algorithm Y (does the author know about Y at all, or is there some peculiar quirk that prevents its use in this instance?).

    Literate Programming (LP) is one possible answer. But what, then, is Literate Programming? Well, Donald Knuth (who started it all) had this enlightening bit to say:

    Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to humans what we want the computer to do. (Donald E. Knuth, 1984).

    And that sums up the point of LP in a nutshell -- we reverse the paradigm of embedding documentation within the source code, and instead embed the source code within the documentation.

    Essentially, the practice of LP is to present your code in named 'chunks'. These chunks of code not only define the hierarchical structure of the program, but also contain the actual source code of the program. Think of it as named macros, or a templating system for presenting source code. For example, I could start describing the overall structure of a program and then define the "root" chunk (the chunk that defines the top-level structure of the program):

    Blah blah blah about the overall design, and the basic structure of the program is as follows: <<foo.pl>>= #!/usr/bin/perl -w use strict; <<load modules>> <<initialize data structures>> <<accept user input>> <<perform analysis>> <<error checking>> <<foo.pod>> @

    Now, in the above, the <<foo.pl>>= token indicates the start of a chunk definition (the chunk is named foo.pl). Within that definition is a bit of code (shebang line, and strict) and then references to other named chunks (note, no trailing = sign means those are merely references to chunks, not chunk definitions, in other words, they are "includes" from elsewhere in the document).

    Now I would begin describing each of those included chunks, in whatever order makes the most sense to present them in, and defining each chunk in the same way. Furthermore, any of those included chunks could themselves also include yet further chunks at a slightly lower level of detail. You can follow this approach from the top down, bottom up (but that's generally less easy to follow), or some combination of top-bottom-sideways presentation. So, the chunking scheme gives you stepwise refinement from pseudo-code (the chunk names) down to real code.

    Another benefit is that this model isn't restricted to one program per file -- you could have two root chunks (each representing a separate extractable program) and present the programs in parallel. Why might we do this? We might develop our test program right along with our main program, and define chunks of test code in sequence with the main code being tested. Similarly, we could also include a complex test data file, and annotate it in chunks in sequence with the code chunks that parse it (chunk of header data, chunk of header parser, chunk of xyz data, chunk of xyz parser, etc.). In both of these situations, the tests and/or the test data lie near the relevant section of code in the same source file (surrounded by whatever documentation you deem necessary), and are easy to keep in sync (add to a given test/add to a given code chunk, add a new test/add a new code chunk).

    When we've written our source, we "tangle" out the root chunks (a root chunk is simply any chunk that isn't referenced (or used by) another chunk). The tangling process assembles all the code chunks for a given root chunk and writes out the file (be it the main program, the test program, or a test data file). Weaving is the process of turning the original literate source into a typeset document. Generally you write the literate source in a typesetting markup language (such as LaTeX or HTML) allowing formatting control, tables, included diagrams, or whatever. When you weave it, any chunk indexing, identifier indexing, and cross-referencing is added (depending on options and the particular LP tool you are using) and then you either view the resulting source in a browser (HTML), or run latex on the resulting file (to create xdvi, postsript, or PDF output). Of course, you can also just use plain text for the documentation and not bother with weaving at all (but then you loose any cross-referencing and such that a woven document would give you). So, the basic processes are:

    --- tangle ----> foo.pl | foo.nw | --- weave -----> foo.tex ----> latex foo ----> foo.dvi | | | -> pdflatex foo -> foo.pdf --------> foo.html

    What about debugging you ask? It would be a problem to track down problems in the tangled source and then have to locate where that code is situated in the literate source file. Fortunately, good LP tools help with this. For example, the noweb tool gives the -L option which inserts #line directives into the tangled source (Perl has line directives just like C) so that error messages will point to the relevant line in the literate source rather than the tangled source.

    Literate Programming (LP) may not be the answer to your dreams of readable source code. However, it does offer improvements over verbose commenting. And while it certainly will not take the place of well thought out design (why bother documenting poor design anyway), it does at least encourage inclusion of the design process with the source code. Another area where LP can be a big win is in teaching -- when the goal is to teach and explain via examples, often an LP approach can be better than simple commenting or line-by-line post analysis.

    I certainly don't use LP all the time (perhaps not even as often as I should) -- many scripts simply do not require such an approach, but is is worth looking into when developing larger projects. A few links to find out more about literate programming:

    • The noweb homepage. Noweb is a language independent LP tool. You can find links to projects and examples from there.
    • The LP FAQ
    • Mark-Jason Dominus has an article briefly highlighting LP as contrasted with POD.
    • PUBcrawl. Once upon a time I thought a literate perl newsletter would be cool. I twisted a few arms in my local PM group to try their hand at writing literate Perl articles -- we created one test issue and PUBcrawl has lain comatose ever since (contact me if you are interested in helping revive it).

    Hey, my 100th post!

Re: Another commenting question,
by boo_radley (Parson) on Mar 15, 2001 at 21:59 UTC
    browsing through some of my code, I see mainly 2 types of comments :
    1. Title Related
      • who wrote what when for who.
      • what's this variable do?
      • what about these subs?
    2. Explanatory
      • Delve into methodologies :"you may think that &foo() is the way to go, but I (boo) chose to use &bar() because ..."
      • Regexps and tricky blocks : "this replaces any space or tab with  ", etc.
      • Warnings : "this might look like the regexp is terminating, but since it's a multiliner, and in the middle of a \Q block, it really is just a /. The regexp ends on nnn"
    I make it a point to review comments and code on Friday afternoons, so my code is pretty well documented.
Re: Another commenting question,
by japhy (Canon) on Mar 15, 2001 at 23:31 UTC
    At my job, we recently started a style guide for our code. One point of order is the documentation we put in our code. We are putting Pod in all our modules, and even some of our CGI programs (that accept an insane number of CGI parameters).

    In addition, we are moving towards commenting blocks of code, to increase readability, and to keep everyone on the same level -- just because I wrote the code doesn't mean the guy next to me will never touch it, or maybe even modify it.

    But documenting your code line-by-line is not efficient. If you have to do that, you're not using descriptive variable and function names. They have names for a reason -- you can give them names that fit their functionality.

    One of the most informative comments I wrote today was an ASCII depiction of two images I was creating with GD. The variable names are helpful, but it's difficult to get a grasp of what the coordinates mean without some graphical representation of the figure:

    # draw a skewed rectange for each data-point # ____ # G p D \ # / o / | | # B_t_C | | # | | +-- $val_height # | face | | # | | / # | E \ # | / +-- $slant_height # A____F/ / # # \-+-/ \+/ # | | # $ppd - $consts{slant}
    And then I went on and used those alphabetic labels when I created the polygons:
    if ($params->{dim} == 3) { my $face = GD::Polygon->new; A: $face->addPt($x_pos, $yi + $val_height - 1); B: $face->addPt($x_pos, $yi + $slant_height); C: $face->addPt($x_pos + $ppd, $yi + $slant_height); D: $face->addPt($x_pos + $ppd + $consts{slant}, $yi); E: $face->addPt($x_pos + $ppd + $consts{slant}, $yi + $val_height - +$slant_height - 1); # E F: $face->addPt($x_pos + $ppd, $yi + $val_height - 1); $image->filledPolygon($face,$hist_front{"@$cRGB"}); my $top = GD::Polygon->new; B: $top->addPt($x_pos, $yi + $slant_height); G: $top->addPt($x_pos + $consts{slant}, $yi); D: $top->addPt($x_pos + $ppd + $consts{slant}, $yi); C: $top->addPt($x_pos + $ppd, $yi + $slant_height); $image->filledPolygon($top,$hist_top{"@$cRGB"}); }


    japhy -- Perl and Regex Hacker
      The single most useful comment that I can remember making, which was tied to a surprisingly well-named pair of variables that just happened to look awful, was, THINK CARTESIAN! x and y represent Cartesian coordinates. Keep that in mind and all will make sense.

      Whenever I tried to describe what I was doing in the code in words, I failed. But with the picture in hand it was dead obvious how to manipulate the grid. :-)

        Whenever I tried to describe what I was doing in the code in words, I failed.

        Just want to share my 0.3 Euro (2 cents) advice, someone once tell me :
        "Never tell what you're doing in your comments, as you should make it obvious in your code,
        instead say what is your goal and why you're doing it this way (special cases and constraints)"


        "Only Bad Coders Code Badly In Perl" (OBC2BIP)
Re: Another commenting question,
by Masem (Monsignor) on Mar 15, 2001 at 21:21 UTC
    If the eyes that will see the product may be anyone outside of yourself, you definite want to comment to a level just below your skill level. But 1 for 1 on comments is too much. For commenting perl, there's two levels that you want to do it at:

    Make sure to comment-document every subroutine and 'global' variable that is used, to the point of what it does, the general idea of how it's done, a summary of expected parameters, and what return values that it gives. This should be at least a short paragraph for somewhat complex subs. This will help others that read your program to understand the purpose of subroutines and variables. This is also a good idea to carry this concept to any significant blocks of code (ie, the stuff between matched pairs of {}'s) so that that particular block is understood.

    At the other level, you should comment anything that perl can easily make arcane, namely things like regex's, maps, foreach/while/do loops, and other operations. Most of the rest of perl tends to be at least 'readable' assuming a sufficient understanding of perl, so things like print, open, and other statements don't need comments unless you do complex operations with them. But even trivial regex lines should be explains as to what they are.

    By doing this, not only do you make your code easily maintainable by someone that follows you, but you can also use it as a learning tool for those with less experience than you.


    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
Comments as flow of consciousness...
by Elgon (Curate) on Mar 16, 2001 at 00:37 UTC
    In many ways this is a continuation to the Why my company doesn't use perl :( thread courtesy of ovid we had a while back because commenting code certainly is one of the things often implemented in a coding standard.

    I code for myself at the moment, being a poor student, but I still comment my code fairly extensively using a standard of my own devising (see below) for a number of reasons -

    First and foremost it is a good habit to get into: Much as surgeons, pilots and submariners have specific checklists that they adhere to even when such may not be strictly necessary (Here I make no claims as regards the quality of my code being to such a professional standard!) programmers should also develop such approaches. Get the habit and you'll keep it. If (when?) I end up coding as a job after University this will be one less habit to get into.

    Secondly in situations where a programmer's code may be read by others it makes sense to give a general guide to your approach to the problem: This makes it easier on other who have to read your code and explains why you have done something in the particular way you have chosen. If other people do this too, you'll find it easier to learn from their code as the approach they have chosen may not be the one you would have taken: This is something you can learn from to improve your own style and breadth of coding experience. Also it will help in code reviews as the person doing the reviewing will have a handle on your method.

    Finally, sometimes I don't get around to finishing a problem in the time I think I will: My workload can be quite heavy at times (Especially now, as I am studying in a foreign language and have exams every two to three weeks on average) so I might have to put somthing down for a week or two and the thought processes involved in the particular problem won't be simmering in the background as they often are when you're occupied on something. The comments help you to get back on track much more quickly if you've had to lay off something for more than a week or two.

    Anyway, here's the way I do things:

    1. Three line summary: Just after the shebang (and use strict;) I give a three line summary of what the program is supposed to do and roughly how. I find that three lines usually is enough to give a general outline. For bigger scripts this can/should be augmented to five lines; any more and you should consider putting the details in a pod block at the end.
    2. Scalar names and use: This is a mixture of coding style and doculentation. Having a series of variables with names like olive, gin, ice and martini so you can say $martini = ($olive + $gin + $martini)/$ice; is very cute but can be pain in the arse to unravel. Give your variables sensible names and comment them when you declare them. Something like:
      my $logfile_name; #Stores name of logfile for appending my %user_logins; #Hash of logins indexed by username
      is probably the way I'd do it.
    3. Block comments: A one line comment for each for/while/foreach block to give the general purpose of the section.
    4. Scattered comments: If you are about to do something that can be done in either a number of ways, that is a hack, or seems strange, detail what you are doing and why. This can usually be fitted into three lines.
    5. Documentation: There is nothing more frustrating than seeing a module which doesn't have the details in the pod; methods names, parameters to pass etc... On the rare occasion that I write something bigger than a 100 line script I generally stick some POD at the end detailing the niceties of the script. Required CPAN modules is a must as is the version of perl needed.

    In many ways you could think of commenting as being like the flow of consciousness as you write your code: It gives ideas as to what (the hell? ;-) you were thinking when you wrote that particular script.

    Anyway, enjoy.

    Elgon

Re: Another commenting question,
by Blue (Hermit) on Mar 16, 2001 at 00:57 UTC
    I've seen it here, but one bit of advice was don't comment your code, comment your meaning. In order to do this, you need to write code that can be understood what it does without comments. If you do something particularly convulted, this may not be the case that then that part in particular comment the code. But if you code can be understood on what it's doing, your meaning is why you are doing it.

    A comment along the lines of: # The following replaces all occurances in @awb_lines of the XX_C1 placeholder with $company That tells me what the code does. As a coder, I should be able to figure that out. (Unless, of course, Erudil or BooK wanted to hide that from me, or merlyn was playing with map, but I digress.) A much more useful comment from my viewpoint would be:

    # Update the email version of the airwaybill (@awb_lines) with # the correct sub-company name ($company) that is handling the # shipment
    Not much different, but now if someone else is maintaning your code, and there is a much better symptom to solution connection. Someone can take outside-the-program infomation ("Hey, it always doesn't have the right shipper on the AWB") and quickly connect this to the program. Without havign to hunt through logic to understant that @awb_lines is what's needed. (BTW, I needed a quick example, if I really was doing this, I would probably do this differently.)

    Even in this example, I was guilty of not using variable names that were descriptive enough. If your code documents what it does, and the comments document why it does it, and you have sufficient usage via POD, you're sitting pretty. (And doing better then me.)

    =Blue
    ...you might be eaten by a grue...

Re (tilly) 1: Another commenting question,
by tilly (Archbishop) on Mar 16, 2001 at 00:28 UTC
    What are you commenting and why? There isn't, IMO, any hard and fast rule.

    My opinion is that most of the time, most code does not need commenting upon. But your public interfaces should always be commented. In my code what I intend to be public is generally fairly obvious - it is what you see comments next to. :-)

    I explained my views in more detail in the thread starting at Re (tilly) 1: What you want and perl advocacy gone way wrong. (In that thread look for the post by IO, really.) I would also recommend The Pragmatic Programmer and Code Complete for two other books that offer good advice about the issues that commenting raises.

Re: Another commenting question,
by DeusVult (Scribe) on Mar 17, 2001 at 00:24 UTC
    The "why not what" model of commenting is a really good idea, both because it is more useful, and because it prevents the "code and comments don't match" issue. If someone is changing a section of code so fundamentally that what it is trying to do is no longer the same, then they had better damn well add their own new comments anyway. For the most part, changes to existing code will be because it didn't work quite right or they wanted to add a little functionality, in which case the philosophy behind the section will remain the same, and the comments will remain valid.

    But what I would really like to do is take a moment to shoot down the "don't comment too much" argument. Where did this come from? Can anyone seriously say that they've ever been reading some code and said to themselves, "Damnit, there are just too many comments in this code!" I didn't think so.

    There is simply no such thing as too many comments, only poorly placed or badly formatted comments. Even if you comment every single line, it is only a problem if you do so in an obtrusive and annoying manner.

    For example, consider the frequently used "box comment" style:

    ########################################################### # # Here are some comments on the following code. # It does stuff. # Its cool. # ###########################################################

    This is a perfectly good style of comment, and should be used to mark off the beginning of every file, function, and major code section.

    However, if you use this style of comment in the second loop of a triple nested while loop, it just breaks everything up. That is annoying and to be avoided. That doesn't mean that the section shouldn't be commented, merely that you need to employ a different style, like this one:

    # # This is a less intrusive way of setting off a long # block of comments inside the middle of a function or # code block. I also usually include a blank line at # the end for spacing. #

    Also popular are the "end of line" comments. The problem with these is that they can clutter things up just like people complain. The key is to use short comments and keep a uniform spacing. For example:

    use strict; #always my $this_is_ a_variable_name #does this comment stand out? my $x; #how about this one? my $what_is_going_on #where will the next comment be?

    Those are ugly, confusing comments that blur in with the code visually, and thus make the code harder to read. Try this instead:

    use strict; # always my $this_is_a_variable_name; # does this comment stand out? my $x; # how about this one? my $what_is_going_on; # where will the next comment be?

    Now, the comments stand out well, and the code can be read easily. If someone wants to read the code, they stay on the left. If someone wants to read comments, they stay on the right.

    However, avoid stupid comments such as:

    $x++; # increment $x

    That's just commenting because you don't know what to do with yourself. Instead, comment it intelligently with:

    $x++; # keep track of how many users have logged in

    The moral of the story is: always comment, but comment clearly, neatly, and intelligently. People who warn you to beware of "over-commenting" are arguing a non-issue. Of all of the comment-related problems that have arisen in the history of programming, "this code has too many comments" surely accounts for less than 0.1% of them. If you're worried about cluttered source, simply take the time to format your comments, separate with whitespace and indent liberally, and remember these words of wisdom from a programmer whose name eludes me:

    With regards to commenting, I have this to say. Write all of your code so clearly, and with variable names so explicit, that it can be easily understood without comments. Then go back and comment it anyway.

    Some people drink from the fountain of knowledge, others just gargle.

      You are heading towards exactly the same style of commenting that lead to one of the absolute worst monstrosities I have ever had the displeasure of working with. You doubt that anyone has ever complained about having too many comments. Well I have, and many excellent programmers that I know have, and your commenting style is exactly the kind of thing that makes me (based on painful experience) cringe.

      Please do yourself and the next programmer a favour and pick up a classic like Code Complete or The Pragmatic Programmer and learn about the real maintainance problems that synchronizing code and comments will introduce. They are real and severe. Instead of having 2 documents (and creating a tremendous amount of work tidying up comments that experienced programmers know not to trust) attempt to have your code stand as a comment in and of itself. Take some time to break it up, structure it, use meaningful variable names. Use meaningful subroutines. Don't use globals.

      I am sorry that I am coming across like a ton of bricks, but rather than trying to (in your words) shoot down arguments against overcommenting, you should try to understand them. What is the job of code? It is to instruct the computer in a way that a human can understand, and that humans later can figure out, refactor, and reuse with a minimum of work. Now when you run the program you can verify what the computer has been told. If you change it and run it, you can test whether the computer did the right thing. However if you change the human instructions, you do not find mistakes until after a human gets confused. And if you need to change what the instructions are, then you need to change both. In reality this does not happen. And trying to synchronize the two documents will be a constant real source of problems.

      The solution is to, as much as is feasible, have the code itself stand as a comment. As merlyn pointed out, one of your (bad) examples of how to comment uses a variable $x and then in the comment explains what $x is and what you are doing. I cannot say strongly enough that I do not want to ever work with code that is written like this! If instead you took half the energy that you are currently wasting in writing and then formatting comments that experienced programmers know not to trust and instead spent it in structuring your code and giving your variables proper names, then your code will have a much better chance of being understandable to maintainance programmers. I should know what they want - after all I spend a lot of my time doing maintainance on things that other people wrote. :-)

      For an example of what I mean take a look at Text::xSV. I wrote that last night in a couple of hours. Were it only meant for internal use, I would probably be missing the pod section, and the API comments that currently appear in the pod would be in front of the various functions. What I find interesting is that though many people have disagreed with me about commenting, they usually also say after seeing my code that they would have no problem working with it. Given that, I think that my opinions on how to make code easy to work with are worth something...

      Also note that I don't actually write uncommented code. But my comments are about different aspects of the code than the mere mechanics of what each line is doing...

        In my own defense, I would like to make it clear that I would never actually use $x as a variable name in a program. That was just for a quickie example. Any good programmer would do as you say with variable/subroutine names, no globals, and good structure. I did not make that sufficiently clear in my post. In no way can commenting, however good, make up for bad code. Good code always comes first, and good comments come second.

        However, I still contend that the good comments must, in fact, come. I, too, have been stuck doing a lot of maintenance work, and never have I come across any code so clear that it negates the need for comments. Your assertion that code can stand as its own comment seems unrealistic. Perhaps you just write much, much better code than anyone I've ever encountered :)

        Yet in my experience, the code is never sufficient. Just a few days ago, I came across some code which confused me. I even wrote to perlmonks about it. As it turns out, my understanding of the code was flawless, but I still didn't know what it did, because the author had given no indication of why he did it.

        I also took the time to peruse your example, and I must say that it seems a far better proof of my point than yours. When you read it, do you suppose that if you were not the author that you would instantly say, "Oh, of course! This code reads text data separated by an arbitrary character!"? No. But by simply reading the abstract which you so thoughtfully included, the reasoning behind the code is immediately revealed. Now, I don't know for sure if that code works as written, but I can guarantee that if I had to test or debug it, it would take at least twice as long to do so without those comments.

        Also note that it was those style of comments that were what I was attempting to advocate earlier, as opposed to play-by-play commentary on the mechanics. I also would like to apologize if there was any hostility creeping into my tone. I've simply wasted way too much time shoveling through the crap of otherwise good programmers who proclaimed their code self-explanatory.

        Some people drink from the fountain of knowledge, others just gargle.

      $x++; # keep track of how many users have logged in
      Actually, I think that's a poor comment, unless the text around it makes it make more sense. I'd prefer to see something like:
      $x++; # $x is number of users currently logged in, and we have a new o +ne
      Hmm. On re-reading your comment, I can't tell whether you meant total number of users that have ever logged in, or whether it's a current count. That's probably why I already flagged it as bad. {grin}

      Even better would be to never use $x for something like that:

      $current_users++; # we have a new one
      That's a lot better.

      -- Randal L. Schwartz, Perl hacker

        $current_user_count

        Is perhaps better (to make it obvious that it is a counter when it is not associated with the ++ operator).

Re: Another commenting question,
by jplindstrom (Monsignor) on Mar 16, 2001 at 07:48 UTC
    =head1 DOCUMENTATION =head2 The Big Picture Comment structure and approach. Describe your decisions and your rationale for making them. =head2 Interfaces Comment (define) your interfaces. Always. If you haven't stated what a sub or method does, it doesn't exist. =cut # #Comment what you do. Program how to do it. # #If you had either code or comments, you should be able to #reproduce the other. But you shouldn't have to. # #Sometimes this is only the sub/method interface. #

    /J

Something that deserves a comment
by tilly (Archbishop) on Mar 16, 2001 at 08:59 UTC
    I have an extreme of the case where seeing what the code nominally does gives no clue as to why it is being done. The comment is both accurate and useful. Try this on for size...
      I guess that is one way to write comments. I worked at a place and read thru their code code and thought it was quite humorous to see stuff like this:
      #really need to change this- really sloppy but it works. After the deadline this needs to get fixed.
      #damn deadlines- there is no reason for code this sloppy.
      #what the hell were we thinking?
      and the such.... I was just was just looking for a way to comment professionally.
Re: Another commenting question,
by McD (Chaplain) on Mar 16, 2001 at 00:59 UTC
    scottstef writes:

    Do you comment for someone: at your skill level? above your skill level? a junior programmer?

    I comment for myself. What I find most useful, though, is knowing that I'm a bear of very little brain (and long words bother me) with a serious short term memory lapse.

    As such, my comments tend to be notes to a future me answering the question, "what was I thinking?"

    This in addition to all the fine advice above, of course.

    This above all: to thine ownself be true,
    And it must follow, as the night the day,
    Thou canst not then be false to any man.

    --Hamlet, Act I scene III

    Peace,
    -McD

Re: Another commenting question,
by one4k4 (Hermit) on Mar 16, 2001 at 00:38 UTC
    Two things...

    The link to comment on this post, says 'Comment on Another commenting question'. Just thought it funny.

    When I comment, its basically whatever I'm thinking of at that moment in time pertaining to the sub I'm working on. Or var, or what-not.

    Its not for a level above, below, or equal to me. But most people will get into the same train of though I was in when reading the comments, thus helping with the code.

    _14k4

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-03-19 07:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found