Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
×
Programming IT Technology

Successful Strategies for Commenting Your Code 500

LilG writes "Over at Particletree, Ryan Campbell writes about Successful Strategies for Commenting Your Code. His essay gives advice and examples on proper commenting, and details some different strategies."
This discussion has been archived. No new comments can be posted.

Successful Strategies for Commenting Your Code

Comments Filter:
  • by __aaclcg7560 ( 824291 ) on Monday August 01, 2005 @12:58PM (#13215059)
    When I was learning Java in college, the instructor would give your failing grade if you don't have comments and the HTML output of the javadoc utility. The C++ instructors, on the other hand, only wanted your name, class and date in the comments. You would think that all programmers would comment their code.
  • My commenting habits (Score:3, Interesting)

    by TildeMan ( 472701 ) <gsivek AT mit DOT edu> on Monday August 01, 2005 @01:00PM (#13215080) Homepage
    I know the value of comments, so I always try to use them except in the smallest of personal utility programs. But I don't comment as I'm writing code. Instead, I write significant chunks of code, then go back and comment each piece of the chunk. In doing so, I have to think, "Okay, what is this code supposed to do?" and in the process, since I hadn't just finished writing the code, I tend to catch more typos and bugs. Seriously, I've saved myself a lot of time debugging by commenting this way.
  • by Saeed al-Sahaf ( 665390 ) on Monday August 01, 2005 @01:00PM (#13215081) Homepage
    I don't know why people (in general) don't like to comment code. I comment mostly for me, so a year or two down the line I'll know why I did something (I've found over the years of writing code, I may think I'll remember, but that often does not end up the case). In the end this selfish purpose ends up helping when other people need to maintain my code (other people fucking around with my code? Never).
  • Re:indeed (Score:3, Interesting)

    by CowboyBob500 ( 580695 ) on Monday August 01, 2005 @01:06PM (#13215153) Homepage
    I agree (I think) with you.

    Comments should be common sense and used where the developer thinks it is appropriate and where they will aid future developers/maintainers understand a particular block of code. Nothing more, nothing less. The article is just typical PHB management bullshit and I feel dumber after reading it.

    The scenario that is the ultimate end product to "comment standardisation" is what happened at a company that a friend of mine works for. They had a developer sit there for 3 days, go through the entire code base, and format the comments to the "company standard". No shit.

    Bob
  • by vivin ( 671928 ) <vivin.paliath@g[ ]l.com ['mai' in gap]> on Monday August 01, 2005 @01:10PM (#13215195) Homepage Journal
    Good comments should explain these areas:

    a) What you're doing.
    b) Why you're doing it.
    c) How you're doing it.

    I took three assembly programming classes in College. The last one was on the 68k, where we wrote an embedded OS.

    Assembly code isn't all that intuitive, and writing comments is especially important. Our professor allocated 20% of our grade on each lab to comments. In addition to accurately describing what we were doing, he checked our grammar. One thing he always stressed is that too many engineers these days don't know how to write comments. Grammar is important in getting the message across unambiguously.

    In general, if a person can read your comment and then figure out how to translate what you said into code, then your comment is pretty good. It should give an idea of what you're trying to do, why you're doing it, and how you're doing it.

    One of my professor's grad students translated a program from MACRO32 into C++, and all without even knowing MACRO32. He looked through the comments to figure out what they were doing. They were so specific that he could easily translate blocks of code over to C++.

    Comments are very important - and I should definitely comment MY code. I can't remember the number of times I've come back to code that I've written and thought "WTF am I doing here? WTF was I smoking when I wrote this?!"
  • My take (Score:3, Interesting)

    by lawpoop ( 604919 ) on Monday August 01, 2005 @01:15PM (#13215239) Homepage Journal
    I'm a self-taught PHP hacker. I've fooled around with VB for MS Access and I hate it -- way too crufty with ADO and DAO, but I digress...

    Anyway, this is the strategy I've come up with after having to go over my old code.

    • Every 'flow control' statement (if, while, else, etc) gets a comment in plain English about what conditions it's checking for.
    • Every logical block of code gets a 'mission statement' saying what large-scale, abstract task about what they are supposed to accomplish. When I say 'logical block', I'm not talking about something the computer will understand, but an abstract grouping of lines of code meant to accomplish a high-level task.
    • For some obscure functions or arguments, they will get a comment at the end, just to help myself with parts of PHP that I'm not familiar with. This is just to keep me from looking up things, and other PHP hackers may not need this commentary to understand the code and its function.
  • Literate Programming (Score:3, Interesting)

    by bsd4me ( 759597 ) on Monday August 01, 2005 @01:21PM (#13215310)

    Two words: Literate Programming [wikipedia.org]

  • by Abcd1234 ( 188840 ) on Monday August 01, 2005 @01:25PM (#13215356) Homepage
    Well, there's nothing wrong with entertaining comments, as long as that's not *all* you have. In my experience, useful comments interspersed with a bit of humour can make code analysis and maintenence at least a little less boring.
  • by Bob9113 ( 14996 ) on Monday August 01, 2005 @01:39PM (#13215490) Homepage
    Three rules of thumb that work fairly well:

    1. Use comments liberally to explain why. Why would I want to call this method? Why did you choose this particular algorithm? Why are you ignoring this exception? Source code has very little support for explaining why without comments - and why is often both the most important point and the most easily forgotten.

    2. Use comments occasionally to explain what. Your method names, parameter names, and logic should strive to be clear enough that explaining what is happening is unnecessary. But that is in a perfect world. If you can't make it clear in a reasonable amount of time, add a comment explaining what is happening.

    3. Never use comments to explain how. The real how diverges from the comment too quickly. If someone needs to see how, they should look at the source code, which is the only reliable resource for explaining how.

    There are exceptions to all of these I'm sure, and this doesn't cover everything (for example, the above says nothing parameter definition comments or copyright comments), but they're decent rules of thumb for most cases.
  • Re:Don't do it! (Score:2, Interesting)

    by halber_mensch ( 851834 ) on Monday August 01, 2005 @01:48PM (#13215598)
    Great idea! The myth of indispensibility is a great reason. May your next job be as a maintenance programmer in a Perl shop where the previous "indispensible" developer had his ass fired for threatening the boss and you get 50,000 lines of Perl dumped in your lap.

    Indispensibility is what keeps your job when the company for which you have produced code is purchased explicitly for the ownership of said code and someone must know how to use it.

    I can speak from experience, having witnessed such a purchase firsthand. The entity which did the purchasing stated outright that in order to use the code they bought the company for, they would need to keep the select few coders that knew it intimately. The source and build processes had little to no commenting or documentation, so without the programmers, the source for the products was useless. Thus 2 coders that were heavily involved in those projects and 2 other employees in other departments were given the power to negotiate a salary and keep their jobs while the rest of the company got shitcanned. Had the code been well documented and the purchaser not needed its authors to interpret it, those people would have at best been given below average compensatory salary offerings at best, or more likely notices of immediate employment termination.

    In a perfect world, we'd all have well documented code. But unfortunately in the real capitalist faux-utopia that we live in, if you aren't necessary for the operation of your own code, you become worthless in comparison to it.

  • by Not_Wiggins ( 686627 ) on Monday August 01, 2005 @01:52PM (#13215641) Journal
    Actually, I start my programming projects by writing all the comments first; in this way, I get the pseudo-code ideas down and write the associated code under each comment. It helps me track where I am in a class/function, what I'm trying to accomplish (what parts still need to be written), and it nicely leaves an understandable trail without having to back-fill the code with comments once the project is "done."

    By front-loading the process with comments, I find it really helps not just the maintainability but it also keeps my programming tasks on track.
  • by Fujisawa Sensei ( 207127 ) on Monday August 01, 2005 @02:07PM (#13215789) Journal
    One thing he always stressed is that too many engineers these days don't know how to write comments.

    I call B.S. ALL Engineers KNOW how to write comments. If they don't know how to comment they're code they aren't an Engineer. In fact I will lay odds the 60% of the "Software Engineers" out there aren't really Engineers. Just because you have a degree in Computer Science doesn't make you an Engineer. I know plenty of "Software Engineers" who don't know what an ABET accredited engineering program is.

    All that aside, knowing how to write good comments, and actually taking the time to write the comments are 2 different matters entirely. In many cases by the time programmer gets around to coding they are frequently tired of documenting what they're doing. Because they're had to write Analysis Documents, Design Documents, and Test Plans. They code doesn't need documentation because "they've already documented the hell out of the project". And guess what, that code may be thrown away in 5 years or so anyway because there's a better way of doing things. Anybody maintaing EJB 1.0 or JSP 1.0 apps these days? (I know there are a few left, but those are the exception.)

  • Flip the Script (Score:3, Interesting)

    by Doc Ruby ( 173196 ) on Monday August 01, 2005 @02:10PM (#13215830) Homepage Journal
    The best basic strategy for commenting code is to flip the script: code your comments. Start writing the program by writing, in English (or your other human language in which you design programs), what the program will do. I start the file with a comment stating what the program will do, with any input and/or output to expect. Then I start writing complete sentences, punctuated, of the steps of processing. Wnen the action is obvious (already described in a comment), I sometimes label code with just a noun clarifying what its operating on. When I've got the comments written, I add code to each section, telling the computer how to do what I said it would in the comment.

    This discipline is tied to my code layout style. I put braces ('{' and '}') each on their own line, in languages which use them to delimit blocks of code (most of the languages I use). After the opening brace, I put a single space, then a comment, like:

    # Use list if it has items.
    if($numEntries = $#list)
    { # Get personal info from people in the list.

    Then I indent the block with 4 spaces, starting with a comment, like:
            # Use local storage.
            my(@names, @addresses, @jobTitles, $name, $address, $jobTitle);

    Loops get described as a single operation, but their block describes each iteration's operation:
            # Get columns into separate lists.
            foreach $row (@list)
            { # Add fields to their columns.
                    # Get fields from row.
                    ($name, $address, $jobTitle) =
                            ($row =~ /^(.+)\s+(.+)\s+(.+)$/);

                    # Store fields in their columns.
                    push(@names, $name);
                    push(@addresses, $address);
                    push(@jobTitles, $jobTitle);
            } # each row
    } # Used list of people.

    The comments, layout and variable names make it easy to understand what's happening. So easy that it's useful to read them first, then write the code :). While this clarity is useful when collaborating with other people, it's useful to consider that you are different when time passes. So reading your own code later is easier. Even if it's Perl, and you're cramming lots of "elegance" into some data structures and regexps - the comments can be clear.
  • CSS (Score:2, Interesting)

    by t_allardyce ( 48447 ) on Monday August 01, 2005 @02:25PM (#13215959) Journal
    would this be a good time for someone to explain to me why CSS doesn't support // comments, only /* ?
  • Re:Flip the Script (Score:3, Interesting)

    by William Tanksley ( 1752 ) on Monday August 01, 2005 @10:20PM (#13219128)
    This was (is) standard in the project I worked for. They went a little further, and used a comment extractor to use the comments to generate the pseudocode, which was reviewed separately from the code. You had to turn in the formatted pseudocode at the end of the design phase.

    It wasn't terrible, but the result was a lot of comments that were echos of the code, and an unknowable amount of code that should have been broken out into discrete functions, but was instead kept nearby its comment because the comment made sense where it was. And don't forget the old code that had comments that no longer matched what the code did!!!

    All in all, I prefer the "code smells" approach to comments -- when you see a comment, think carefully about whether it's a good thing in itself, or whether it's actually being used to hide bad code. For an example of a question I might ask, with your comment "# Store fields in their columns", might it possibly be better to have a function named StoreFieldsInTheirColumns()?

    -Billy

One man's constant is another man's variable. -- A.J. Perlis

Working...