Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Ways of commenting subroutines

by stephen (Priest)
on Mar 28, 2001 at 13:35 UTC ( #67783=perlquestion: print w/ replies, xml ) Need Help??
stephen has asked for the wisdom of the Perl Monks concerning the following question:

I'm interested in what subroutine commenting practices people use. I'm not interested in figuring out which is the "best", just wonder methods others use...

When I create a module, before each private subroutine I put a comment like so:

## ## user_address() ## ## Arguments: ## $name: string Name of the user ## $phone: string Phone num of user ## ## Returns: string Address of user ## ## Does a database check on the given user and returns ## the address. ## sub user_address { #whatever }

I always use empty parentheses on the top line, just to make it obvious from a glance that this block of comments documents a subroutine.

Also, whenever I have a subroutine that will be called from outside the module, I use POD, like so:

=item population() Arguments: $country: string Country code of country Returns: integer Population of country Given a country, returns the population. =cut sub population { ...

My question: what do you do? I've seen a few varying styles in CPAN documentation... is there one style that you've found particularily useful, and why?

stephen

Comment on Ways of commenting subroutines
Select or Download Code
Re: Ways of commenting subroutines
by arhuman (Vicar) on Mar 28, 2001 at 13:44 UTC
    I think almost everything was said in this node (some other interesting things could be found here)

    Now For my part, chating with tilly convinced me that explicit function name, (and obviously code logic)
    is definitly something to pay attention to
    (mainly beccause of the code/comments synchronization problem):
    For example your function could be renamed db_check_user_address()

    Anyway even if it's obvious :
    Pay more attention in writing clear code rather than trying to explain complex/strange/bad/obscure code.

    NOTE: I've heard dkubb is working on a document, describing good coding practice, needless to say I'm impatient to read it...
    (Especially when you see the quality of some of this post...)
    Furthermore I see more and more questions about how to write good code? what is more elegant? how much a code should be documented? ...
    I then think I'm not the only one who find perlstyle a little bit short.
    And I really think that with all the skilled coders around, the monastery could produce a good answer...

    "Only Bad Coders Badly Code In Perl" (OBC2IP)
Re: Ways of commenting subroutines
by busunsl (Vicar) on Mar 28, 2001 at 14:09 UTC
    Most of the time I just use a one-liner for commenting subs.

    I try to adhere to the following rules:

    Use a self-explaining name for the sub, this will also explain the return value(s).
    Use self-explaining names for the parameters, they are pulled in at the top of the sub, so they are seen immediately.
    For subs used outside of the modules use pod.

Re: Ways of commenting subroutines
by jeroenes (Priest) on Mar 28, 2001 at 15:51 UTC
    tilly and others heartily recommended Code Complete. I just have started reading it, and I must say it has quite something to say on the subject of commenting. There is more to it than meets the eye, apparently.

    Jeroen
    "We are not alone"(FZ)

      I have read Code Complete, and I agree it raises some good points,
      but seeing as I don't know Pascal (which most of the examples are in)
      I find reading the book really frustrating.
      I wish he would update the book with some examples from Perl and Java.

      UPDATE:
      Maybe explaining what I meant would be good, since I am still get voted -- on this
      ack!

      I think that what Code Complete has to say regarding commenting, and construction of code to be well said, and
      still applicable.

      But there are portions of the book, especially Design, where the material Steve McConnell presents
      feels dated to me. I don't know Pascal, so talking about the merits of it as a language in his examples
      does not elucidate his discussion.

      Further, Steve McConnell spends a long portion of his discussion in design talking about modules, when I prefer functions.

      Basically I rubbed some people with my opinion and if I did, so be it. I'll take my drubbing, but it's my opinion
      and I'm not going to change it because this book holds a revered place in some people's libraries.

      I still wish he'd update his examples with some from Java or Perl.
Re: Ways of commenting subroutines
by kal (Hermit) on Mar 28, 2001 at 16:07 UTC

    I like using pre- and post- conditions a lot of the time. The subroutine should say what it expects, and under what conditions you get a return value, etc. Something like:

    sub add_one_to_number() { # add_one_to_number ($number) : takes a number, returns number + 1 # PRE1: number exists # POST1: we return the number plus one my $number = shift; if (! defined $number) { return undef; # fail PRE1 } $number++; return $number; # success POST1 }

    Okay, Noddy example, I know. It marks out under what conditions the author expected to reach these areas. If there is a bug at all, either it's because there is a precondition that we haven't thought about, or we don't successfully reach the postcondition (i.e., incorrect code). Also, putting in carps and things helps you track better what's going on if you follow the PREs and POSTs.

    It's one of the things that works for me, anyway :) (obviously, this is in addition to all the other comments and stuff you make!!)

Re: Ways of commenting subroutines
by Masem (Monsignor) on Mar 28, 2001 at 17:53 UTC
    Another possibility beyond those talked about here are using comment-to-documentation formats such as Javadoc or Doxygen, which require to have certain key lines in the comments preceeding a function to describe what happens; the comments are still quite readable within the code, and you've got an easy way to make usable documentation outside of the POD mechanism if your project calls for it.
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain

      Or Robodoc, which should work with perl too.

      Have Fun

Re: Ways of commenting subroutines
by mikfire (Deacon) on Mar 28, 2001 at 20:06 UTC
    I use a similar style, but I also try to include a header section for the entire module that descibes what it does, why it was created and any other notes necessary. I usually include a $Id$ tag as well, just to make the version number quickly available.

    Since I also use CVS for my source code control, I have also gotten in the habit of, at the very bottom of the POD, to create a HISTORY section and putting a $Log$ tag in there. It keeps the checkin history with the file, but doesn't clutter either the top of the file or r the POD with a lot.

    I also have written code similar to yours to pull my sub headers out and marginally PODify them. Check out this node for one of my more interesting attempts ( the first toy ) at documenting the possible return values for a module.

    mikfire

Re: Ways of commenting subroutines
by mbond (Beadle) on Mar 28, 2001 at 22:53 UTC
    I forget the name of this commenting style, but its supposed to be a standard so that parsers can write the basic documentation for you.

    #Requires: # var 1 to be valid <something> # var 2 to be valid <something> # #Returns: # var 1 is Preserver/Produces/Destroys

    destroys means don't count on it being there, produces means that it is generated in that function and returned to the calling function and preserved means that it will return unchanged. mbond.
Re: Ways of commenting subroutines
by Shadowfax (Sexton) on Mar 29, 2001 at 01:23 UTC

    i use a modified version of the microsoft flowerboxes
    used in Visual BASIC standards. i include the name of
    the finction in the top line and it's kinda obvious what
    else i do.
    i chose this method since the whole thing is easy to read,
    easy to modify, and contains all the info you could really
    ask for as a person walking into my code. it is usually
    more detailed than this, but in the interest of space:
    #***<StringToArray>************************************************* # Purpose: Combine 2 strings into 1 array # # Inputs : 2 strings # # Outputs: 1 array # # Programmer Date Comments # --------------- -------- -------- # Bob Smith 03/30/01 Created #******************************************************
    as for the comment to write clear code and not
    complex/hard to understand/ blah blah blah:
    i do not believe that clear or obvious code is
    always the best answer to the problem. sometimes
    a difficult to see or downright ugly answer is the
    perfect trick. if you only write clear code, then
    good luck with unclear problems.

    sincerely Shadowfax

    "A computer is almost human - except that it does not blame its mistakes on another computer."

    Edited Wed Oct 17 23:37:54 2001 - Footpad

      I think that even more than other programmers, Perl people have to take most care to write clear code.

      Perl code, with heavy use of RegEx, default variables, and syntax trickery, can be an absolute pig to read (all you one-line-coders, take note!). Code readability has to be one of the most important aspects of professional programming.

      And it's all very well making a commitment to comment all your code, but the more comments you add, the harder it becomes to maintiain your code. Either you spend too much time adjusting comments when the code changes, or you don't update them at all: (excuse the Java example)
      public String getCustomerSSN() { // return the customer's SSN< return customerSSN; }
      becomes:
      public String getCustomerID { // return the customer's SSN return customerID; }
      ...so the comment (which was already not really necessary) becomes incorrect, making the code less clear.

      A good example of code that can be relieved of comments:
      if (ftpResponse.charAt(0) == '2') // ftp result in 200s = success
      if a method is added to do this test:
      public boolean wasSuccessful(String ftpResponse) { return ftpResponse.charAt(0) == '2'; }
      ...then the original code becomes:
      if (wasSuccessful(ftpResonse))
      ...so the comment is no longer necessary.

      (The above examples come from 'Essential Java Style' by Jeff Langr (Prentice Hall PTR) - a very good book that goes through a series of Best Practise rules-of-thumb. In this case, he goes on to say that one of the few places where comments are necessary is when a method has a dependency, i.e. it requires that another method be executed first.)

      I know from personal experience that excessive comments can ruin productivity - on one of my first commercial projects, the head programmer insisted that everyone had a ratio of about 2:1 comments to code (that's two lines of comments per line of code!). The design sucked, so despite all these comments the coding was difficult, unclear and underproductive.

      On the other hand, when I worked on a project six months later, using the Extreme Programming methodology (XP), where you are supposed to have practically no commenting, we were writing excellent safe code. One of the idealogies of XP was that code always should be as simple and clear as possible. If it could not be easily understood, it was basically wrong.

      I don't want to sound like a Software Engineering lecturer, but I certainly want to say that (IMHO) if a problem is unclear, you really, REALLY should not jump in and start coding it. An extra hour spend dealing with the more abstract design will save you 10 hours in coding, maintainance and debugging, and a good design will make any problem more clear...

      (waving goodbye whilst dismounting my high horse)...
        first off, let me say that i do not disagree with you.
        that said, i would like to clarify. i was not refering
        to a problem unclear in that i did not understand. i was
        describing the fact that sometimes the logic needed for
        solving a problem is not obvious, is not intuitive, and
        quit often is not any clearer than mississippi mud. these
        are the times when after you understand the problem, you
        can step back and see the issue still resides in a fog
        bank, but rather than spend all day looking for a nice
        little way to code so that your little sister in elementary
        school can understand it, you bang in a quick and dirty
        line that solves the problem and a nice descriptive
        comment to enlighten your posterity.
        in response to the 2:1 ratio... that's called 2 weeks notice
        in my book. insanity is not my cup of tea, and that is
        clinical right there. if you have not come across a problem
        that requires ugly logic, you have not experimented much.
        i also fall heavily in support of the "hacker ethic" described
        so well by steven levy in "hackers - heroes of the
        computer revolution" in that any code you can write,
        i will write in less lines. (not a challenge, just
        philosophy) "bumming" out instructions
        is the foundation of computer programming and continues
        to drive me as a programmer. if i write something, i
        will write it later in less lines. i do not ask you to
        agree, but i ask you to not insinuate my "more functionality
        with less keystrokes" method is wrong. i do not argue
        that you are wrong because you like to write in cute
        little snippets with no comments, so please extend me
        the same curtesy. thanx, and my what a beautiful horse
        that was.

        Shadowfax

        "A computer is almost human - except that it does not blame its mistakes on another computer."
(sacked: inline POD) Re: Ways of commenting subroutines
by sacked (Hermit) on Mar 29, 2001 at 02:24 UTC
    I use inline POD so I only have to make a change in one place if the function changes:
    ################### # =pod =item displayform Usage: displayform( ['message to user']); Displays a form for the user to fill out for submission to ARS Server. Required field for the form is 'problem' (body text). There is an optional string parameter to this function that will display a message along with the form. =cut # ################### sub displayform { ...

    --sacked
Re: Ways of commenting subroutines
by Lexicon (Chaplain) on Mar 29, 2001 at 05:50 UTC
    My current commenting style, although it needs work. You'll have to excuse it's JavaScript-iness, that's all I have handy.
    // ======================================================== // COUNT OCCURRENCES ( // STR, // String to search through // SUB // String to search for // ) // -------------------------------------------------------- // Counts the instances of SUB in STR. Counts overlapping // occurrences. Count_Occurrences( 'rrrrr', 'rr') = 4. // -------------------------------------------------------- function Count_Occurrences ( STR, SUB ) { var last = 0; var count = 0; while ((last = STR.indexOf(SUB, last + 1)) > -1) { count++ } return count; }
    Update: If you ever spend a year in a country where they don't speak your language, keep a spell checker handy. Alternatively, if my code is used it will only be by non-english speakers, who wouldn't know how to spell 'occurrence' anyway. ;)

    -Lexicon

      ouch! you just hit on one of my pet peeves... bad spelling.

      It's "occurrence", not "occurance". Your code may be the greatest thing in the world since sliced bread, but if routine names contain spelling mistakes people are going to believe that the code contains other shoddinesses, thus you wind up needlessly damaging your reputation.

      Worse, client programmers using your code are going to stumble and trip, because they're going to try and call count_occurrences and fail miserably.


      --
      g r i n d e r

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2014-07-29 06:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (211 votes), past polls