Please create an account to participate in the Slashdot moderation system

 



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:
  • Huh? (Score:5, Funny)

    by tntguy ( 516721 ) * on Monday August 01, 2005 @12:51PM (#13214973)
    These comments you speak of, they seem foreign and strange to me.
  • by dcarey ( 321183 ) on Monday August 01, 2005 @12:52PM (#13214983) Homepage
    I was doing some maintenance on someone else's code and came across this nasty set of like 8 nested if/elses. It was a bloody horrible hack. But the best part of all was the comment right at the top: /* Oh, fuck */
    • So you found that, eh? *evil chuckle*

      I was in a similar spot a month or two ago and found some other company's comments - unhelpful as always - in the form of typed out sound effects.

      # This function goes vroooooooommm-pop!

      I have no idea why the developers put such comments there other than to entertain themselves as they sifted through their horribly written Perl.
    • 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?!"
      • 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

  • it should be hard to read!

    but not really, commenting as you go has always worked best for me, going off an uncommented API is evil when it is complex, i loathe working on some projects because there is absolutly no documentation
    • it should be hard to read!

      Like this piece of code?

      for(teamCount = 0; teamCount < defender.team.length; i++) {

      It's not the comments that are making this code confusing - it's the fact that 'i' is not defined in the function, and thus must be a global. Having a global named 'i'? Now that's bad code!

      Methinks that perhaps they meant to write:

      for(teamCount = 0; teamCount < defender.team.length; teamCount++) {
  • by modi123 ( 750470 )
    /* no */
  • Example (Score:4, Funny)

    by dduardo ( 592868 ) on Monday August 01, 2005 @12:54PM (#13215000)
    /*This loop starts at x is equal to 1 and continues while x is less then 5. x is incremented by 1 each time.*/ for( int x=1; x5; x++ ) { printf("Hello World\n");/*Prints "Hello World"*/ }
  • # does something important
    code

    code

    code

    #not sure what, but it looks important.

  • ... seems to have been turned into sawdust...
  • var names (Score:3, Insightful)

    by rockytriton ( 896444 ) on Monday August 01, 2005 @12:54PM (#13215004)
    My best strategy is intelligent variable names and clean simple code. -- http://www.dreamsyssoft.com [dreamsyssoft.com]
    • This is the most insightful post but you must not forget to enable the code completion of your IDE if you want to type "teamEnumerator" as fast as "p" in a loop.
  • by ChrisF79 ( 829953 ) on Monday August 01, 2005 @12:54PM (#13215013) Homepage
    I viewed the source on the site and nothing was commented :)
  • by jetkust ( 596906 ) on Monday August 01, 2005 @12:55PM (#13215017)
    Comments are more important than Code?

    I once tried writing code that was completely made up of comments. It was easy to write and all, but didn't work very well.
  • Comments? We don't need no stinkin' comments!

    Why would I want to risk my future job security by letting other people know what I am doing?

    Seriously, we all need to comment. But, how desperate are we for topics when we have a slashdot submission on "commenting strategies"? All you need to do is get all of the developers in a room and spend ten minutes talking about what should appear in comments. Then, enforce the rules with code reviews.

  • /* TODO: Flesh out comment here */
  • by i.r.id10t ( 595143 ) on Monday August 01, 2005 @12:56PM (#13215035)
    Don't comment at all, and just run it thru The Commentator!

    http://www.cenqua.com/commentator/ [cenqua.com]

  • /*
    * FIXME - Should handle slashdotting better.
    */
  • by Anonymous Coward on Monday August 01, 2005 @12:57PM (#13215044)
    But when reading the article I was glad that the very first item was SELF DESCRIBING CODE. The most important part of code documentation is the code iteself IMHO.

    I think it was Fowler who once went as far as to state that when you find yourself needing to document code in order for it to be understood (vs. thoroughness, completness, or document generation) you probably need to refactor your code.

    How many times have we come across code like this?

    public void bigFunction1()...

    public void bigFunction2()...
    • Self describing code is great for explaining what the algorithm is, but sometimes it's just not going to be clear how a function fits into the big picture (because the problem you're solving is a mess), and sometimes you need a clever algorithm that solves the problem in a non-obvious way. The mapping of code to algorithm may be self-describing, but that doesn't mean the mapping of algorithm to problem space is (or that it can be made so - in many cases it's the problem being solved that needs the all the
  • Commenting (Score:5, Insightful)

    by Hamster Of Death ( 413544 ) on Monday August 01, 2005 @12:57PM (#13215046)
    Write the comments first, then add the code. That way you'll get a better grasp on the problem you're solving. If your comments don't explain the problem or someone else can't solve the problem using your comments then you'll probably need to rethink your approach.
    And for crying out loud update the comments when you change code!
    *grumbles about 10 year old code and 15 year old comments*
    • This is *exactly* how I've approached many problems in the past couple of years, and it has amazed me how many logical errors are visible when someone does a quick peer review of my comment-only pseudo-code. At this point, you don't have to be knowledgeable about the language your co-worker is using. You simply need to have a reasonable grasp of the logical flow to spot potential problems.

      Tim
    • Re:Commenting (Score:4, Insightful)

      by bmwm3nut ( 556681 ) on Monday August 01, 2005 @01:50PM (#13215613)
      exactly! in fact, this was taught to me by a senior programmer who said: "you should never document your code, your should code your document." in projects where i've followed that rule, i've had many fewer problems than ones where i jumped into the code quickly.
  • by StarvingSE ( 875139 ) on Monday August 01, 2005 @12:57PM (#13215048)
    The next generation of professional coders will most likely be good commenters as well. I know from experience in my computer science classes, professors will mark programming assignments down significantly if comments are not included, or if they are hard to read. Most of the time they want all functions to be commented to explain what their parameters mean, how the function works, and the format of the output.
    • My old C++ prof would mark down for too many comments or unneccessary comments.
    • Comments were stressed just as much when I was taking programming courses ~30 years ago. The problem isn't that people aren't taught to write comments. There are lots of reasons that people don't write good comments:

      - It's hard, and it's hard to know that you got it right: Getting code right means the program works. Getting the comments right and there might be a payoff months in the future.

      - Lots of programmers aren't good writers. Comments are written for people to read.
    • As one who has graded many undergraduate programming assignments I can tell you that professors very seldom actually read, let alone provide feedback on, comments. Comments on assignments tend to be scored as, "Are they there? If yes, good! If not, -10 pts for being a dumb ass."

      Summary: Though the next generation of coders may be more diligent about including comments (at least initially -- though I'm not sure I'm even convinced on this point), there is nothing that leads me to believe the content and ap
    • I disagree that schools emphasising the value of comments will make students better at commenting. An analogy would be that the value of literature is already emphasised by schools - yet still relatively few students become great authors.
    • Part of this is to prevent cheating. Everyone will turn in essentially an identical program, so comments set people apart. Anyone can change the variable from iCount to CounterX, but when people try to explain what the code is doing, you clearly see who got it from a friend.

      They definitely preach commenting for other reasons also. I helped my brother-in-law for Comp Sci 1, and his professor made them comment to the point where there were 10 lines of code and 20 lines of comments.
  • 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.
    • I strongly agree that students should be taught from the beginning to comment their code. That being said, when I was in school I noticed that the instructors who were the most anal about comments were the least effective at teching programming. One teacher in particular (not really a professor) would fail an assignment entirely if the comments were not exactly like she wanted them, and the requirements were quite complex. However she didn't have a clue about programming beyond the examples listed in the te
    • 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.

      C++ means never having to
      printf("Sorry"); //real coders are silent
      .
  • Properly tab comments Make sure comments are tabbed out to the line they are referencing. Additionally, make sure similar comment types align when tabbed.
    Both those who prefer indenting with tabs and those who prefer indenting with spaces tend to agree: use spaces for alignment. Otherwise when somebody with a different tabstop comes along, your comments will be all out of whack.

    Dlugar
    • True that. I use UltraEdit for most of my coding now, and it has a nice tool built in for converting tabs to spaces and vice versa.

      There's nothing worse than loading up a project someone else wrote and had their tabstop set at one space. I think they do that on purpose :)
    • I find the expand utility (which probably comes with most Linux distros) very useful for this. Type tabs in whatever IDE you're using, run expand when you're done, and you have spaces. I imagine that most editors even go so far as to build this feature in, though I've never bothered looking it up in vi.
    • Commandment T: Tab stops shall be set at 8 characters. No more. No less. Indents, I'm not so picky about, as long as they're a factor of 8 (3 and 5 just freak me out...). If you're using a real programming editor (e.g. vim or xemacs, and not notepad!) the editor should keep things straight for you.

      If it gets really bad, there's always: Ctrl+Home, Ctrl+Space, Ctrl+End, Ctrl+Alt+\
  • by Jeffrey Baker ( 6191 ) on Monday August 01, 2005 @12:58PM (#13215064)
    Dear Doxygen and JavaDoc users,

    The following is an example of useless documentation:

    frobWoggleFfloofMoing

    public void frobWoggleFfloofMoing(String, String, String)

    Frobs the Woggle

    ...

    You see, running Doxygen over your header files may produce some output in HTML format, but it doesn't produce what I like to call "documentation." For instance, documentation would explain what is a Woggle, and when should it be Frobbed?

    Thank you, and have a nice life.

    • ROFL. That reminds me of the documentation for the Scientific Atlanta PowerTV APIs (these are the APIs used on various digital settop boxes). They have exactly that style of documentation, *printed*... it's *immensely* frustrating.
    • Score:6, one of the most important comments on Slashdot.

      Couldn't agree more. There is nothing like the sinking feeling when you see a project uses Doxygen because it almost always means the "documentation" will be useless. Doxygen is useful in its place, but that place is only as *part* of a documentation process.

      Aaarrghh!

      Roger
  • If success is defined as enhancing your job security, then boobytrap your code with misleading comments to make it impossible for anybody else to work on it.

  • Comment out all buggy code, all code written by coworkers and all code written under previous boss. Increses your popularity with current boss.
  • 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).

    • Two years down the line? I comment code so I remember it two DAYS down the line.

      I've lost my train of thought.
  • For those writing in assembly (and why waste time writing in any less efficent language?), I find the best rule is that every single line must have a comment. Additional comments can be added as needed. I can actually go back and understand my assembly code this way.
  • by WillAffleckUW ( 858324 ) on Monday August 01, 2005 @01:03PM (#13215113) Homepage Journal
    1. Never spelchezk.
    2. Use randomly chosen variable names, or objects that resemble your favorite Orcs and Trolls from LotR - after all, everyone knows that a Lothlorien object will have farseeing ability, so it's obvious.
    3. When instantiating something for the first time, never explain it - real programmers read the original object source.
    4. If you do something complex, write a short pithy comment like /* magic occurs */
    5. If you do something easy but you were drinking too much hot cocoa, write a long verbose description, and also mention how good the hot cocoa was.
    6. Always include song lyrics to what you're listening to while you wrote the code.
    7. Object inheritence means never having to explain the code.
    8. Repetition is the best way to reinforce obvious things - so repeat the obvious thing since it's the best way to reinforce it.
    9. If you break up with your girl/boyfriend, write about it in the comments - people really want to know.
    10. If you're updating or modifying code, write your opinion about the original code in the comments. Use nasty words if you can.
  • by eno2001 ( 527078 ) on Monday August 01, 2005 @01:03PM (#13215119) Homepage Journal
    ...on who is going to be reading the code after you are gone. Sadly, due to differing levels of expertise, there is no optimum method of commenting code. For some, this is a very useful comment (I'm using pound sign comment designation as an example):

    # The main function starts here

    or...

    # This is a loop and it will run while a certain
    # condition exists.

    or...

    # Don't forget to remove this section after
    # I'm gone - Dan - 04/25/1995

    Think about the children! ;P

  • How & Whys (Score:4, Insightful)

    by Anonymous Coward on Monday August 01, 2005 @01:05PM (#13215136)
    It's been said before, but I find the best advice I've ever gotten on commenting code is very simple -

    Comment the why, not the how.

    Hopefully the code should be clear enough to pick out the how, but *why* you are doing something is never going to be apparent from the code itself - at best someone might be able to infer it, but that becomes especially tricky when time passes or a new person signs on.
  • Proper commenting, as usual, remains just out of reach.

    Today's Excuse: Well I would have commented my code just like they said to, but the site was Slashdotted so I couldn't learn how to do it right. By the time the page finally loaded it was time to deliver the project. But I really, really, REALLY promise I will comment my code next time. Yes, really!

  • You can find the article text here [mirrordot.org] on MirrorDot.
  • All functions/methods (besides accessors) are commented. If a chunk of code needs a comment, it should be refactored into its own method and that method should be commented.

    Someone suggested this simple strategy to me a few years ago and I'm surprised at how well others pick up my code quickly. It really does make a big difference.
  • 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.
  • I maintain some legacy code that has, during it's (30 year) life, been converted through various versions of the language making it virtualy unreadable in places. There's one fairly frequently used section commented with:

    'not quite sure what this bit does'

    It's been like that for years, but whatever it does, it seems to work.
  • zerg (Score:5, Insightful)

    by Lord Omlette ( 124579 ) on Monday August 01, 2005 @01:16PM (#13215249) Homepage
    Ask someone else to look at your code. Every time they pause while scrolling, touch their chin, squint their eyes, furrow their brows, etc., it means you need a comment.
  • It is a good practice to write comments at the same time (or earlier than) you write your code.


    This is what I do; I've always thought comments should allow one to reproduce the functionality of the code just by reading the comments. Also makes it much easier to understand what you've done when you or someone gets back to it later.

  • I strongly agree with some of this, especially giving everything clear names, which he calls code commenting. (I hate Hungarian notation, though.) I love TODO comments: they are a great for an author to record thinking about future improvements. And if I'm publishing an API, in-code documentation like JavaDoc are a great way to keep your API docs.

    But he doesn't mention unit tests at all, which I think are one of the best places to define what code is for. Unlike regular comments, unit tests can be verified
  • Successful Strategies for Crashing Your Website
  • It isn't exactly a dupe -- but hasn't this been covered already, sometime in the decades we've been writing code?

    Or did we really wait 30-40 years to bother to write up something on how to comment?

  • The syntax for commenting things in the Doxygen style is a little weird, but once you're used to it, its great. I find it much easier to keep my comments up to date than my external documentation, so this way I can do both. In addition, I'm a consultant, which means I often have to look at massive amounts of code written by other people, most of which is uncommented. I find that running any code I have through Doxygen before anything else gives me a nice, clear, high level view of how the code is structu
  • Literate Programming (Score:3, Interesting)

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

    Two words: Literate Programming [wikipedia.org]

  • Iteration and loop counting is nice, but leads to reader fatigue and antipathy...

    To ensure readability, make sure to translate all iterator use and loop constructs to recursive function calls and definitions.

    Besides, if the next programmer can't deal with it, he's unworthy ;-)
  • Since I can't post on his site, here are a few interesting ones:

    I'll throw in some disagreement about a couple of things. Code commenting has one purpose: to communicate to a developer at some time in the future how some code works, so that he can adapt/fix it. There is also interface documentation (ie javadoc) but I consider that an essentially solved and separate issue.

    Hungarian notation is bad because it discourages descriptive naming. By forcing you to add extra characters to a name indicating type,
  • Don't comment.

    Write intention-revealing code. Use meaningful identifiers. Write with the maintenance programmer in mind. Code is write-once, read-many. In the days of low-level programming languages and maximum identifier length, comments were at least necessary to explain WTF a PLGRNX1 means. With modern development tools, you don't even have to type out the whole identifier after the first time, you can use code completion.

    Too many comments makes me wonder why the programmer couldn't write clearer code.
  • 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.
  • 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.
    • 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 commen

THEGODDESSOFTHENETHASTWISTINGFINGERSANDHERVOICEISLIKEAJAVELININTHENIGHTDUDE

Working...