Slashdot Mirror


Successful Strategies for Commenting Your Code

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."

500 comments

  1. Huh? by tntguy · · Score: 5, Funny

    These comments you speak of, they seem foreign and strange to me.

    1. Re:Huh? by bluelip · · Score: 3, Funny

      "The code was hard to write. The code should be hard to read."

      Was that some form of early DMCA or IP lockdown?

      --

      Yep, I never spell check.
      More incorrect spellings can be found he
    2. Re:Huh? by TommydCat · · Score: 2, Funny

      /* Please phrase your reply in the form of a comment. */ /* Thank you */

      --
      This comment does not necessarily represent the views and opinions of the author.
    3. Re:Huh? by torpor · · Score: 2, Funny

      /*
        * slashdot comment comment
        * 1.0.0 - torpor - init.
          */

      #pragma KARMA_HACK // technically, also a comment. /* comments are fun. */ //code goes here..

      --
      ; -- the corruption of government starts with its secrets. a truly free people keep no secrets. --
    4. Re:Huh? by MHobbit · · Score: 4, Funny

      A TRUE Klingon warrior does not comment his code!

      *ducks*

      --
      Debugging? Klingons do not debug. Bugs are good for building character in the user.
    5. Re:Huh? by KinkifyTheNation · · Score: 1

      They call it "code" for a reason!

    6. Re:Huh? by Seumas · · Score: 1

      # In Soviet Russia, code comments YOU!
      # In Korea, only old people comment code!

    7. Re:Huh? by Pollardito · · Score: 1

      exactly, my commenting strategy is "eventually"

    8. Re:Huh? by Kehvarl · · Score: 2, Funny

      *ducks*

      A true Klingon warrior does not duck.

      A true Klingon warrior would have nothing to do with such a weak waterfowl.

    9. Re:Huh? by jamshid · · Score: 1

      Here's a funny guide about how to write unmaintainable code. Here's a link to the documentation section:

      http://mindprod.com/jgloss/unmaindocumentation.htm l

      and here are the general principles:

      "To foil the maintenance programmer, you have to understand how he thinks. He has your giant program. He has no time to read it all, much less understand it. He wants to rapidly find the place to make his change, make it and get out and have no unexpected side effects from the change.

      He views your code through a toilet paper tube. He can only see a tiny piece of your program at a time. You want to make sure he can never get at the big picture from doing that. You want to make it as hard as possible for him to find the code he is looking for. But even more important, you want to make it as awkward as possible for him to safely ignore anything. "

    10. Re:Huh? by not-enough-info · · Score: 2, Funny

      The user catalog is a perl database and we need to localize for how many countries? Then, today is a good day to die!

      --
      ---k--
      </stupid>
    11. Re:Huh? by thelaughingman · · Score: 1

      Last I heard, these 'comments' were nothing more then an hacker tool. http://slashdot.org/article.pl?sid=05/06/29/122120 7&tid=217

    12. Re:Huh? by hhlost · · Score: 2, Funny

      // TODO: add comments

    13. Re:Huh? by zipzap54 · · Score: 1



      /* No Comment */

      --
      "All programmers are playwrights and all computers are lousy actors."
    14. Re:Huh? by HornWumpus · · Score: 1
      A TRUE Klingon does'nt edit or compile.

      He just copys console to .exe and enters op codes with the Altkey and numpad.

      --
      John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
    15. Re:Huh? by Baricom · · Score: 1

      Nonsense. Ducks are among the most honorable of the lesser species. I shall never forget the three most profound words ever spoken by the wise human philosopher, Gordon Bombay: "Ducks stick together."

    16. Re:Huh? by maxwell+demon · · Score: 1

      /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*
      * Slashdot Comment                     *
      * Author: maxwell demon                *
      * Purpose: Answer to Comment #13215065 *
      *xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/

      // FIXME: Find something insightful to say here

      // TODO: Find out how to prevent the lameness filter blocking
      // post like this one without having to add lots of meaningless
      // stuff to the comment, which actually adds to the lameness
      // of a posting instead of reducing it.

      // TODO: Find out how slashdot determines if there are
      // "too many" 'junk' characters.

      // TODO: Find out why even that many text doesn't seem to
      // counter the few stars at the beginning

      // WORKAROUND: changed some stars to 'x'

      // FIXME: Find out how to prevent slashdot from eating spaces
      // at the beginning of the line

      --
      The Tao of math: The numbers you can count are not the real numbers.
    17. Re:Huh? by Anonymous Coward · · Score: 0

      This might end up being the last post but after reading through the comments, the subject was never touched.

      What happens if the person or persons following you in developing code do not speak english. I know that most Indian developers speak english but what happnes if the offshoring of IT starts going to other countries other than India. Say, China or Russia?

      Comments in code will then be useless.

    18. Re:Huh? by Kehvarl · · Score: 1

      I believe you are neglecting the post script to that comment. It involved superglue.

    19. Re:Huh? by Anonymous Coward · · Score: 0

      A true Klingon warrior does not comment his ducks, either!

  2. indeed by Anonymous Coward · · Score: 0

    indeed, that's the problem

    -- marc

    1. Re:indeed by CowboyBob500 · · Score: 2, Interesting

      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

    2. Re:indeed by Anonymous Coward · · Score: 0

      I disagree, sort of.

      At least when you're in a position where your code is read by many others, I feel that the more verbose, the better. Structured, of course.

      It may cost a bit more timewise, but it requires little thought (although it can be hard for people) and it tends to help out and make a good impression.

    3. Re:indeed by lgw · · Score: 1

      Not that the article is brilliant, but it's sometimes necessary to require some sort of comments to get certain programmers to have any comments at all. At the same time, it's good to remind people that you don't need tocomment everything. My favorite rule from any job was: you're required to add a comment when you do something clever.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    4. Re:indeed by NicodemusPrime · · Score: 1

      I would have to agree. Having hard to locate/read comments is as bad as not having them at all. It may be a pain in the ass to do it to a large codebase, but it makes life easier down the road. I would rather spend 20 mins writing structured comments than 3 hours trying to figure out what purpose this function serves.

    5. Re:indeed by B'Trey · · Score: 2, Informative

      There are two problems with this.

      The first is that common sense isn't. There are lots of coders who seem not to have any.

      Second, what seems clear and obvious when you're writing the code is anything but to someone else who's approaching the code fresh. That "someone else" may very well be you six months or a year down the road. Every function over one line (and most of those) should have a comment indicating what it does. Any variable that isn't a throwaway loop counter or similar should either be so clearly named that your grandmother could tell you what it's used for or be commented. Etc.

      It takes seconds or minutes to write comments. One comment can save you hours of time and loads of frustration. Common sense says to write the comments, even if you don't think you'll need them. You only need to be wrong once or twice to come out ahead.

      --

      "The legitimate powers of government extend only to such acts as are injurious to others." Thomas Jefferson.

    6. Re:indeed by CowboyBob500 · · Score: 1

      I never said that developers shouldn't comment their code. I was simply saying that formalising the structure of comments is a waste of time. If a developer doesn't understand where comments are appropriate, they are not a good developer and should be fired for being inadequate at their job.

      Formalising the process of comment writing is adding yet another burden onto the developer along with development methodologies, case tools (though not if being used for MDA), pair-programming, and all the other shit that PHBs think is wonderful after discovering it at some conference.

      Bob

    7. Re:indeed by ozmanjusri · · Score: 1

      My favorite rule from any job was: you're required to add a comment when you do something clever.

      So I should have added a comment for my resignation letter?

      --
      "I've got more toys than Teruhisa Kitahara."
  3. My favorite code comment not written by me by dcarey · · Score: 4, Funny

    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 */

    --

    -- (Score:i , Imaginary)

    1. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      At my job, I had to go in and do some maintenance on some old code.

      Right at the top was this comment..

      /* My appologies to the poor SOB who has to work on this! */

    2. Re:My favorite code comment not written by me by lukewarmfusion · · Score: 4, Funny

      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.

    3. Re:My favorite code comment not written by me by Abcd1234 · · Score: 4, Interesting

      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.

    4. Re:My favorite code comment not written by me by zardo · · Score: 1
      My comment distribution goes something like this:

      1. 50% come right before functions/methods to explain what they do.
      2. 20% insulting someone else or their code.
      3. 20% the word "TODO".
      4. 5% useful bits of information.
    5. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      5. 5% profit

    6. Re:My favorite code comment not written by me by stevey · · Score: 1

      Actually the perl source code is full of fun comments like the Tolkien quote The road goes ever on..

      It helps lighten the mood when reading it... and the other comments are useful and helpful too.

    7. Re:My favorite code comment not written by me by bjtuna · · Score: 1

      That reminds me of how my cousin once told me he was pretty sure there was a program he wrote at a previous job that, under just the right obscure error condition, will send up a debugging alert box that says 'Dammit'.

    8. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      haha... ...and yet, /* Oh, fuck */ tells you everything you need to know about the code it's commenting on, i.e.:

      - Do not under any circumstances try to read the code below
      - Delete me now
      - Beat original coder upside the head

    9. Re:My favorite code comment not written by me by sconeu · · Score: 1

      1. You only have 95% of your comments
      2. I'd argue that your Item 1 is part of Item 4., assuming the function block comments are accurate.

      --
      General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
    10. Re:My favorite code comment not written by me by e2d2 · · Score: 1

      Horribly written Perl? Say it aint so!

      Christ the Perl geeks have contests to see who's code is the worst! So I never expect much from those ne'r-do -wells.

    11. Re:My favorite code comment not written by me by pzampino · · Score: 1

      I couldn't disagree more. First and foremost, humor is subjective, and what may have been funny to the author of the comment, may not be funny to all readers of said comment. More importantly though, when I'm debugging someone else's code, I'm not in the mood for humorous comments. If I want humor, I'll go watch CaddyShack or Fletch. When I want to solve a code-related problem, I only want information relevant to that goal.

      --
      "If men will not be governed by God, they will be ruled by tyrants." - William Penn
    12. Re:My favorite code comment not written by me by Idealius · · Score: 1

      lol I have a similar thing for my hacks

      my classic is: //Close your eyes, this parts dirty. ..followed by nested if's or switch's, etc.

    13. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      ... as they sifted through their horribly written Perl.
      There's another kind?

    14. Re:My favorite code comment not written by me by javamann · · Score: 1

      Geez, I wouldn't want to work with you. I always sprinkle funny thing in my comments. Kinda like authors that put funny sayings at the beginning of their chapters.

      -Pete

    15. Re:My favorite code comment not written by me by radtea · · Score: 1


      My favourite is:

              x = 5; // here we set x equal to six

      On an unrelated note, despite what some others in this thread have suggested, I think any humour in comments is a Bad Thing. Some poor maintenance coder, whose first language may not be English and who may not have the cultural background to appreciate the humour, could have a very hard time sorting out the humour from the important stuff.

      This can also be an issue with slang, which changes over time. The slang that a crusty old bastard like me is likely to use will be incomprehensible to a 20-something new hire, and her slang would be equally incomprehensible to me.

      So dull, characterless, direct, literal, professional comments are the only way to go.

      --
      Blasphemy is a human right. Blasphemophobia kills.
    16. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      How about when you want to get the stick out of your ass?

    17. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      Hey! You aren't my cousin!

    18. Re:My favorite code comment not written by me by jimicus · · Score: 1

      20% insulting someone else or their code.

      Which works just fine until you find that the person you've insulted er... wrote most of the program you're commenting from scratch when the company was a tenth of its current size, is still working at the same company and is a senior software architect in the same reporting line as you.

    19. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      In the source code for a major ERP vendor, I have seen comments from thier developers like:

      HUH?!
      what does this do?
      How does this work?

      This is in released code for a system for which they charge customers big bucks.

    20. Re:My favorite code comment not written by me by GodGell · · Score: 1

      humor in comments is definietly not a bad thing. general political/cultural humor neither, as long as it doesn't refer to things not "visible" from other countries through the media or something.

      i guess a good example to this would be:
      bad: // tamas gaspar miklos can suck my dick // who the fuck from /* wee, i'm commenting a comment */ another country would know who TGM is?

      good: // monica lewinsky can suck my dick /* monica lewinsky is much more likely to be well-known in other countries, she has shown the word that doing some nice mo
      ves on a famous dick makes you famous, too. */

      anyway, i usually don't put much comments in my code, especially not in code like my server which i most likely won't release to other people. but in open source code i add some general comments where things are not obvious.
      read the source code, too. :) // here we explain why too much comments are bad

      /* oh, fuck */

      --
      [SHOW SOME LENIENCY TOWARDS ... I mean, FUCK BETA] Eat. Survive. Reproduce. GOTO 10
    21. Re:My favorite code comment not written by me by Xyrus · · Score: 1

      "I have no idea why the developers put such comments there other than to entertain themselves as they sifted through their horribly written Perl."

      Is there any other way to write Perl? ;)

      ~X~

      --
      ~X~
    22. Re:My favorite code comment not written by me by jc42 · · Score: 1

      Ah, but the Obfuscated Perl Contest merely illustrates that we perl hackers have achieved the level of enlightenment of our masters, the C programmers.

      One might even argue that the perl crowd has surpassed their teachers. After all, when the Obfuscated Perl Contest was first organized, they realized that it was the initial element in a list, and named it the Zeroeth Annual Obfuscated Perl Contest. In this manner, they avoided the logical mistake of the ioccc crowd, whose contests are numbered starting at 1.

      There are some mistakes that, once made, can never be corrected. This was a valuable lesson in the need for analysis and design before one sets forth on a task.

      I do believe that the Obfuscated C programmers are duly proud of their offspring.

      However, I don't believe that any self-respecing C or perl programmer would feel insulted if called a "ne'r-do -well", not even if you had spelled it correctly.

      --
      Those who do study history are doomed to stand helplessly by while everyone else repeats it.
    23. Re:My favorite code comment not written by me by dooglio · · Score: 1
      I worked on a project years and years ago where we had many retail stores installed with a network of cash registers tied to a server in the back room.

      In the polling code on the server, there was a case in a switch statement which would never ever get executed. There was a comment for the case statement:
      /* this should never happen*/
      and the actual code for the case statement sent the following text to the registers: "IT HAPPENED".

      The funny thing is, after a strange set of power fluctuations at one site, we got a support call where the guy on the other end said, "It says 'IT HAPPENED' on each of our registers."

      Well, we laughed about it anyway.

    24. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      Some years ago I was perusing the Windows 3.1 source code (don't ask cause I won't tell) and came across this gem:

      mov ax,3 ; I don't know why 3 works, but it does

      Explains a lot, eh?

    25. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      Holy crap, I am laughing really hard.

    26. Re:My favorite code comment not written by me by zardo · · Score: 1

      Not here, I work for a smaller company, I'm the only computer guy besides the boss. People come and go over the years, some better than others. I'm training a new guy right now.

    27. Re:My favorite code comment not written by me by AaronLawrence · · Score: 1

      The only risk is that if the comedy is a bit sarcastic or whatever, someone later reading can think it's serious and get tied in knots.
      So they better be obvious jokes, I guess :)

      --
      For every expert, there is an equal and opposite expert. - Arthur C. Clarke
    28. Re:My favorite code comment not written by me by Pete · · Score: 1
      pzampino:
      First and foremost, humor is subjective,
      [ ... ]
      If I want humor, I'll go watch CaddyShack or Fletch.

      Humour subjective. Right. Gotcha. :)

      I know that in general I want to read comments that actually have something to do with the code. But when talking about humorous comments, I generally see them as little throwaway one- or two-liners sparsely scattered through the code. And virtually all the funny comments I've encountered are funny only in context - that is, they're funny only to another programmer who has a rough understanding of the code being commented.

      I'm guessing you've had a bad encounter with a programmer that thought they were funny when they really weren't. If so, you have my sympathies. But really, it's extremely cool when you're plowing through a large chunk of otherwise fairly dull code, and you run across an innocuous bit of dry wit that catches you off guard and makes you laugh.

      Especially when it's the kind of humour that only another programmer would get. It feels like the original programmer is sharing a grin with you, through a window of months or years since the code was written. It's really quite cool.

    29. Re:My favorite code comment not written by me by Pete · · Score: 1
      Excellent, that's the way it should be done. Glad to find someone that shares my point of view :).

      It's probably because you have such a cool name.

    30. Re:My favorite code comment not written by me by Anonymous Coward · · Score: 0

      Especially when it's the kind of humour that only another programmer would get. It feels like the original programmer is sharing a grin with you, through a window of months or years since the code was written. It's really quite cool.

      No, it's a waste of time.

      I'm not being paid to be distracted by meaningless drivel; I'm being paid to work.

      If the original programmer had the same work ethic, perhaps he'ld still be with the company, instead of leaving behind his messes for others to clean up. Wasting his own time writing jokes on work time is bad enough; wasting every single code maintainer's time on his idea of humour is criminal.

      The parent is right; work is not a game, and if you want jokes, write them on your own time.

      Don't chew up my deadlines by writing comedy instead of writing proper comments and documentation. Your time might not matter to you; but mine matters to me. Don't waste my time and mindspace on your drivel; I've got enough to do while tracking down all the bugs you left!

  4. Don't do it! by Anonymous Coward · · Score: 0, Funny

    Don't EVER comment your code if you work for a company. That's a sure fire way to lose your job! If you don't comment your code then you are the only person who can understand it, making you indispensible.

    In summary, DON'T COMMENT!

    1. Re:Don't do it! by BaudKarma · · Score: 1

      Indispensible, and pretty much unpromotable.

      Me, I hope to be able to pass this project on to some junior dweeb in a year or so, and move on to something New and Exciting.

      --
      It's the land of the brave, and the home of the free
      Where the less you know, the better off you'll be.
    2. Re:Don't do it! by treerex · · Score: 2, Insightful

      Don't EVER comment your code if you work for a company. That's a sure fire way to lose your job! If you don't comment your code then you are the only person who can understand it, making you indispensible.

      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.

    3. Re:Don't do it! by 1nt3lx · · Score: 3, Informative

      This works quite well, but there are some consequences for this action:

      1. You are likely to be passed by on promotions because self inflicted developer dependence for this application.
      2. You will have to figure it out later, after you've forgotten what all that magic gobly-gook does.

      magic gobly-gook: effective, efficient, and incredibly dense code produced wilst 'in the zone'

    4. Re:Don't do it! by Anonymous Coward · · Score: 0

      That 'whoosing' noise you hear is the displacement caused by the joke flying directly overhead.

    5. Re:Don't do it! by halber_mensch · · Score: 2, Interesting
      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.

      --
      perl -e "eval pack(q{H*},join q{},qw{70 72696e74207061636b28717b482a7d2c717b343 637323635363534323533343430617d293b})"
    6. Re:Don't do it! by Anonymous Coward · · Score: 0

      That 'raspberry' noise you hear is because you've never had to pick up behind someone who didn't think it was a joke either and actually implemented the practise. And if you think it doesn't happen in the real world, you're either incredibly naive or have never worked as a programmer.

    7. Re:Don't do it! by Daniel_Staal · · Score: 1
      magic gobly-gook: effective, efficient, and incredibly dense code produced wilst 'in the zone'

      Not to be confused with regular gobly-gook: ineffective, inefficient, and incredibly dense code produced wilst 'in the zone'.

      Getting the two mixed up has caused all kinds of problems...

      --
      'Sensible' is a curse word.
    8. Re:Don't do it! by BigZaphod · · Score: 1

      You could always maintain 2 source trees. A secret one with comments so you can get your job done, and another auto-gened one which runs through some tools to strip all the comments. That's the code you show everyone and check into the source repository. :-)

    9. Re:Don't do it! by PureCreditor · · Score: 1

      Companies are willing to hire outrageously expensive consultants to re-invent existing code if it's too hard to update or maintain, and they have absolutely no reason to keep people around just to maintain obscure code.

    10. Re:Don't do it! by treerex · · Score: 1

      And the whooshing noise *you* hear is the displacement caused by the (partial) sarcasm of my response. And, as the other reply points out, this happens all to often.

  5. it was hard to write by hsmith · · Score: 1

    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

    1. Re:it was hard to write by Rei · · Score: 1

      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++) {

      --
      "It felt almost as good as stealing cars from grandma." -- Margaret Thatcher, probably.
    2. Re:it was hard to write by lgw · · Score: 1

      Code like that is great for job security, though. No comments makes you look unprofessional - good looking code that no one else can maintain is an art. Back in the days when everyone had the same terminal and therefore the same font, you could have great fun with miking 'l's and '1's in variable names, or 'm's and 'rn's, or other fiendish tricks.

      These days, of course, who wants to be stuck maintaining some peice of code you wrote 10 years ago? Unless it's the payroll system, of course, as that's the holy grail of job security. ;)

      --
      Socialism: a lie told by totalitarians and believed by fools.
    3. Re:it was hard to write by Anonymous Coward · · Score: 0

      Why stop there? Why not just code everything in morse?

    4. Re:it was hard to write by Anonymous Coward · · Score: 0
      Methinks that perhaps you meant to write:
      for(teamCount = 0; teamCount < defender.team.length; ++teamCount) {
      not that i dont relish in the sheer absurdity of of your method or anything...
    5. Re:it was hard to write by Rei · · Score: 1

      Not that I don't relish in your correction of correct code, but ++teamCount is equivalent to teamCount++ in the current location because, unless teamCount isn't a primative, given the return value is ignored, the exact same binary output will be produced. Even if, strangely, teamCount is not a primative, the worst that will happen (assuming non-obfuscated, correct code) is slower execution.

      Remember: x++ and ++x, when implemented by the book, are to perform the same function, but return different return values (either the former value of x or the latter value of x). When the return value is ignored, they perform identically for primatives, and for most cases with good optimization enabled, perform the same for objects.

      --
      "It felt almost as good as stealing cars from grandma." -- Margaret Thatcher, probably.
  6. I wish by Anonymous Coward · · Score: 0

    the guy who wrote the ldap authentication module for drupal read this because its proving to be a beotch to modify. I know comments suck (speaking as a developer) but god knows their necessary, especially when working on and debugging someone elses code.

  7. Gotta say it by modi123 · · Score: 2, Funny

    /* no */

    1. Re:Gotta say it by Anonymous Coward · · Score: 0

      No again.  That should be

      /* no
         no
         no
         What part of no didn't you understand */

      and

      // no

    2. Re:Gotta say it by modi123 · · Score: 1

      Or my email sig /* Halley */ Halley's Comment *smirk*

  8. Next article... by Anonymous Coward · · Score: 0

    We come here to get away from work, not to learn how to do it properly. Plus, isn't this a dupe?

    1. Re:Next article... by Taevin · · Score: 1

      Slashdot dupe checking (now with comments!)

      /* hahaha... */
      bool IsDuplicate()
      {
          /* ...hahahahaha... */
          return false;
      }

  9. Example by dduardo · · Score: 3, Funny

    /*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"*/ }

    1. Re:Example by Metasquares · · Score: 1

      That's actually an example of something TFA says explicitly not to do - it's the "Don't insult people's intelligence" tip.

      All in all, I found that the article's guidelines matched pretty closely to my own commenting style. I second the author's recommendations.

    2. Re:Example by sykjoke · · Score: 1

      Jesus, you write comments like my old employer wanted me to!!, he didn't like comments like.... /* display hello world 5 times*/
      for( int x=1; x5; x++ ) {
              printf("Hello World\n");
      }

    3. Re:Example by JustOK · · Score: 1

      But, where does the function end??? And what's this LOOP you talk of? Also, although we don't know what you're doing here, the company standard is to use i.

      --
      rewriting history since 2109
    4. Re:Example by John+Newman · · Score: 1
      /* display hello world 5 times*/
      If the point is to just print 5 Hello World's, yours is a better way to comment, isn't it? Comments shouldn't explain the language, just get the point across as to what a block of code does - so it can be understood by someone who knows the language, or re-implemented in a different language. Your old boss's way is unhelpfully complex and obfuscating. In short, I think your old boss was a jerk. ;)
    5. Re:Example by sykjoke · · Score: 1

      I think your old boss was a jerk. ;)

      hence the old in the boss bit.

    6. Re:Example by Anonymous Coward · · Score: 0

      That's okay. It's to be expected that comments often don't reflect what the code actually does.

      Fix the code or fix the comment?

      I'll fix the comment. /*This loops forever, unless x5 is 0, in which case it does nothing.*/

  10. comments by jchawk · · Score: 1

    # does something important
    code

    code

    code

    #not sure what, but it looks important.

    1. Re:comments by kryten_nl · · Score: 1

      Ah, YOU where the one that copied UNIX code into Linux....

      --
      For the perfect anti-Unix, write an OS that thinks it knows what you're doing better than you do and let it be wrong.
  11. The ParticleTree... by frank_adrian314159 · · Score: 1

    ... seems to have been turned into sawdust...

    --
    That is all.
  12. Been said many times before... by Anonymous Coward · · Score: 0

    If it's hard to write, it should be hard to understand... and if it's easy to write, then it obviously doesn't need commenting.
    gosh.

  13. var names by rockytriton · · Score: 3, Insightful

    My best strategy is intelligent variable names and clean simple code. -- http://www.dreamsyssoft.com

    1. Re:var names by nkh · · Score: 1

      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.

    2. Re:var names by Anonymous Coward · · Score: 0
  14. human readable by cerelib · · Score: 1

    If a non-programmer or somebody with no real knowledge of the project can look at a piece of code and understand what it generally does and how, then you have good comments. But good comments are not always necessary, sometimes subpar will do. Next question.

    1. Re:human readable by superyanthrax · · Score: 1

      I disagree, good comments are always necessary. Working in a CS research group has allowed me to see how important commenting code actually is. We may think we're all tough and we can read any program from scratch, give yourself a 2000 line program you've never seen before and you'll change your tune. It will take you far too much time and effort to read that program and figure out what it's doing if there are no comments clearly telling you. One of the most important purposes of writing code is so it can be reused, and if you don't write good comments it will be very hard to reuse.

    2. Re:human readable by Conspiracy_Of_Doves · · Score: 1

      If a non-programmer or somebody with no real knowledge of the project can look at a piece of code and understand what it generally does and how, then you have good comments.

      Then good comments are... what? Undesirable?

    3. Re:human readable by naarok · · Score: 1

      I'll agree (mostly) with the what, but not the how.

      A non-programmer should be able to determine the what, but the what should come as much from the naming choices as from the comments.

      If your comments are explaining how the language works to the point that a non-programmer can understand it. You've gone too far with your comments. Long before this point, the actual code that programmers will need to maintain will have become obscured by the comments and you will have made the code harder to maintain.

      In general, the primary purposes of comments is for maintenance (either by someone else in a months time, or by you in a years time).

    4. Re:human readable by Anonymous Coward · · Score: 0

      ..and before you know it, they've hired a cheaper programmer.

    5. Re:human readable by jersey_emt · · Score: 1

      I agree, but a 2,000 line program is a *very tiny* one that would (in most cases) be easy to parse through as long as it has good form (proper indenting, meaningful variable names, etc.).

      --
      My spoon is too big.
    6. Re:human readable by cerelib · · Score: 1

      the difference of the what and how is needed. In the case of C style languages, the what would be the general comments for a function that explains what the function is supposed to accomplish. The how is more of the internal function comments explaining the process that is being used to accomplish the task.

    7. Re:human readable by cerelib · · Score: 1

      No, just not always necessary. If you are writing production level software that is aimed at being a long term product then good code commenting is important. If you are writing small utility programs, small scripts, or idea prototypes then you should not worry about having good comments when subpar will do. But some form of comments are always good to have.

    8. Re:human readable by gardyloo · · Score: 1

      But good comments are not always necessary, sometimes subpar will do. Next question.

          Wait -- we're supposed to be talking about code, not Slashdot.

    9. Re:human readable by mOdQuArK! · · Score: 1
      Working in a CS research group has allowed me to see how important commenting code actually is.

      Working in several corporate software development environment has shown me how _BAD_ commenting can fubar a development process beyond belief. You've got some people spending hours of otherwise-productive time mindlessly writing 3-page header comments for every single little utility function to satisfy some corporate "commenting" policy, which end up being out-of-date a few days later. If you're lucky, the out-of-date information will just be slightly confusing - if you're really unlucky, the comment will be so misleading it will introduce fundamental misunderstandings into the development/design process.

      If you've got to rely on comments to understand code, then either the code is really complicated, or you or the coder are incompetent. Good software should use the minimum comments necessary to explain how things work/how to use things to a competent reader, keep them up to date, and not much more.

      One of the most important purposes of writing code is so it can be reused, and if you don't write good comments it will be very hard to reuse.

      No, the best way to make sure your code is easy to reuse is to define a simple interface with easy-to-understand usage rules. If you've got that, then you'll be able to describe the interface to a competent programmer with simple documentation.

    10. Re:human readable by naarok · · Score: 1

      Fair point, I was reading the "how" differently.

    11. Re:human readable by ucahg · · Score: 1

      Readable code is important, but I think equally important is readable filenames. I mean how many times have you downloaded the source to a program only to not know what you were looking at? Clear, self-explanatory filenames go a long way.

  15. Terse comments. by Anonymous Coward · · Score: 0

    Looks like some MUMPS programmers should read this article.

  16. Practice what you preach by ChrisF79 · · Score: 5, Funny

    I viewed the source on the site and nothing was commented :)

    --
    Finance tutorials and more! Understandfinance
    1. Re:Practice what you preach by pinchhazard · · Score: 1

      I viewed the source on the site and nothing was commented :)

      Perhaps their server preprocesses the page to remove comments.

      --
      Do you love freedom??? Do you love freedom!!! DO YOU LOVE FREEDOM!!!!!!!!
  17. Comments are more important than Code? by jetkust · · Score: 4, Funny

    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.

    1. Re:Comments are more important than Code? by NialScorva · · Score: 4, Funny

      At least you had no compile errors or core dumps, and I bet you didn't have any exploitable vulnerabilities either.

    2. Re:Comments are more important than Code? by VanWEric · · Score: 1

      But it compiled and ran REALLY REALLY fast!

      --
      www.olin.edu
    3. Re:Comments are more important than Code? by agent0range_ · · Score: 1

      I bet it compiled quickly, though.

    4. Re:Comments are more important than Code? by Not_Wiggins · · Score: 4, Interesting

      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.

      --
      Diplomacy is the art of saying, "Nice doggie!" until you can find a rock.
    5. Re:Comments are more important than Code? by Anonymous Coward · · Score: 0

      I once found a bug in the Oracle Pro*C compiler that would cause the _compiler_ to core dump when I changed the contents of a comment.

      Turned out that the compiler had some sort of buffer-overflow problem that a particular value in a comment, near a particular piece of code, would trigger. Dang weird. I remember showing people how I could delete a single character from a comment and the code would compile and work fine.

    6. Re:Comments are more important than Code? by pilgrim23 · · Score: 1

      Anny programmer who thinks the code is more important then the content.... has never been out on a date....

      --
      - Minutus cantorum, minutus balorum, minutus carborata descendum pantorum.
    7. Re:Comments are more important than Code? by Lord+Ender · · Score: 1

      That isn't really bad advice. FIRST you should write all your code in comments, then you should go through and fill in the code under the comments. Anything else and you aren't properly engineering your code.

      --
      A slashdotter who didn't build his own computer is like a Jedi who didn't build his own lightsaber.
    8. Re:Comments are more important than Code? by Anonymous Coward · · Score: 0

      yes, such is COBOL.

    9. Re:Comments are more important than Code? by pzampino · · Score: 1

      The problem with this is that your code can evolve significantly from the time you write those initial comments to the time the code is functional. So, if you're going to take this approach, you better make sure that your comments change with your code. The only thing worse than no comments, is incorrect comments.

      --
      "If men will not be governed by God, they will be ruled by tyrants." - William Penn
    10. Re:Comments are more important than Code? by WinterSolstice · · Score: 1

      That's almost exactly what I do, too. My comments here are kinda flip, but in real life they are quite descriptive

      I'll write this example in perl, just for fun.

      # This sub will check the user input for some value
      # I need and do something with it
      sub Check_Input(
              foreach ( @_ ){
                      #take argument that was passed and compare it to something else
              }
      }

      etc.

      I find that if I describe each step, then update the comments once I have gotten it to work that I am able to easily maintain code I wrote years ago.

      I also use two comment styles. I use // (or #// in perl) for "temp" or debug comments, and /* (or #/* in perl) for real comments. If I want to figure out what I was debugging, I just hop to the correct comment style.

      -WS

      --
      An operating system should be like a light switch... simple, effective, easy to use, and designed for everyone.
    11. Re:Comments are more important than Code? by Tooky · · Score: 1

      The whole Test Driven Development idea takes this a step further. Instead of thinking about what you want to code and writing it as pseudo-code, you write some code that will test it once its written. Then as soon as you've written you can make sure that it does what you intended it to do, plus you've got a runnable specification to go with it. Not only does this help protect you from introducing bugs at a later date, it explains fairly well what your code does, and HOW you intended it to be used.

    12. Re:Comments are more important than Code? by triffidsting · · Score: 1

      Not to mention that it probably performed excellently...

      --
      Non, je ne veux pas coucher avec toi ce soir.
    13. Re:Comments are more important than Code? by RedWizzard · · Score: 1
      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."
      The danger of this approach is that you have to be careful not to end up with comments which just replicate what the code says (eg. width++; // increment the width). With a high level language there usually isn't a great deal of difference between psuedo code and actual implementation.
    14. Re:Comments are more important than Code? by Not_Wiggins · · Score: 1

      The danger of this approach is that you have to be careful not to end up with comments which just replicate what the code says (eg. width++; // increment the width).

      Perhaps I should have clarified my use of "pseudo code" better, as I didn't mean the alternative/language-neutral way of writing code(ie, a=open file("blah"); for each(read(a)){ ; } ). With the way I write my pre-coding comments, I find it very difficult to fall into the trap you've (correctly) outlined. An example of the way I comment might look like something below:

      // Retrieve all the users that have a balance from the database

      // For each user, check to see if the balance is positive

      // If the balance is negative, then we need to send them a letter telling them to get their act together


      In this way, I'm documenting what I want to get done and why. You're point is valid in that if I had written true pseudo-code, it would be pointless for the comments.

      --
      Diplomacy is the art of saying, "Nice doggie!" until you can find a rock.
  18. comments? by lucabrasi999 · · Score: 1

    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.

    1. Re:comments? by methos1125 · · Score: 1

      Unfortuantely not adding comments doesn't add to job security, just makes your code all the more disposable. At least after they can your butt you'll have something that connects your work to the company when you add comments for the next developer to follow and save. No comments will simply cause the next developer in line to do a block delete and rewrite.

    2. Re:comments? by lucabrasi999 · · Score: 1

      I was being sarcastic. If you review the rest of my original post, you will note that I said "we all need to comment" (or words to that effect). Next time, I'll remember to include "sarcasm" tags.

    3. Re:comments? by dptalia · · Score: 1

      The first time you come across important, but undocumented code you hire two guys to learn is and document it. You do the same thing with anyone who is the only person who knows whatever. Never be dependant on one person's knowledge.

      --
      Genius is one percent inspiration and 99 percent perspiration, which is why engineers sometimes smell really bad.
  19. TODO by mccalli · · Score: 1

    /* TODO: Flesh out comment here */

    1. Re:TODO by networkBoy · · Score: 1

      //Lovely.

      --
      whois gawk date unzip strip find touch finger mount join nice man top fsck grep eject more yes exit umount sleep dump
  20. Don't comment by i.r.id10t · · Score: 5, Funny

    Don't comment at all, and just run it thru The Commentator!

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

    --
    Don't blame me, I voted for Kodos
    1. Re:Don't comment by Anonymous Coward · · Score: 0

      Too bad this is not a real program... I would love to have this as an aid. :)

    2. Re:Don't comment by Anonymous Coward · · Score: 0

      You know this could actually turn into a project. Remember Parrot?

    3. Re:Don't comment by Stiletto · · Score: 1


      HAHA I stopped at:

      wicked refactorings

      It's hard to take something seriously when they use the word "refactoring".

  21. Successful strategy by koh · · Score: 1

    /*
    * FIXME - Should handle slashdotting better.
    */

    --
    Karma cannot be described by words alone.
  22. How much do I comment? by Anonymous Coward · · Score: 0

    I/* singular pronoun */ try/* verb */ to/* ??? */ comment/* yeah right */ as/* ??? */ little/* really, I do */ as/* ??? */ possible/* probably could have commented per letter if I wanted this comment be funny */

    1. Re:How much do I comment? by Reverend528 · · Score: 1
      You can't comment a statement in its own language unless you intend to comment the comments as well. And that always ends in recursion:

      I /* singular /* adjective /* noun /* noun /* noun /* noun /* noun /* noun ....

  23. I was skeptical at first regarding the topic by Anonymous Coward · · Score: 5, Insightful

    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()...

    1. Re:I was skeptical at first regarding the topic by lgw · · Score: 2, Insightful

      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 documentation it can get).

      --
      Socialism: a lie told by totalitarians and believed by fools.
    2. Re:I was skeptical at first regarding the topic by aled · · Score: 1

      I keep telling my code to document itself but it doesn't. What I'm doing wrong? Help!

      --

      "I think this line is mostly filler"
    3. Re:I was skeptical at first regarding the topic by Tooky · · Score: 1

      This is exactly what comments are for!

      Self documenting code (e.g. well named variables) to explain the what, comments to explain the WHY.

    4. Re:I was skeptical at first regarding the topic by lgw · · Score: 1

      That's the most concise statement of this truth I've seen - nice!

      --
      Socialism: a lie told by totalitarians and believed by fools.
  24. Commenting by Hamster+Of+Death · · Score: 4, Insightful

    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*

    1. Re:Commenting by jacen_sunstrider · · Score: 1

      I was migrating some code between assignments of my Assembler class at school, and I was able to basically dump an entire routine from one to the other with very slight changes, mostly to the label names.

      Upon recieving it back after it was graded, I was reminded by the TA that my comments, which were great the first time around (referring to musical instrument sales) were not as apt when referring to kegs of beer sales (one of the course instructors was an old drunk). Since, I've always tried to check through my comments, but it's always more of an afterthought.

      As for your first point, I think that's a matter of preference, equivalent to someone learning better by listening or taking notes, etc. Our neighbor swears by fleshing out problems with comments first, but myself and my roommate (probably dirtier programmers) have far more success commenting after we have some reasonable semblance of a program to run. I think it's because of the openness; we're not limiting ourselves by only thinking beforehand (that's really more of an excuse), and are able to think on the fly, most of the time typing faster than we can think (which resolves to forgetting a few lines of code...really, who needs an else{} statement?).

    2. Re:Commenting by Anonymous Coward · · Score: 0

      Absolutely! You beat me too it. Before any coding takes place, you should always design a "procedure" with methodical steps written in comments _first_. You later fill in the actual code beneath each comment. This is very akin to early flowchart design - a lost art.

      * The real advantage(s) to commenting before coding is:

      1. Over time, you save time - with a little practice, you can design an entire module/class with nothing but comments. Your logic is preserved, it's much much more readable, and you fill in the "blanks" with actual code later.

      2. You can _continue_ the methodical steps in logic to complete a task, without breaking that train of thought by stopping to code (by filling in the "blanks").

      3. Someone else can continue your unfinished work, without little intervention on your part!

      4. Over time, if you pratice "comment b4 code", you'll find that you: a) no longer need to _add_ comments, b) commenting is not a chore, but an aid, and c) future revisions require very little "re-familiarization" with old code, as you insert new code.

    3. Re:Commenting by bmwm3nut · · Score: 3, Insightful

      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.

    4. Re:Commenting by truckaxle · · Score: 2, Insightful

      Oh hey I have maintained code written with this technique

      Sure and when you get around to actually writing your code and you find out that it doesn't quite work as easily as you thought it should and you deviate from your comments then rarely does the comments get updated. After a few rounds of revision and testing the comments are a mere artifact and document how you original thought it should work.

    5. Re:Commenting by Beek · · Score: 1

      You get the same benefits doing test-first development... But on top of that, you *must* update the tests when you update the code (unless the code change is trivial).

    6. Re: Commenting by Craig+Ringer · · Score: 1

      I find this an absolutely critical tool when designing and writing new classes. I don't usually write each method that way, but the overall class structure, the methods, and the members are all written as stubs and commented before any "real" code goes in.

      I can't seem to "think it out on paper" but I *can* think it out in words in a header file, and massage that into the shape I want before starting any "real" code.

    7. Re:Commenting by ghostunit · · Score: 1

      This is only true when attempting to make software using the old plan-then-build approach and does not work with evolutionary-type programming (the style oftenly associated with Lisp, visit www.paulgraham.com and check his OnLisp book for more info).

      The assumption is that you have a clear idea of the program you want, then design it perfectly and finally code it. In reality, rarely ever will you know everything the program should do and even if you do, you may need to experiment with several algorithmical/arquitectural approaches. In such cases it's better to work fast building prototypes and tests to understand what is it you need than to comment code or attempting to arrive at a perfect solution.

    8. Re:Commenting by cpeterso · · Score: 1


      Someone should write a domain-specific language compiler for comments. Given comments as input, it will generate your code from your comments.

    9. Re:Commenting by Anonymous Coward · · Score: 0

      In that case the comments usually go something like

      # solve problem X here

      and then get more specific as I figure out exactly what has to be done. At the very least, it helps me figure out how the solution to 'problem x' fits into the overall program. And, often, several 'solve problem x' comments will get inserted after I've actually begun the code. It just helps me stay organized and helps document the program flow for later.

    10. Re:Commenting by Anonymous Coward · · Score: 0

      Write the comments first, then add the code.

      A terrible waste! I follow a repeating cycle of:

      1) Write a minimum of design, write code.
      2) Review and refactor, manual/unit/regression tests.
      3) Update your design documents... and release a build
      4) communicate with coworkers, end users, gurus
      5) go to 1

      Now you have code that needs no or less comments, but most of all the project is maintainable and ready for improvements. Do not write something to throw away (like comments or sensless reports), instead make things right in the beginning. Strangly, growing software is not limited by programming skills or hardware shortcomings... but by ancient software procedures, insuficient languages and tools, lack of team cooperation and most of all people who code rather than design. /Mark

      PS: Oh yes, I haven't read the original article before I posted this :)

  25. really being stressed in schools by StarvingSE · · Score: 3, Informative

    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.

    --
    I got nothin'
    1. Re:really being stressed in schools by Conspiracy_Of_Doves · · Score: 1

      My old C++ prof would mark down for too many comments or unneccessary comments.

    2. Re:really being stressed in schools by djmurdoch · · Score: 1

      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.

    3. Re:really being stressed in schools by j-tull · · Score: 2, Informative

      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 appropriateness of their comments will be any better than what we see today.

    4. Re:really being stressed in schools by shic · · Score: 1

      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.

    5. Re:really being stressed in schools by Nytewynd · · Score: 1

      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.

      --
      /. ++
    6. Re:really being stressed in schools by StarvingSE · · Score: 1

      In my classes at least, the prof's aren't just saying "write comments or you get -10 pointes." They actually give us an outline of what a good comment block for a function would look like and what it should include. Comments don't have to be fine literature, they just need to provide some concise important info that helps a reader understand the code. Like I said, I don't know how other classes are taught, but this is how mine are.

      --
      I got nothin'
    7. Re:really being stressed in schools by Anonymous Coward · · Score: 0

      I got my revenge. I wrote comments in lousy spanish (no, I can't write spanish well).

    8. Re:really being stressed in schools by Anonymous Coward · · Score: 0

      While I was going through school. We were not only were we marked down about commenting. But how we were commenting. /* This is the Doomsday Algorithm */

      Doesn't cut it. That would not do for the Object Oriented Design that is stressed even more. After a while the projects we were working in classes made it very clear, even for the people who wrote the code. That there is no way possible to get it right in the time frames we were given if we did not follow good coding, design, and commenting procedures.

      You don't need to be an author to comment. All you need is a brief description, what goes into the function (because everything is an object) and what goes out of it.

      The job I have is because someone did not comment their code. Those people are gone. I have my job because they didn't comment their code and when it came to build off what they built they couldn't get it done in time. Oops what job security. You mean a project could possible get so large you can not contain it all in your head? Imagine that.

      I followed my simple procedures I have learned in school. Now, I have a set of code in classes and libraries that are tools I can always use. I have comments so that if I forget how to use one of the functions/objects that I can simply look at it and get it right. Now, they my bosses hand me a project thinking it would take me a month, and it takes me a week. Life is much easier now.

      So please, don't comment your code. The kids coming out of school today need your jobs.

    9. Re:really being stressed in schools by Politburo · · Score: 1

      Yes, but is the boss going to mark you down for not including comments? It's much more likely that they're much more interested in simply having something working on-time, comments or no.

    10. Re:really being stressed in schools by murdocj · · Score: 1
      My old C++ prof would mark down for too many comments or unneccessary comments.

      Bet he didn't have to do that too often

  26. No by rbarreira · · Score: 5, Funny

    No, that first one should be something like:

    This loop starts at 1, and to 5 it counts. It doesn't count to 6, nor it does count to 8. It does not count to 3 or 4, except in passage to 5. When it reaches number 5, the fifth number...

    --

    The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
    1. Re:No by Conspiracy_Of_Doves · · Score: 1

      9 is right out

    2. Re:No by lboxman · · Score: 2, Funny

      That's only appropriate if you're documenting python code...

      --
      Regexes are like cocaine. The first hit is pretty good, but afterwards you try to use them to solve all your problems.
    3. Re:No by legirons · · Score: 3, Funny
      Not in the real world... more like:
      //----------
      // ReadSalaryData - reads table of salary values from database
      // Parameters:
      // - DB, database handle
      // - Data, pointer to list
      // Returns: Success
      //---------
      void DeleteUsername(char *Name)
      {
      ...
    4. Re:No by rbarreira · · Score: 1

      You've never seen this, have you?

      Funny anyway ;)

      --

      The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
  27. What's So Hard About Comments... by __aaclcg7560 · · Score: 2, Interesting

    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.

    1. Re:What's So Hard About Comments... by pete6677 · · Score: 1

      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 textbook. Needless to say the only things I learned in that class were what I had taught myself.

    2. Re:What's So Hard About Comments... by awol · · Score: 1

      It's not a case of commenting being hard. My issue with comments is that after a while, if not at the beginning, they can only ever be wrong. That is, as time goes by the likelihood of a comment being wrong increases unacceptably and one thing worse than no comments is wrong comments.

      Our policy is to write formally simple code with comments reserved for the occasions when the code is bizarro, for performance or becuase it is doing something tricky. Basically to stop people from "fixing" the non-conformant code.

      We also completely document the functions in shared library headers to provide a doxygened contract for library users.

      Other than that, nada.

      --
      "The first thing to do when you find yourself in a hole is stop digging."
  28. Successful Strategies for crashing your server by Toba82 · · Score: 1

    1) Write article 2) Post on your website 3) Submit to slashdot 4) ... 5) PROFIT!!!111!!!

    --
    I pretend to know more than I really do by mooching off google and wikipedia.
  29. Don't tab inline comments! by Dlugar · · Score: 1
    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
    --
    Computer Go: Writing Software to Play the Ancient Game of Go
    1. Re:Don't tab inline comments! by I8TheWorm · · Score: 1

      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 :)

      --
      Saying Android is a family of phones is akin to saying Linux is a family of PCs.
    2. Re:Don't tab inline comments! by Metasquares · · Score: 1

      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.

    3. Re:Don't tab inline comments! by Ricdude · · Score: 1

      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+\

      --
      How's my programming? Call 1-800-DEV-NULL
    4. Re:Don't tab inline comments! by methos1125 · · Score: 1

      Forget IDE's Emacs (Or Xemacs if you prefer) does a wonderful job or tabbifying code to look good on any text editor. I've been using it for 12 years now and swear by it over any other editor no matter which OS I'm working on. Comments are tabbed to the correct place and and are easily visible with syntax highlighting. I've tried using other editors to get stuff done, and keep returning to the good ol' Xemacs. Just my $0.02

    5. Re:Don't tab inline comments! by vrai · · Score: 1
      Eight characters? Indents should be two or four, if you can't see them properly I'd suggest a visit to the opticians.

      As for tabs - there's no place for tabs in source code. Always use spaces. Spaces look the same in any fixed width font on any platform, tabs do not.

      I agree about you with the editors though. Notepad is good for nothing. There are plenty of free alternatives that have an expanded feature set - such as being able to render '\n' as a line-break.

    6. Re:Don't tab inline comments! by Brandybuck · · Score: 1

      Standard tabs are eight spaces. Standard indentation is four spaces. Anyone see the problem?

      This is why I always convert tabs to spaces. It's just polite to other coders. Any decent editor will do this for you automatically. Are bytes so precious that we need to save three of them for every indent?

      --
      Don't blame me, I didn't vote for either of them!
    7. Re:Don't tab inline comments! by Anonymous Coward · · Score: 0

      8 characters might be fine for a language such as C. Have you ever tried to program Java with an 8 character indent? With the lots-of-nesting going on, you'd need either a real-wide-screen, or an extremely slim font.

      You can write "proper code" right? You're not a newbie, or a wannabe faux-programmer, right?

  30. A comment on comments by Jeffrey+Baker · · Score: 5, Insightful
    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.

    1. Re:A comment on comments by Abcd1234 · · Score: 1

      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.

    2. Re:A comment on comments by Anonymous Coward · · Score: 0

      Hey, now. Kids read this site.

    3. Re:A comment on comments by oojah · · Score: 1

      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

      --
      Do you have any better hostages?
    4. Re:A comment on comments by Coryoth · · Score: 1

      As far as JavaDoc goes I like to expand on it with JML. Essentially it's just a matter of adding comments outlining "this is what I intend the function to do" which is always useful to the reader - the bonus is that the comments are also parseable, and allow for extra static checking beyond just type checking.

      Documentation that helps reduce bugs - what more could you ask for?

      (Note that this doesn't eliminate the need for good explanatory comments, it just allows you to get some extra mileage out of some of the comments that you ought to be making anyway)

      Jedidiah.

    5. Re:A comment on comments by wowbagger · · Score: 1
      A-FREAKING-MEN, BROTHER!

      I've said this before, and I shall say it again.

      When I examine your code, I need to know:
      • WHAT your code it intended to do.
      • HOW it will do it
      • WHY it does what it does.


      Doxygen and JavaDoc are good at the HOW, but cannot do the WHAT or WHY.

      To extend your example:

      public void frobWoggleFfloofMoing(String, String, String)

              Frobs the Woggle

      • How does this Frob the Woggle (what algorithm, what limitations are there, how much time will it take, how much memory, is it thread safe)?
      • Why would I *want* to Frob the Woggle?
      • What side effects does Frobbing the Woggle have?
      • (In a reference counted system) Do I need to hold a reference to the Woggle before I Frob it?
      • Do I get the same Woggle back, or do I get a new Woggle of refcount=1?
      • When do I even NEED a Woggle?


      (all these are questions I had when I was trying to grok the low-level RPM API, and which were very poorly documented on the RPM WIKI.)
    6. Re:A comment on comments by 0xABADC0DA · · Score: 1

      Doxygen and javadoc provide a consistent way to document the code inside the source. Sure, you get comments that include no-brainers like "@param size, the size" but even these add some value by reinforcing the comment structure. So when I see code commented with doxygen or javadoc I can skip the step of parsing the documentation format and go straight to what it says. It doesn't sound like much, but when you look at the Java API for instance, all of it follows the same basic format: summary sentence, description, parameters, return value, and those people who have experienced it know it really helps having that consistency.

      Some other posters have diss'd doxygen comments because they say what but now how, or something like that... what does woggle do and when do I need to use it? Is the returned wobble a new one or an old one with ref++. But that's not a problem with doxygen or javadoc, but with the language you are commenting (ie C): there's no good place to comment on these things in-line. In Java the class comment tells you when you would use it and what the basic function the whole thing does. The method comments tell you if it's some shared reference and what algorithm is used (if appropriate). But in C you just have functions... there's no cohesive whole to explain the higher-level ideas you might want to document, so the result is you get comments on individual functions that don't tell you what you want to know and are either too low-level or too high-level.

      But both doxygen and javadoc are the single best way you can document code. Documentation outside the code is for chumps... seriously. If your code is not organized well enough that you can write meaningful comments -- high and low level -- within it then you design sucks. And what's the use of writing great external documentation for a piece of poo?

    7. Re:A comment on comments by Jeffrey+Baker · · Score: 1

      I happen to think that POD is far better for in-line comments than either Javadoc or Doxygen.

    8. Re:A comment on comments by cynicalman · · Score: 1
      C'mon, you can't drop the POD bomb without an explanation. Even tho' javadoc isn't perfect, it makes it easy to document at any level (class/method/field) with a nice reporting tool built into the language.

      While POD can do links and crossreferences, it's doesn't (IFAIK) analyze the symbols of the codebase being documented and ensure that a) they are there, and b) of the right type (Perl doesn't have many types, but it has types ;-) And to call POD's syntax obscure is an insult to obscurity.

      In short, while I love Perl and like POD, if I had to choose a language for my next project based solely on the built-in documentation tools (well, okay, it that was the only criteria I'd quit the job, but this is hypothetical) it would not be Perl.

      --
      the cynicalman - http://blog.geeksmithology.com
    9. Re:A comment on comments by metamatic · · Score: 1

      Most JavaDoc seems to be useless unless you already know how to use the package. It's so frustrating to be faced with a huge list of classes, no overall documentation on what the hell they are supposed to do or how to approach using them, and to know that the people who wrote the code probably think it's documented.

      --
      GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
    10. Re:A comment on comments by jimicus · · Score: 1

      Doxygen and JavaDoc are good at the HOW, but cannot do the WHAT or WHY.

      Don't blame the tool. Doxygen does a great job of the HOW, but it can't reasonably be expected to handle WHAT or WHY unless there are appropriate comments in the code in the first place. If you're going to use a tool like Doxygen or JavaDoc, at least have the good grace to spend 20 minutes learning the correct syntax so you can write useful comments which wind up in the generated documentation.

    11. Re:A comment on comments by Jeffrey+Baker · · Score: 1
      Here's why I think POD is great. Besides lots of generated formats like HTML, POD works just like man: it shows *everything* about the package on one page, where I can read it. And since Perl programmers actually use and enjoy POD, I know there will be sufficient documentation to go from zilch to productivity.

      Take, as an example, the DBI perldoc. It starts with succinct method documentation in the form of examples, in the order they might be used in an actual program. Then it moves on to useful newbie information, and a long, complete-sentence description of the way DBI works. And, since the page is in a linear format, I can find the specific documentation I need with one tap of my little finger on the / key.

      Now let's look at a Javadoc from the Blackberry J2ME software. The front page has all the class names on the left, with terse descriptions in tables on the main page. There is no main description which tells me what the software is, nor how to use it. The packages are described like "The UI API provides a set of features for implementation of user interfaces for MIDP applications", however there is no definition of MIDP here, nor indeed is there any such definition anywhere in the Javadoc tree. Worse, since the javadoc is in a huge tree of separate HTML pages, I can't just quicksearch for the bit I'm looking for. I have to switch to the terminal and use grep -r, or try my luck with Google.

      Here's the description for Class MessageFormat:

      Formats and parses messages in a locale-sensitive manner.

      Locale-specific formatting is passed on to other formatter objects that inserted into this formatter's pattern (this class supports the string, date, and time element formats).

      That's swell. WTF is a formatter object? A pattern? Maybe the superclass will tell us:

      Defines fundamental functionality for classes that format locale-sensitive information.

      Examples of information that might be locale-sensitive are dates, system messages, and numbers.

      Huh, no help there either. I don't know what it is about POD or Javadoc, but most of the time 'perldoc Whatever::Package' gives you some seriously useful documentation, and in my experience nearly any given Javadoc is totally useless to the beginner.

    12. Re:A comment on comments by wowbagger · · Score: 1

      Oh, I agree - no automated "documentation generator" can generate WHY or WHAT - that is a task for the software writer.

      And I will also agree with several people that WHY and WHAT probably don't belong in code comments per se but in proper external documentation.

      But I, like the GGP, have encountered far too many projects that, when confronted with the astonishing lack of documentation, will point proudly to their Doxygen pages and say "Nu-HUH! We do SO have documentation! So THERE!"

    13. Re:A comment on comments by Anonymous Coward · · Score: 0

      There are several things I'd add to JavaDoc.

      1) I just wanna use it comments
      These would be particularly useful in the Swing classes. There are so many methods that I don't want to see. I don't want all the UIDelegates in there. I just want to use the widget as intended.

      2) Parent class methods included inline. Once again, when I a presented with a new class, I want to see what it can do. I'm not interested that it's great-grandparent can do what I want, If THIS class can do it (via inheritence), it should be documented.

      3) Private method docs.
      I should be able to generate a javadoc and use it as a design document. This means that I should be able to see private methods laid out in the same format. Since I am working on the source, I should be able to generate it myself.

      javadoc -showprivate MyClass.java

      1) and 2) could be options selectable from the API html. Hit a button to expand and contract the documentation as the reader sees fit.

    14. Re:A comment on comments by Anonymous Coward · · Score: 0

      For instance, documentation would explain what is a Woggle, and when should it be Frobbed?

      You should find what a Woggle is in the documentation for the Woggle class. You will find a link to it at the bottom of the frobWoggleFfloofMoing documentation in the See Also section.

      You're nearly spot on about the "when should it be Frobbed", but I'd extend that to "why should it be Frobbed".

    15. Re:A comment on comments by cynicalman · · Score: 1
      First off: good answer ;-)

      Second, you aren't contrasting the tool for documentation so much as the person who wrote the documentation. If you were to say that "the community of developers working on CPAN modules is better at documenting than 99% of the developers releasing OS Java software" I would have to agree with you.

      Third: Calling DBI a "package" and equating it with Java packages isn't really fair. A Java package can consist of several related classes, while DBI is just one module out of possibly dozens that may be in a system, and more comparable to a class than a package. You still need a general idea of what you're looking for to even run perldoc.

      Fourth: In javadoc, if you have the documentation up for a single class, getting to any piece of it is still just a touch of the "/" key (if you're in Firefox, other browsers may require something like Ctrl-F)

      There are other things I like about Javadoc, but that has less to do with javadoc itself, and more to do with how people have extended it (you know, Ctrl-Q to see the javadoc for a method in IDEA, or tools like XDoclet, being able to add my own tags and easily write extensions to handle them), and I'm sure you can do the same things with POD.

      In the end, let it be known that I was not interested in defending Javadoc so much as hearing why you like POD.

      --
      the cynicalman - http://blog.geeksmithology.com
    16. Re:A comment on comments by Anonymous Coward · · Score: 0

      Hmm... Lets see how DBI perldoc starts off:

      NAME

      DBI - Database independent interface for Perl

          use DBI;

          @driver_names = DBI->available_drivers;
          @data_sources = DBI->data_sources($driver_name, \%attr);

          $dbh = DBI->connect($data_source, $username, $auth, \%attr);

          $rv = $dbh->do($statement);
          $rv = $dbh->do($statement, \%attr);
          $rv = $dbh->do($statement, \%attr, @bind_values);
          . . .
          The synopsis above only lists the major methods and parameters.

      And that's not totally useless to the beginner??! ROFL.

    17. Re:A comment on comments by brettper · · Score: 1

      That's nothing - half of the online help in Windows is like this too. Tells you the basic obvious stuff you can work out but no details to be had anywhere

    18. Re:A comment on comments by illuvata · · Score: 1

      1) Sounds more like a criticism of Swing, but maybe I misunderstood you

      2) You really want every class to include a description of Objects methods? I think it's better to use @inheritDoc where appropriate, but otherwise not to display inherited comments.

      3) it's -private, not -showprivate

  31. When to comment... by EWIPlayer · · Score: 1

    From the article: "It is a good practice to write comments at the same time (or earlier than) you write your code."
    MSDN on Using Comments Effectively

    Odd that i would want to disagree with MSDN (cough) but I actually find it better to do a massive comment on a file or set of files a day or two after they've reached a milestone. This forces you to go through and ensure you understand it. It also makes it so that you're commenting from "outside" the programmer's headspace a little bit. As well... it let's you see those sections where one would normally write /* Oh Fuck */.

    --
    This sig used to be really funny...
  32. Depends how you measure success by Linus+Torvaalds · · Score: 1

    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.

    1. Re:Depends how you measure success by Punk+Walrus · · Score: 1
      This is true. We caught a "boobytrap" that was commented just like that in VB6 code. The function call was commented like some code "Wizard" in VB6, with [paraphrased] "Standard Windsock routine, please check your installed helpfiles, copyright 1999 Microsoft," and so on. The function was called something like:

      0pen_winsock

      Yeah, with a zero. Real cool, hard to tell if it wasn't for a boneheaded mistake he made when he called it (functions can't start with a number... or something, it's been a while since I did VB6).

  33. The best strategy by 2008 · · Score: 1

    (in emacs, on a .py)

    edit -> select all
    python -> comment out region

    Voila!

    --
    I quit!
  34. How much money is wasted in bad comments? by madscientist003 · · Score: 1

    I would be interested to know if there is some "official" estimate of how much money is wasted as a result of poor commenting practices. It all obviously depends on the size of the code and the number of people who are responsible for maintaing it.

    My personal experience is with one person codes. I was recently in a situation where I was trying to study a code that another person had written and left behind. There was approximately 3000 lines of code with approximately 5 lines of comments. Quite painful, and unnecessarily so.

  35. Best strategy for comments, so far... by Maljin+Jolt · · Score: 1

    Comment out all buggy code, all code written by coworkers and all code written under previous boss. Increses your popularity with current boss.

    --
    There you are, staring at me again.
  36. My commenting habits by TildeMan · · Score: 2, Interesting

    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.

  37. Why I comment code... by Saeed+al-Sahaf · · Score: 4, Interesting

    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).

    --
    "Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
    1. Re:Why I comment code... by fishbowl · · Score: 1

      "I don't know why people (in general) don't like to comment code."

      I always put a boilerplate header in every source file with a copyright and proprietary notice (required by my company's policy), and I also comment everything that's not and extremely obvious implementation of the design as already documented, and certainly, anywhere the implementation diverges from the design. Also, anything that's incomplete, or not implemented as well as I'd like it to be, gets a "TODO" or "FIXME" comment.

      But local variables don't get explained in the comments, and neither do member functions that are already spec'd in the design docs (which they all are.)

      To go any further, I'd need to add 10-30% more time on every source file, which is not an option given the production pace in my environment. However, I already know from substantial experience that maintenance folks consider my code to be a pleasure to work with. I'm quite proud of that, and it's not just about "comments" or "style".

      --
      -fb Everything not expressly forbidden is now mandatory.
    2. Re:Why I comment code... by ashultz · · Score: 1


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

      I've lost my train of thought.

    3. Re:Why I comment code... by I8TheWorm · · Score: 1

      I comment all the time. Sometimes it's before I start coding in a function to line up my thoughts. Sometimes it's after, to explain the horrible hack I had to implement. Sometimes I leave the name of the idiotic manager that forced me to write code that used unsupported features, along with an explitive or two.

      --
      Saying Android is a family of phones is akin to saying Linux is a family of PCs.
    4. Re:Why I comment code... by gunnk · · Score: 1

      The REAL trick is to comment your code so that 8 years from now when your company is still running that "temporary" hack you threw together you will STILL understand how to fix it... ... but the poor chump that inherits your code will have to hire you back at ridiculous consultant rates.

      --
      Life is short: void the warranty.
    5. Re:Why I comment code... by Anonymous Coward · · Score: 0

      A good way to do this would be to comment clearly, but in a language that few, if anyone, understands. Klingon is too obvious, as there's usually one person at any coding firm that can read it. Lojban might work, but again, programmers are almost the most likely people to know it. Personally, I'd suggest Old English, the BCPL of our modern language. If they have to hire just one professor of the languages because of it, it'd be good for them.

    6. Re:Why I comment code... by IkeTo · · Score: 1

      > I don't know why people (in general) don't like to
      > comment code.

      I don't write in-code comment because I think writing comments is a horrible way of documentation. I'll prefer writing out-of-code overview documents of the whole set of code so that people (or the future me) will know where to look at for particular behaviour, and what are the general design. After that, it is all the code which serves as the definitive comment---unless there is no way to write code that are sufficiently efficient, clear and easy to maintain at the same time.

      As for insufficient skills, those with insufficient skills to read my code has no business with my code. Period.

    7. Re:Why I comment code... by Anonymous Coward · · Score: 0

      As for insufficient skills, those with insufficient skills to read my code has no business with my code. Period.

      "Anyone who's not a building contractor has no business hanging a picture. Period."

      "Anyone who's not a professional electrician has no business plugging anything in. Period."

      See how elitist that sounds? Now, why should programming be any different? The experts (senior programmers) abstract the nasty details away, so that less technical people can still do their programming tasks without hassles.

      I don't write my own socket libraries from scratch: I read the documentation for it, and use code that I don't understand. I don't write my own OS kernel; I use it without understanding all the fine details. I don't write my own compiler; I use it without understanding all the fine details.

      I *could* do all of these things, but it's not worth my time. Saving time is what comments are all about.

      I don't want to wade through the code to find out what it does; I want it spelled out in the embedded comments that specify the interface documentation. I want the name of the algorithm used, and a proof of correctness if necessary, spelled out in the comments, so that I can look it up and see what's gone wrong if I have to. I want documentation on what's been done, at the site of where it's been done, so that I can find it and it can be kept up to date.

      Overview documents are great, but they're not enough.

      When I pass off a specific function (or set of functions) for unit testing to my testing department, I want them to be able to extract the documention on what the function does, what it's side effects are, and be able to prove whether or not it works as documented. If it doesn't, one of the comments or the documentation is broken.

    8. Re:Why I comment code... by IkeTo · · Score: 1

      > "Anyone who's not a building contractor has no
      > business hanging a picture. Period."

      No. But anyone who's not a building contractor really has no business taking down a wall in your house.

      > "Anyone who's not a professional electrician has
      > no business plugging anything in. Period."

      No. But anyone who's no a professional electrician really (should) have no business removing the front cover of your socket and swap a worn wire in it with a new one.

      Anything has an internal and an external interface. I have no problem documenting the external interface: I do write doc comments or PODs. What I won't do is to write comments that essentially says "this internal function is there for doing this and this", because the internal function will be modified faster than I can write comment for it, and if it is so complicated that it really needs comments, it is too complicated anyway. I won't write comments that essentially says "this line of code is there so that this and this happen", because I think that the code should be written in a way that it is trivial to know this for any professional developer, and unless it is impossible to do it, I won't write such a comment. This is what I call a in-code comment.

      As of programming, if you are still in an age where senior programmer will make all the design and your junior programmer will code it, it means you will always have bad design. Design comes from the coding, or actually the difficulty of coding. You are spliting up two very closely related tasks to two different people. The same for unit testing.

  38. Architecture is more important than Comments by olivermoffat · · Score: 1

    I (sadly) have a lot of experience working with old, ugly code. And I can tell you, I would give up every single comment if I could have a good Architecture. Good architecture adds more value to a code base than does good comments.

    1. Re:Architecture is more important than Comments by lgw · · Score: 1

      This is true, but it's also a lot harder. I'd expect a kid out of college to comment properly. Good software architects are a rare breed.

      --
      Socialism: a lie told by totalitarians and believed by fools.
  39. IN SOVIET RUSSIA ... by Ihlosi · · Score: 1

    code comments you.

  40. Assembly code by frovingslosh · · Score: 1

    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.

    --
    I'm an American. I love this country and the freedoms that we used to have.
    1. Re:Assembly code by WillAffleckUW · · Score: 1

      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.

      Good thing I write in assembler, so I don't need to comment. What is this assembly you speak of?

      --
      -- Tigger warning: This post may contain tiggers! --
  41. and don't by www.sorehands.com · · Score: 1

    And don't put in how much of a asshole your boss is and the other coworkers are, unless you want them to see it.

    Don't appologize for your code, then promise to fix it later. I saw that done at one company, 3 years after the commenter have left.

    1. Re:and don't by soloport · · Score: 1

      I'm sorry that your employee called you an asshole in his code. Must have been rather embare... uh... [too much irony!] [head asplode!]

  42. Things to always remember when commenting by WillAffleckUW · · Score: 4, Funny

    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.

    --
    -- Tigger warning: This post may contain tiggers! --
    1. Re:Things to always remember when commenting by NineNine · · Score: 1

      Actually, when I was a programmer, I'd always put random shit in my comments. It was a good way to vent. I can't count the number of times I was having a bad day, then I ran into some other developers' bizarre comments that made me feel a hell of a lot better.

      In fact, a certain state's Medicare billing system is full of comments discussing AC/DC's music and my personal treatise on pizza.

    2. Re:Things to always remember when commenting by WillAffleckUW · · Score: 1

      In fact, a certain state's Medicare billing system is full of comments discussing AC/DC's music and my personal treatise on pizza.

      I have the lyrics to a song by Heart inside some core code that runs insurance subrogation myself, as well as When The Levee Breaks ...

      --
      -- Tigger warning: This post may contain tiggers! --
    3. Re:Things to always remember when commenting by sapped · · Score: 1
      10. If you're updating or modifying code, write your opinion about the original code in the comments. Use nasty words if you can.


      Recently my cubemate was modifying some code and came across the following comment "This routine is cunningly named CreateCustomer because it does not create any customers."

      Immediately she turned to me and asked if I had made the comment. After looking at the rest of my, admittedly snide, comments she was immediately able to figure out where to jump to for the real correction.
    4. Re:Things to always remember when commenting by HermanAB · · Score: 1

      You forgot the best one. 11. Always use negative logic: #define TRUE 0 #define FALSE 1 if (!geardown != FALSE) then do_not_eject_pilot();

      --
      Oh well, what the hell...
    5. Re:Things to always remember when commenting by WillAffleckUW · · Score: 1

      Perl drives me crazy where it assumes 0 is false and then ignores 0 results since they're not true.

      I have to change my 0 results into -1 values and stuff them in my hashes - and then comment that so I know that a -1 is really a 0 value.

      but defining non-standard values with Defines drives me insane, just like nested negative negative truths (!(!(isFrog))) which is just isFrog ...

      --
      -- Tigger warning: This post may contain tiggers! --
    6. Re:Things to always remember when commenting by Anonymous Coward · · Score: 0

      Hear hear! I've put random song lyrics in my code many times. I'm also prone to make up random variable names like "Fred" and "Bob" (or more often than not, "Shit" or "WhatTheFuck" if it's a temporary variable I'm using to fix a crashing bug at 1 in the morning.) This is usually in my own code though, and not often used if someone else is going to read it. However, I did turn in one piece of code for a school project that included the comment, "Half Life 2 is the greatest game of all time" in the middle of a graphics function.

    7. Re:Things to always remember when commenting by Reverend528 · · Score: 2, Funny
      haikus or other poems are also useful comments:

      // nested switch statments
      // with some inefficient code
      // and memory leaks

    8. Re:Things to always remember when commenting by Anonymous Coward · · Score: 0

      Kristin Hersh fan, eh? Good taste.

    9. Re:Things to always remember when commenting by Anonymous Coward · · Score: 0

      Kristin Hersh fan, eh? Good taste.

      She rocks my world ...

  43. All Depends... by eno2001 · · Score: 3, Funny
    ...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

    --
    -"...bad old ideas look confusingly fresh when they are packaged as technology" - Jaron Lanier (Digital Maoism on Edge.o
    1. Re:All Depends... by starseeker · · Score: 1

      # The main function starts here

      Actually, that would have been useful for me to have had in the Maxima code base (1970s and 1980s lisp code)

      I'm just beginning to get the hang of lisp, and I had a heck of a time figuring out exactly how the darn thing got started. Anything would have been nice - I didn't know at the beginning that user::run kicked things off, for example (seasoned lisp coders feel free to laugh yourselves out of your chairs). I finally got some idea of the flow of things and charted it:
      http://maxima.sourceforge.net/maximaflowtoplevel.p ng

      Of course, all the cool and important stuff happens later on, but at least I know roughly how I get there now. Progress!

      Essentially I wanted to know this because I was looking for ways to unravel how Maxima actually WORKS (comments were apparently considered a waste of space back in the day, or worse encouraged people to play with (and break) the code.) Now it's open source, and I would like to have the code in a readily understandable state (well, as much as possible - some math stuff is just hard to follow no matter how you comment it) but it's remarkably like redoing a decade old house that has fallen into disrepair. And with minimal to no comments, it's like working without blueprints - you have to poke and prod and hope things are relatively sturdy.

      --
      "I object to doing things that computers can do." -- Olin Shivers, lispers.org
  44. Sample Comment by giminy · · Score: 0

    i++; // Incremement i by 1
    if (i 3){ // check if i less than 3
          println("hello, world"); // print "hello world" to screen
    } // if (i 3)

    --
    The Right Reverend K. Reid Wightman,
    1. Re:Sample Comment by Abcd1234 · · Score: 0, Redundant

      Yeah, sample for how to do it exactly *wrong*. Do you *really* need to tell people you're incrementing i by one when the line is "i++"?! Honestly, people... code, written well, is nearly self-documenting. Comments should exist to *augment* the code... clarify the tricky bits, outline complex algorithms, provide explanation for why things are done how they are. They should not simply re-express the code in words...

      Example, in the above code, I'd probably have a block at the top which said something like: "If i is less than 3, then <some condition> has been satisfied, so print out 'hello world'".

    2. Re:Sample Comment by rylin · · Score: 1
      // reminder to jr coder to use operators that don't get stripped away by slashdot.
    3. Re:Sample Comment by kryten_nl · · Score: 1

      Or:
      > (= &gt;)
      < (= &lt;)

      --
      For the perfect anti-Unix, write an OS that thinks it knows what you're doing better than you do and let it be wrong.
  45. How & Whys by Anonymous Coward · · Score: 4, Insightful

    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.

    1. Re:How & Whys by Surt · · Score: 1

      There's a corollary to this that says:

      If you write code where the how is tricky, comment it very clearly.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    2. Re:How & Whys by phidipides · · Score: 1
      Agreed. The single best advice I've ever seen on comments comes from the Linux Kernel Coding Style guideline:
      Comments are good, but there is also a danger of over-commenting. Never try to explain how your code works in a comment: it's much better to write the code so that the working is obvious, and it's a waste of time to explain badly written code.
      Generally, you want your comments to tell what your code does, not how. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably go back to chapter 4 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly why it does it.

      And for the people that have posted that comments are unnecessary, try working on a team when the software being developed is going to be modified and extended over a period of years, and see if you still think comments are unnecessary. When your eyes are bleeding from spending several hours trying to figure out the what and why of thousands of lines of code written by inexperienced programmers you will offer sacrifices at the alter of well commented code.
  46. Office Space -- how realistic? by rwade · · Score: 1

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

    How reasonable a fear is this?

    Though commenting improves efficiency by allowing other members of the staff to collaborate effectively, it may also make one irrelavent or very easy to replace if new people can so easily introduce themselves to the methods of doing the work.

  47. Mod parent way up :) by TCM · · Score: 1

    (+6, Funny)

    and give him some Underrated, not just karma-less Funny.

    --
    Of course it runs NetBSD. BTC: 1NT7QvbetmANwaMzhpVL6
    1. Re:Mod parent way up :) by rbarreira · · Score: 0, Offtopic

      Never mind about the karma, I think I have enough already. Thanks anyway ;)

      --

      The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
    2. Re:Mod parent way up :) by Rick+and+Roll · · Score: 1

      Do you ever lose Karma? I've been a real dick lately and I still have my extra point.

    3. Re:Mod parent way up :) by rbarreira · · Score: 1

      Since I gained it, I never lost it. Sometimes I have downmods, but I guess the upmods balance it out. Looking at your comment history, it seems that you're on the same situation :)

      --

      The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
  48. Ive always... by Neticulous · · Score: 1

    I have always written all my comments out before I start to code, it gives me a good idea of exactly what I have to do, helps me to not forget parts of a program, and makes it much quicker overall.

  49. Look out... by Anonymous Coward · · Score: 0

    Just make sure that your comments are easily understood by someone in India.. so when they take your job it will make the transition easier.. that way you don't have to train the person that's going to take your job from you..

  50. People Cut Corners Once in the Workforce by rwade · · Score: 1

    There is some training involved in any job, but in every job I've had, from fast food to clerical, people disregard at least some of the methods -- particularly with regard to documentation -- so that they can get the job done and stand around or go home.

  51. As Always, Just Out Of Reach by Nom+du+Keyboard · · Score: 1
    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!

    --
    "It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
  52. All the commenting you need by dakkon1024 · · Score: 1

    */ Begin pay raise */

    1. Re:All the commenting you need by Bodhammer · · Score: 1

      Your fired because your code won't compile...

      Should read: /* Begin pay raise */

      --
      "I say we take off, nuke the site from orbit. It's the only way to be sure."
    2. Re:All the commenting you need by dakkon1024 · · Score: 1

      You can't fire me, I'm certified!

  53. What makes a good Comment? by vivin · · Score: 4, Interesting

    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?!"

    --
    Vivin Suresh Paliath
    http://vivin.net

    I like
    1. Re:What makes a good Comment? by lgw · · Score: 1

      Assembly programming is a different world, as far as commentg goes. You really should comment every line of assembly, even when you just increment a register, because the repition of what that register is being used for right now helps *a lot* when several people add things to a routine over the years, and don't always understand what they're doing.

      There's proably not a modern language for which every-line comments make sense, but for assebemly it's quite a useful habit. The rule of "you should be able to port it without understanding the language" is the right standard for assembly comments.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    2. Re:What makes a good Comment? by mOdQuArK! · · Score: 5, Insightful
      You really should comment every line of assembly, even when you just increment a register,

      As long as you're commenting the _real_ effect of the instruction, and not just mindlessly repeating what the mnemonic already tells the reader. I've seen lots of stupid assembly-language comments like "increments the A register". Gee, thanks - I couldn't have figured that out from the "INC A" mnemonic.

    3. Re:What makes a good Comment? by vivin · · Score: 1

      You really should comment every line of assembly, even when you just increment a register

      Rather than doing that, you should increment a block of assembly code. You almost have logical blocks of code that do something. Instead of commenting one instruction at a time, you should be commenting a block of code. Commenting it one line at a time is tedious as well, and doesn't really provide that much information:


      1H LDAA =$10 ;Load the AR with $10
          DECA ;Decrement the AR
          BNE 1B ;If the AR is not zero, branch back


      versus


      1H LDAA =$10 ;Initialize our counter (in the
          DECA ;AR) with the value $10. W estart
          BNE 1B ;the loop, decrementing the ;value in the AR until it ;reaches 0.


      The second version is much better than the first. And also, saying "increment the AR" to an "INCA" instruction is not that helpful. Why am I incrementing it? What happens when I increment it? Too often I've seen useless comments like that.

      --
      Vivin Suresh Paliath
      http://vivin.net

      I like
    4. Re:What makes a good Comment? by lgw · · Score: 2, Insightful

      I couldn't agree more. Some people just need not to program.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    5. Re:What makes a good Comment? by lgw · · Score: 1

      Comments that don't add any information are useless, of course. Comments like:

      "point to the end of the buffer"
      "decrement by the size of a record"
      "loop till we find a non-empty record" ... are usually a waste of space in C++, but are vital to assembly, as variable names are almost never self-describing, and repeating what a register is being used for *here* is worth repeeating on every line, as people can insert a large block of code into the middle of your code and change the proximity you depended on for the clarity of your comment.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    6. Re:What makes a good Comment? by GlassHeart · · Score: 1
      Good comments should explain these areas:

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

      This is good in theory, but in practice the "how" will become obsolete much more quickly than the "what" or "why". The "how" is also redundant for most cases, because hopefully the maintainer can understand the code as it was written. Thus, I would have to recommend documenting the "how" only for the most confusing or subtle code. Put another way, if you really have to document the "how", consider a different solution.

    7. Re:What makes a good Comment? by Fujisawa+Sensei · · Score: 2, Interesting
      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.)

      --
      If someone is passing you on the right, you are an asshole for driving in the wrong lane.
    8. Re:What makes a good Comment? by Paradox · · Score: 1
      Good comments should explain these areas:

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

      While I agree with a, and sometimes c (usually in the case of frameworks), I think you should never document how you do something unless the code is complex by its very nature (assembly, code that twonks with hardware settings or obscure memory/os operations, etc...).

      If you document how to do something simple, and that simple thing changes, you now have at least doubled your workload. Instead, make your code clear and self-documenting and maintainers will thank you far more.

      I have two reasons to say this. The first is every maintainer's nightmare. Bad comments are worse than no comments at all. We naturally give comments a large amount of trust, so if they are wrong, it can take awhile to realize it. Second, comments must be updated along with maintenance. An excessive amount of documentation greatly increases the workload (and thus, the opportunity for a mistake).

      Finally, if you every find yourself writing comments inside a method, ask yourself, "Why is this method so long and complicated? Can I make it smaller and self-documenting?" I find that my ideal documentation comes when my code is only on headers. Often, we refactor how things are done without refatoring much of what and when its done.

      By only documenting your method signatures (like with Javadoc, Doxygen, rdoc, etc...) you help minimize your work and maximize your documentation's effectiveness. It will also help you to write self-documenting code.

      This is, of course, just IMHO. But, I really dislike people who excessively document on the grounds of that literate programming nonsense. To get a concrete idea of the style I'm promoting, please see one of my open source libraries.

      --
      Slashdot. It's Not For Common Sense
    9. Re:What makes a good Comment? by aspx · · Score: 1

      What you describe is not commenting, it is writing the code twice. Once in English, once in ASM/C++. I don't think that is a useful standard. Do you really think developers will maintain all those comments, as the code is changed?

    10. Re:What makes a good Comment? by idontgno · · Score: 3, Informative
      As long as you're commenting the _real_ effect of the instruction, and not just mindlessly repeating what the mnemonic already tells the reader.

      Or worse yet, lying.

      One pre-paleolithic piece of mainframe assembler I (and my colleagues) once worked with was an intricate sequence of shift operations designed to isolate a 5-bit segment in the middle of a 36-bit word in one of the accumulators. It was documented with a breathtakingly detailed block of comments, complete with little pictures of the contents of the register at each step in the process (composed of dashes and vertical bars and everything--ASCII documentation art).

      The code wasn't working, but there was absolutely no way that it was the code's fault. It was just FM (F'ing Magic) that it was broke. We were convinced of this. That is, until one of my supervisors, a crusty old communications sergeant, actually studied the instruction string of the segement of code in question and noticed that in the last step, the actual answer was being shifted the wrong direction--right out of the register and into the bit bucket.

      If only we could have compiled the comments...

      This, then, is Johnson's Postulate on Documentation: "Read the source code, too."

      --
      Welcome to the Panopticon. Used to be a prison, now it's your home.
    11. Re:What makes a good Comment? by hackstraw · · Score: 1

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


      Although I'm not a fulltime code monkey, I used to be, and I've never heard of the what, why, how approach (I never took a CS class either, so it could be something I've missed).

      I understand the what, but the why and how seem irrelevant. I've never heard a why explanation. Seems too philosophical for writing code. How, _should_ be clear from the code, unless its a very long function.

      I've always appreciated comments for global or module variables that do not or cannot have a name that is self descriptive. I also appreciate function comments that say what the inputs are, what the function does, and what the outputs are.

      A pet peeve of mine is inconsistency. I've seen sparsely documented code that had a comment like:

      int i; /* loop counter */

      Why someone thought that a one character loop variable needed a comment for clarity is beyond me.

    12. Re:What makes a good Comment? by Zaiff+Urgulbunger · · Score: 2, Insightful

      Or worse yet, lying.

      Not specifically regarding assembler, but you've just reminded me of the thing I absolutely hate the most which is people taking a chunk of existing code, comments an' all, tweaking the code to do something similar but different, but not updating the comments. Any typically the people (they ain't programmers!) who do this also use the existing function name but suffix it with a "2" or something -- I mean, why bother with a meaningful name? Someone might be able to understand the code!!

    13. Re:What makes a good Comment? by Zaiff+Urgulbunger · · Score: 1

      I think I'd have to recommend keeping how's very close to the actual implementation, because what can otherwise happen is that code will be modified but the comments remain as before which can be trés confusing in the future!

    14. Re:What makes a good Comment? by ShyGuy91284 · · Score: 1

      I agree. I was about to make the same comment. I took a Computer Organization class in the spring, and we used MIPS assembly (R2000). That stuff could probably be a bastard for even the original programmer to fully understand if he has to go back to something in a large source file in some cases. The lack of variable names other then $S#,$T# (at least in MIPS) is what I really hate about asm....

      --
      In undeveloped countries, the consumer controls the market. In capitalist America, the market controls you.
    15. Re:What makes a good Comment? by noidentity · · Score: 1

      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++.

      What about the readers who knew MACRO32, where they blasted with lots of redundant (and possibly inconsistent) comments when they read the original code?

    16. Re:What makes a good Comment? by mrchaotica · · Score: 1
      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.)
      If that's the case, I tend to think that those technologies were poor choices to begin with. I mean, for every 5-year-old dead JSP 1.0 program I'm sure there are several 20-year-old C programs that are still working fine. (Of course, I don't mean to imply that C should be used for the same kind of thing as JSP, just that it was perhaps a better choice for its particular problem than JSP 1.0 was for its.)
      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    17. Re:What makes a good Comment? by John+Bayko · · Score: 1

      I think you have that out of order. The most important comment is always why, followed by how. The what is expressed in the code itself, and if that's not clear, your code probably needs some refactoring.

    18. Re:What makes a good Comment? by jhcarnelian · · Score: 1
      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.
      For assembly language programs, that's what you need to do because assembly language programs severely limit how you can name and abstract things. For high level languages, the what/why/how should be mostly self-explanatory from the names and abstractions you use. If you feel the need to add long comments to code written in a high-level language, there is something wrong with the code.
    19. Re:What makes a good Comment? by phlamingo · · Score: 1

      "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."

      That is the programming equivalent of the old pilot's saw: "A good landing is one you walk away from."

      I think it is better to set the bar a little higher. Most pilots aim to walk away from a landing AND be able to fly the plane again later.

      Likewise, a good goal for comments could be, "Explain this piece of code and its context without insulting the reader's intelligence." Or, maybe, "Ensure that maintainer isn't tempted to change this code without understanding it." Or even, "Tell myself why I did it this way so I'm not tempted to break it next month."

      --
      I had forgotten how much cooler teenagers look when they are smoking. Oh, wait ...
    20. Re:What makes a good Comment? by lebow · · Score: 2, Informative
      Ok well there is sometimes a reason I've found to do this. I come in in the middle of a project where some one wrote a bunch of poorly designed functions, that don't take arguments ( data is passed through global vars ) and they produce a extremely specific result that should be more general. for example fetchdata() a highly specific function with a generic name. I want to write a real fetchdata() that is generic and I can use in other parts of the code but the good name is already taken, and I don't have the patience ( or time ) to go through and fix it every where in the whole project. ( I guess I could do a global search and replace but.. )

      So I make fetchdata2() ( or fetchdata_good() and use that from now on and when I can try to replace the old fetchdata()s to use the better version.

    21. Re:What makes a good Comment? by mickwd · · Score: 1

      It's also appropriate, on occasion, to comment what you're NOT doing.

      If you had to reject an alternative approach, one that might have appeared easier at first glance, for some obscure reason, say why.

      This will save someone (possibly yourself) looking at the code much later and wondering why you didn't take that alternative approach. If that person has to extend or re-write that code, they may well use that alternative approach that you so-carefully avoided, and fall over the problem that you carefully foresaw.

    22. Re:What makes a good Comment? by swthomas55 · · Score: 1

      My favorite comment (not written by me) is this line from the Unix V7 source:

              sub r3,r0 / this is the clever part

      You can see the whole file at http://minnie.tuhs.org/UnixTree/V7/usr/sys/40/m40. s.html

      Seeing the entire context doesn't enlighten me any more than does the single line above. The only purpose of the comment, imo, is to flag to the reader "if you think you understand what is happening here, you might want to look again."

    23. Re:What makes a good Comment? by Anonymous Coward · · Score: 0

      > Grammar is important ...

      On Slashdot, that is spelled "grammer".

    24. Re:What makes a good Comment? by Anonymous Coward · · Score: 0

      You break the design into functions and steps
      within the function. Comments should describe
      the function and what steps you are doing inside
      the function.

      Especially for complex calcs.

      # Take
      # var1 - current balance
      # var2 - interest rate
      # var3 - days of moon
      # and use calculation from 1.2.1 in version 2.0 # of the spec to calculate var4 - new balance as # as date var5.

      When I come to debug this if at the point of
      the comment one of the values is wrong then
      i backtrack further otherwise I dig into this

    25. Re:What makes a good Comment? by Nevyn · · Score: 1
      What about the readers who knew MACRO32, where they blasted with lots of redundant (and possibly inconsistent) comments when they read the original code?

      Yeh, the I ported code I didn't understand story didn't make me think "ooh, I should comment more" but "Ohh, someone needs to take a hammer to someone's fingers, for the sake of the rest of us". Here's a free clue to the OP, when you translate X into Y, you do not start off with Z which is a different translation of X (esp. given that there is no assurance that Z is an accurate translation).

      --
      ustr: Managed string API with ave. 44% overhead over strdup(), for 0-20B
    26. Re:What makes a good Comment? by hondo77 · · Score: 1

      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.

      Just because one knows what an ABET accredited engineering program is, doesn't make one a software engineer.

      [The] 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.

      They better document the code because the paper documentation they wrote will be long way before the code is.

      --
      I live ze unknown. I love ze unknown. I am ze unknown.
    27. Re:What makes a good Comment? by jimbonics · · Score: 0

      why is it spelled grammer on slashdot? was this a failed attempt to correct someones spelling?

    28. Re:What makes a good Comment? by shadow_slicer · · Score: 1

      That's still better than what I've seen. Some people drop to shorthand when writing commments.
      So on the "INC A" line the comment would be "inc A reg"

    29. Re:What makes a good Comment? by Anonymous Coward · · Score: 0

      Uhmm... did you RTFC? I dunno if anyone can translate a program if they don't understand it. the OP is saying that if you write comments really well and explain it really well you shouldn't need to actually know the programming language. At the very least you should know enough programming to figure out how to implement the comments.

      Duh.

    30. Re:What makes a good Comment? by figa · · Score: 1

      By your description, I was able to instantly tell that you went to Arizona State and took assembler from Pheanis. I had Neuman, who held the same philosophy, (Pheanis was off that year), and it was probably my most valuable class in college. Oddly enough, it landed me my first programming job using Java (which I did not know at the time). I described my assembler implementation of the multi-threaded OS, and that won the interviewers' hearts.

    31. Re:What makes a good Comment? by GlassHeart · · Score: 1
      I think I'd have to recommend keeping how's very close to the actual implementation, because what can otherwise happen is that code will be modified but the comments remain as before which can be tr?s confusing in the future!

      That would be ideal. The problem is that in most real cases, the cost of maintaining the "how" comments becomes prohibitive, and they lapse into the confusion you fear. In some cases, such comments are worse than not having any.

      As I've said, if your code is not clear and readable enough for a competent maintainer to figure out the "how" based on the code, aided by the "what" and "why" comments, it's already a pretty bad sign. High level computer languages, by virtue of their precision, is often a better tool than English to describe the "how".

    32. Re:What makes a good Comment? by not-enough-info · · Score: 1
      a) What you're doing.
      b) Why you're doing it.
      c) How you're doing it.
      ...or what they were doing, but their legacy remains, hewn into the living rock... of Stonehenge.
      --
      ---k--
      </stupid>
    33. Re:What makes a good Comment? by borawjm · · Score: 1

      It makes you think though.. If comments become "too" detailed, it's almost as if you are explaining something in one language then repeating it again in a another language. Why not skip the code part and create machine code based on the comments alone? Perhaps this what future compilers will do?

    34. Re:What makes a good Comment? by Anonymous Coward · · Score: 0
      Just because one knows what an ABET accredited engineering program is, doesn't make one a software engineer.

      No, but it does mean that one knows what an engineer is.

    35. Re:What makes a good Comment? by vivin · · Score: 1

      You're right on the money :)

      I was lucky enough to be in the last class that Pheanis ever taught at ASU. CSE 521 during the spring of '04 - it was also my last semester at ASU.

      CSE 225, 421, and 521 have been the most valuable classes that I've ever taken in college.

      --
      Vivin Suresh Paliath
      http://vivin.net

      I like
    36. Re:What makes a good Comment? by clausen · · Score: 1
      Good comments should explain these areas:

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

      While I agree with (a) and (b), I disagree with (c). Programming languages are very good at explaining exactly how something is done. If your function is so complicated that it isn't obvious at first glance how exactly it achieves its stated objectives in (a), then you should fix your code.

      I wrote a rant on this topic called How (Not) to Write Comments at http://members.optusnet.com.au/clausen/rants/comme nts.html a few months ago for my students. Before giving my recommendations, I made some fun of the comments my students were writing, which I classified as mystic translations, autobiography, military, comic strip and haiku.

    37. Re:What makes a good Comment? by pommiekiwifruit · · Score: 1

      Having *source code* would be an advantage over what some people work with!

    38. Re:What makes a good Comment? by sdpuppy · · Score: 1

      Well, the most honest comment I've seen in a program was: /* not sure what this does - except everything works with this here */

    39. Re:What makes a good Comment? by Pyrrus · · Score: 1

      The idea is not to say "increment register A", because yes, everyone who has any buisiness reading the code knows what register A is. The idea would be "increment number of bytes in the buffer", because it is not obvious *what* the number in register A means.

    40. Re:What makes a good Comment? by Shaklee39 · · Score: 1

      Any time you mention that you are a grammar nazi, expect your comment to be sifted through with a fine-toothed comb.

    41. Re:What makes a good Comment? by NickDoulas · · Score: 1

      Good comments should explain these areas:

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

      Sure, all that would be great, but I would be happy to just have part (b) - WHY you're doing it. It might take more time than I would like, but I can eventually stare at code long enough to figure out what/how. But you may never figure out "why" something is done the way it is without comments.

    42. Re:What makes a good Comment? by Anonymous Coward · · Score: 0
      I want to write a real fetchdata() that is generic and I can use in other parts of the code but the good name is already taken, and I don't have the patience ( or time ) to go through and fix it every where in the whole project. ( I guess I could do a global search and replace but.. )

      Let me finish your sentence: you don't trust a global search and replace to not change string literals, etc. inappropriately. (And rightfully so.)

      What you need a decent suite of refactoring tools. Search freshmeat. They're out there. Tools that will show you all the callers of a function - even polymorphic stuff with generic names; they understand context. Tools that are smart enough to see if your renaming a field causes it to be shadowed somewhere by a local variable. Tools that really understand the consequences of what you are doing and help you see them quickly.

      If you're using Java, I highly recommend Eclipse. It's an IDE. If you have a favorite editor, that's fine. Do your normal editing in whatever and fire up Eclipse when you have sweeping changes like this. (You'll probably find yourself using Eclipse more and your regular editor less as time goes on. But maybe not, who knows.)

    43. Re:What makes a good Comment? by Kuros_overkill · · Score: 1

      Sounds like my famous: /* I have no idea what the following 40 lines do, but they work, they work well, DO NOT TOUCH */
      There is one thing that does tend to bug me, and all the instructors at the course I just finished did this. Comments focused soly on the How. I don't need the How (unless, of course you are doing something strange, then they would be much apreciated). I need the What and the Why.
      Example of what i would see all to often:
      int addNums(int Num1, int Num2)
      {
      /*Declair Temporary Variable */
      int tempNum;
      /* Add Params, store in temporary Variable */
      tempNum = Num1 + Num2;
      /* Return Temporary Variable */
      return tempNum;
      }
      This tells me nothing I can't figure out from the code myself.
      as oposed to:
      What /* addNums: Returns the Sumation of two numbers */ Why /* Used to do quick sumation on only two numbers */
      /*Seperate from addNumsArray(int[] Nums) for speed improvement since dual number addition is used most often in prog */
      int addNums(ect...

      this on the other hand tells me what the function does, and (in this case) that we wrote this to handle a special case, what that special case is, and why we are handling it.

      To many programers (IMHO) are not treating code as a language. They don't attempt to learn how to read it. Instead they rely soley on the comments to tell them what is going on. This leads to both usless comments cloging up what I am trying to read, as well as shifting the focus on the What and Why, and re-distributing it on the How. (relates to grand parent)

    44. Re:What makes a good Comment? by maxwell+demon · · Score: 1

      No, the code expresses the how (because that's what the computer needs to know). Granted, the distinction between what and how is blurry, and the more high-level a programming language is, the more it is moved in the direction of "what".

      The point is: "what" is the goal you want to achieve (e.g. "post a reply on slashdot"), "how" is the algorithm to achieve the goal (e.g. "Klick on the link 'reply', type your answer in the text box, hit the 'Submit' button"). You generally code the algorithm, not the goal.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    45. Re:What makes a good Comment? by Pete · · Score: 1
      ALL Engineers KNOW how to write comments. If they don't know how to comment they're code they aren't an Engineer. [...] Because they're had to write Analysis Documents, Design Documents, and Test Plans. They code doesn't need documentation [...]

      The sentences around vivin's quote that you didn't quite manage to paste: "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."

      I guess it's a good thing those fake engineers will have you to write they're comments for the'm. ;)

      In fact I will lay odds the 60% of the "Software Engineers" out there aren't really Engineers.

      No True Scotsman, anyone?...

      And for god's sake dude, "engineer" is not a proper noun, you're not supposed to capitalise it. The same applies for analysis documents, design documents and test plans. Argh.

    46. Re:What makes a good Comment? by Anonymous Coward · · Score: 0

      Do you have any idea how many MIS graduates are out there who say "Computer Science" and call themselves engineers are out there?

      Thousands. There are second rate schools, like Troy State University where they give seniors crossword puzzle takehome tests, churning out MIS degrees, call them Computer Science then get Software Engineer as their job title because it sounds good? Hell I interviewed one guy who didn't even have a degree who had Software Engineer on his resume. We've had people with accounting degrees who had no idea what an engineer really was, but because they were Management they had the title of Engineer IV .

    47. Re:What makes a good Comment? by Anonymous Coward · · Score: 0
      No True Scotsman, anyone?...

      The No True Scotsman argument is philosophical Bullshit. The Fallicy of the argument is correlates unrelated grouping. Today being Scottish has nothing to do with sugar on your oats. You should also be aware that sugar does not grow in Scotland. So a true Scotsman would not put something imported by the English in his oats. England conquored Scotland, and thus the English, and Scots did not get along, remember William Wallace and Robert the Bruce? So at one time putting sugar in you oats indicated not only that you had money, which most scots didn't, but that you were also an English sympathizer.

      How about using a relational grouping of skills?

      Such as: All members of the swim team are good swimmers? or all Lifeguards know CPR. (CPR is a requirement for getting your RedCross Lifeguarding certification. Or more closely to Software Engineers and Comments All members of the SWAT team know how to shoot?

    48. Re:What makes a good Comment? by RAMMS+EIN · · Score: 1

      ``If only we could have compiled the comments...''

      Which reminds me of the Story of Mac. One of the best ways to make your code understandable is to write it understandably in the first place. Use sensible names, ADTs, simple functions, etc. etc. This doesn't completely obviate the need for comments, but it makes understanding the code itself a lot easier.

      --
      Please correct me if I got my facts wrong.
    49. Re:What makes a good Comment? by Young+Master+Ploppy · · Score: 1

      The usual way that people approach this is to dive in, code away feverishly through several iterations until they've got something that seems to work, THEN go back through it and add comments - if they have the time...

      One trick I picked up early on in my coding career that radically changed the way I approach the coding process is to write your comments FIRST.

      It's a very handy way of planning out your structure, algorithms, and data flow on complex chunks of code before anything is set in stone.

      Otherwise, if you dive right in there and start coding away, you often realise halfway through that your first approach is not going to work, and you have to go back and change THIS structure, change THOSE parameters, add THIS call, take THIS chunk out into a separate function, etc etc...

      Try writing your comments first - you should be able to walk through your process and catch some of the most common gotchas before you even write a single line of code. Of course, you're always going to have to do the occasional rushed hack job, but I've found this approach tends to actually save me time in the long run.

      --
      http://instantbadger.blogspot.com
    50. Re:What makes a good Comment? by Anonymous Coward · · Score: 0
      for every 5-year-old dead JSP 1.0 program I'm sure there are several 20-year-old C programs that are still working fine

      Perhaps in the embedded world, but look at the changes since then. K&R is dead, ANSI has made changes, OSs have basically been rewritten or dumped. Who uses "far" pointers now and how many applications were written using them?

    51. Re:What makes a good Comment? by rthille · · Score: 1

      I'd have to say that the most important thing of the 3 is 'b', Why. After all, after beating my head against the code for a few days/weeks, I can figure out the 'what' and the 'how', but not the 'why'. When the assumptions around the function change, the 'why' part becomes critical.

      --
      Awesome furniture, accessories and cabinetry in Santa Rosa, CA: http://humanity-home.com/
  54. My strategy by Anonymous Coward · · Score: 0

    Of course, job security should be your #1 concern. Good comments are just the icing on the cake. After you have implemented deceptive function names (deleteFile -> openFile), hostile macro's (// -> sleep();), just add comments that confirm what the function appears to do on first glance. Add some edge cases as tested and working that will certainly fail, and give some ludicrous versions for the compiler the code has been `tested` with.

    Your code is good enough when it seems easier to just feed it to an obfuscator than to use the actual code.

  55. Mirror by Swamii · · Score: 1

    You can find the article text here on MirrorDot.

    --
    Tech, life, family, faith: Give me a visit
  56. Literate Programming by Anonymous Coward · · Score: 0


        http://www.literateprogramming.com/

    Overall, this fella's article is just stupid. He gives very good examples of bad comments, and then goes on to give some "good" examples, which are just as poor:

          var teamCount; // loop counter

    which is it? the count of the number of teams you have, or a loop counter? if it is a loop counter, why not just label it i? Overall this article was useless at best, and down right wrong at worst.

    1. Re:Literate Programming by Anonymous Coward · · Score: 0

      +1

    2. Re:Literate Programming by mrjb · · Score: 1

      +1
      And that, my friend, is why we're talking about commenting code.

      --
      Visit http://ringbreak.dnd.utwente.nl/~mrjb/growingbettersoftware to download your free copy of the book
    3. Re:Literate Programming by Anonymous Coward · · Score: 0

      Who needs comments ! Use python it's self commenting pseudo code.

  57. How To Comment Code by $RANDOMLUSER · · Score: 1
    --
    No folly is more costly than the folly of intolerant idealism. - Winston Churchill
  58. Important by koreaman · · Score: 0

    A TRUE Klingon Warrior does not comment his code!

  59. My favorite comment by VanWEric · · Score: 1

    One of the other programmers put in a really awesome comment the other day. I wish to share it with you all.

    My code: (from a core library that services many different code bases)
    numInputs = pd.getInt("numInputs");

    His comment/fix:
    numInputs = 3; //pd.getInt("numInputs");

    Why parse the parameter database when you already know the answer? Who cares about the other code bases? I WANT THREE NOW!

    --
    www.olin.edu
  60. Misleading... by quark007 · · Score: 1

    /* comments can be terribly misleading. Debug only the code. */

    --
    - Sh!t
    1. Re:Misleading... by $RANDOMLUSER · · Score: 1

      This may be the wisest comment posted so far. How many times have we all changed the code (which we understood) but not the comments or the process (which we didn't)?

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
  61. My simple strategies by FortKnox · · Score: 1

    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.

    --
    Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
  62. My take by lawpoop · · Score: 2, Interesting
    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.
    --
    Computers are useless. They can only give you answers.
    -- Pablo Picasso
    1. Re:My take by eyeye · · Score: 1

      Every 'flow control' statement (if, while, else, etc) gets a comment in plain English about what conditions it's checking for.

      If the conditions in an "if" are difficult to understand then your problem isnt one that commenting can fix. Try meaningful variable names and if necessary split your logic into intermediate steps.

      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.

      Again this should be fairly obvious from the names of your methods and variables ,I would also argue that most "blocks" of code should be doing simple things and not "high level" or "large scale" tasks for reasons of cohesion and reusability.
      --
      Bush and Blair ate my sig!
    2. Re:My take by purd · · Score: 1

      I'm a self-taught PHP hacker

      I stopped reading your post right there. Really.

    3. Re:My take by Anonymous Coward · · Score: 0
      Every logical block of code gets a 'mission statement' saying what large-scale, abstract task about what they are supposed to accomplish.

      I call these "functions" or "subroutines".

    4. Re:My take by lawpoop · · Score: 1

      So your code consists entirely of functions and subroutines? Do you write libraries exclusively?

      --
      Computers are useless. They can only give you answers.
      -- Pablo Picasso
    5. Re:My take by Anonymous Coward · · Score: 0

      You and me :) I find it hilarious that some people consider themselves "programmers" after hacking together a couple of messy PHP sites.

  63. At Least Be Honest by s7uar7 · · Score: 1

    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.

  64. zerg by Lord+Omlette · · Score: 5, Insightful

    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.

    --
    [o]_O
    1. Re:zerg by $RANDOMLUSER · · Score: 1

      And when they stick a gun in their mouth?

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    2. Re:zerg by Anonymous Coward · · Score: 0

      You get promoted to a manager.

    3. Re:zerg by exp(pi*sqrt(163)) · · Score: 1

      Or it might just be that they're using an algorithm that's tricky to understand. Of course nobody on /. would know about that as all anyone seems to do these days is write code to copy text from web forms into databases and vice versa. But I'd like to point out that there are still people out there who do actual programming, the kind of stuff Knuth discusses in his Art Of Programming.

      --
      Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
    4. Re:zerg by cmeans · · Score: 1

      Or maybe they're just not as smart and/or knowledgable/experienced as the author.

    5. Re:zerg by Craig+Ringer · · Score: 1

      While I see what you're getting at and generally agree with you, that's not always true.

      You have to pick your "target audience." Do you assume they have a solid understanding of the language and tools (such as a framework/toolkit)? Do you assume they're an expert with them? With a large toolkit, or complex language (think C++ and MFC), especially with a lot of subtelties, it's *NOT* reasonable to assume the reader knows something just because you do.

      In an open source C++ project, you might not even want to assume all that much knowledge of C++, to make it easier for people with a C background to follow what's going on and track down a bug.

      The following, for example, is C++ that you might see in Qt code that calls out to Python's C API. It's also broken for non-latin-1 text coding, but this is just a sample:

      <ecode>
      Fred* fred1 = dynamic_cast<Fred*>(name);
      Q_ASSERT(fred1);
      PyObject* pystrName = PyString_FromString(fred1->fullName.latin1().data( )));
      if (!pystrName)
            return NULL;
      </ecode>

      That relies on knowledge of:
          - Pointers
          - the dynamic_cast<> operator's behaviour, namely that it does a runtime check to see whether `name' can be cast to a Fred* based on inheritance (using RTTI), and returns 0 if it can not be cast.
          - That Q_ASSERT is a macro that will check the pointer is not zero (depending on compile time flags, it'll print a warning or abort the program)
          - that calls into the Python/C API return NULL when they've set an exception, and if you're going to be returning to Python you should return NULL to propagate the exception. (Otherwise you must PyErr_Print() or PyErr_Clear() it). ... and probably lots more. There's no sane way to explain all that. You have to pick your balance of expecting people to use API documentation and know the language, while explaining to them the bits you think need more explanation. It's not easy, given that what needs explaining varies depending on the reader.

      After all, this:

      <ecode>
      class Fred(object): pass
      fredInstance = Fred()
      def printName(self):
              print "I'm Fred!"
      Fred.printName = printName
      fredInstance.printName()
      </ecode> ... probably hurts the brain of a programmer used to static languages like C++. It might be best to explain to a Python user, too, since it's not that commonly used. Similarly, if I was going to use recursive template metaprogramming in a C++ program I'd need to explain that in detail, because most C++ programers don't know about it - but I wouldn't expect to have to explain the cast operators.

      I also think it's ok if someone looks puzzled by part of your code that's *genuinely* *hard*. Complex algorithms can take a while to understand, for example. There, your *goal* is to make them look like they're thinking hard, rather than have them exclaim "WTF!" or "huh? what the heck is this?".

    6. Re:zerg by Craig+Ringer · · Score: 1

      ... and in other news, I hate the extrans default on slashdot, and can't count brackets properly.

      That code also assumes the reader knows that NULL is false (and hopefully that it's actually just a macro for `0', which is false).

    7. Re:zerg by NoOneInParticular · · Score: 1

      Not really, if you say above the tricky algorithm that 'this a tricky algorithm that needs time to understand but achieves the following things: [list of things]', people will usually scroll further without examining the intricacies of the algorithm right away.

    8. Re:zerg by Leftmoon · · Score: 1

      I try this, but you know what annoys me? When I put very complete and explanatory comments in code, then sit down with someone to review the code and the first thing they do is skip past the comments, look at some assignment and ask me why I'm doing it. I mentally sigh and point to the comments. I put those comments there for a reason, read them! If you're still confused, I clearly need to add more, but at least give them the benefit of the doubt. There are so many lazy programmers on both side on the comments.

    9. Re:zerg by zsau · · Score: 1

      While reading that, I thought you were suggesting that if they pause while scrolling, we should touch their chin, squint their eyes, furrow their brows etc.! Maybe you should comment your English :)

      I think the most important thing about commenting code is that you shouldn't have to read the code to understand the comments, because the comment's written in such poor English that it's almost worse than useless.

      --
      Look out!
    10. Re:zerg by Lord+Omlette · · Score: 1

      I wish slashdot would allow me to edit my comments, because then I'd feel like less of an idiot.

      --
      [o]_O
    11. Re:zerg by Lord+Omlette · · Score: 1

      I feel your pain. I'm lucky because I've managed to beat it out of my coworkers. (Technically labmates, and we're all grad students, but still.)

      --
      [o]_O
    12. Re:zerg by Anonymous Coward · · Score: 0

      quit fucking saying zerg, you piece of shit

  65. Comments should reproduce code by Sebby · · Score: 1
    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.

    --

    AC comments get piped to /dev/null
    1. Re:Comments should reproduce code by wk633 · · Score: 1

      The problem is, many people take that to mean:

      i++; // increment the variable i by one

    2. Re:Comments should reproduce code by Sebby · · Score: 1
      Yeah, well as the article suggest, "Don't insult anyone's intelligence"

      What I mean is like:
      // Take NodeID value from Nodes array; verify that it's a valid integer.
      // Display it in the matrix column for NodeID values,
      // then add it into the DoneIDs array.


      This, in (properly formatted) C code will end up being a few lines; the comment gives you what you need to do to get it done, without describing every bit movements needed :)

      Of course, for a Perl addict, they can probably squeeze that into 20 bytes of code.

      --

      AC comments get piped to /dev/null
    3. Re:Comments should reproduce code by iabervon · · Score: 1

      Comments should reproduce design. If they reproduce code, they're redundant and likely to become inaccurate. The design, on the other hand, is useful to know, and not actually otherwise in the file. They should say what the code is supposed to do, rather than what it actually does.

    4. Re:Comments should reproduce code by tomhudson · · Score: 1

      I can just see it now - C code with Perl line-noise for comments :-)

  66. Real coders comments for C++ code by WillAffleckUW · · Score: 1
    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
    .
    --
    -- Tigger warning: This post may contain tiggers! --
  67. x<6 by smittyoneeach · · Score: 1

    you're welcome

    --
    Get thee glass eyes, and, like a scurvy politician, seem to see things thou dost not.--King Lear
  68. What about unit tests? by dubl-u · · Score: 1

    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 by the computer, so they're much less likely to be misleading or out of date. If you have good unit tests (and especially if you do test-first development), I think a lot of traditional comments become less useful.

  69. Comments... hmmm... makes me think of Blogs!!!! by Anonymous Coward · · Score: 0

    This makes me wonder, we all have such rather different strategies for commenting code, why not put it in a blog, like how liz taylor feels about this or that, maybe that's the type of comments we need!

  70. Next on his list of things to write about by deblau · · Score: 2, Funny

    Successful Strategies for Crashing Your Website

    --
    This post expresses my opinion, not that of my employer. And yes, IAAL.
  71. Hasn't this been covered already? by dalutong · · Score: 1

    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?

    --

    What comes first, finding a teacher or becoming a student?
  72. Environment variables... by Saeed+al-Sahaf · · Score: 1
    To go any further, I'd need to add 10-30% more time on every source file, which is not an option given the production pace in my environment.

    I would imagine that the type of work environment has a lot to do with the amount and quality of commenting as well. For example, I don't work in a commercial production environment; I do R and D in a government agency, which means fairly soft deadlines. I have a lot of respect for people that pump out apps that actually work, and am fairly forgiving of bugs in commercial software for this reason.

    --
    "Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
  73. Comments hurt your job by null-sRc · · Score: 1

    If you comment your code too well, you become replacable.

    If you comment your version, and strip them out (maybe strip every other comment?) you become more of an asset since you will be the only guy that knows how your code works.

    Sad to resort to these tactics, but it's also sad that your boss will fire you in a whim if he can replace you with a $10/hour new grad.

    --
    -judging another only defines yourself
  74. Note that there are actually government standards by Anonymous Coward · · Score: 0

    We used to have a template (taken from some government standard or other) for a hugh block of comments to be dumpped on the front of each new program we did for government contracts.

    Picky, stupid items, but actually usefull 20 years later when someone else had to take it up.

  75. Doxygen all the way by Radius9 · · Score: 1

    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 structured.

  76. Literate Programming by bsd4me · · Score: 2, Interesting
    --

    (S(SKK)(SKK))(S(SKK)(SKK))

  77. Use intuitive functions... by Sam+Nitzberg · · Score: 1

    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 ;-)

  78. disagreed on a number of points by Surt · · Score: 1

    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, you decrease the likelyhood that you'll use a long descriptive name, and you don't add any information: type information is already available in the variable declaration. Worse, if you do change types, and don't change the variable signature, then you're potentially introducing misleading information.

    Likewise, end of function tags are bad because they can be misleading, and they don't add information that is not available from brace structure (and in any reasonable modern editor, you can easily reformat all text to correct brace indentation).

    Similarly, excessive inline commenting can lead to readability problems: if you have too many comments, how do you tell when the author is trying to communicate something important? For example I consider: // Continue original attack if still alive
            if(isAlive) {
                    isAlive = attacker.attack(defender);
            }

    A bad comment. It's essentially documenting the usage of the if conditional. The if conditional is self explicit. If there is something interesting about the logic of doing this, perhaps it ought to be code explicit instead:

            if(isAlive) {
                    isAlive = attacker.continueAttack(defender);
            }

    Also, for your header comments, you'd be very smart to adopt javadoc compatibility, even for c/c++ code. There are lots of tools that make that a smart move.

    --
    "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    1. Re:disagreed on a number of points by Ricdude · · Score: 1

      I'm the kind of nut that likes (a variant of) Hungarian notation. And I typically have to break my for loops over two lines because I use very descriptive names for my variables, so they aren't really mutually exclusive. When properly followed, it makes this error perfectly clear:

      m_fComplete_pct = 100.0 * ( complete / iTotal );
      Oh, yeah, integer division truncates, and doesn't round. Also, note the unit specifier on the variable. Makes it easier to track time variables in particular (seconds? nanoseconds? timeval?).

      Some people like to complain about having to go change all the references when the type changes (you have). However, I find that if the type can be easily changed from one to another (e.g. double to integer), it's usually worth double checking the logic everywhere that variable is referenced anyway.

      My personal preference for my version of Hungarian notation is based on many years of fixing other people's broken code, and trying to avoid making the same boneheaded mistakes myself. My Hungarian style tells me, at a glance, a variable's scope: m_fComplete_pct is a member variable of a class, complete is a local variable, iTotal is a procedure argument. If it's not a local variable, the type is also indicated: m_f... is either floating point or double, iTotal is an integer. nTotal would be an unsigned integer. Local variables are defined close enough that a page up or two will usually indicate its type. However, in a larger inheritance hierarchy, there's no telling where m_f... would have been defined, so it's handy to drag around its type as well.

      There's a lot more to it than that, but rather than post the whole document, I'll just leave you with the jist of it. The key is consistency, whatever approach you find working for you.

      --
      How's my programming? Call 1-800-DEV-NULL
    2. Re:disagreed on a number of points by Surt · · Score: 1

      Certainly postfixing something like pct makes sense, that's contextual information about the variable that clarifies its undocumented meaning.

      Prefixing m for member and f for float though is inviting error in my opinion, particularly when someone less careful than you comes along and starts working with your code. Far better to do your code development on an editor that can give you that information straight from the declaration (vc, eclipse, idea and i'm sure many others can all do this in context). I would also tend to think that the given error would most likely be discovered when the value turns out to be zero, if you've already managed to make the mistake of doing integer division in the wrong order. It seems possible it might rescue you from making the mistake in the first place, but that's not a very typical type of error for people to have problems with (IMO).

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    3. Re:disagreed on a number of points by Ricdude · · Score: 1

      I do find the prefixes helpful, but you really do need to be religious about it. I've convinced some of my coworkers to try my style, and the few who've made a serious commitment to it think it's improved their work.

      You'd think that double vs. float thing would be easy to catch, but when you're trying to solve a set of 16 non-linear equations (i.e. 16 variables, with a screen full of calculations), it makes it easy to catch which of the 50 divisions is the one causing you problems. Or, at the very least, if you don't include (or can't easily find) the type information, it makes it really tricky to figure it out.

      Editors and environments have improved somewhat over the state of affairs when I was working on that system, though. It might not be as useful now as it was then. I'll have to look into eclipse, as I've heard wonderful things about it. It may take some training to keep my fingers from the emacs shortcuts, but if it's worth it...

      --
      How's my programming? Call 1-800-DEV-NULL
    4. Re:disagreed on a number of points by Surt · · Score: 1

      There are definitely advantages to editors beyond emacs, particularly since most of them support emacs key maps. When I want to know the type of a variable, I just mouse hover over it. Definitely try out eclipse .. though it's not the best, it is free, and it can automate an amazing amount of work.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
  79. Favorite College Assignment Comment (true) by j-tull · · Score: 1

    From a senior OS student in his shell programming assignment: /*Drunk. Fix later.*/

  80. great quote by Anonymous Coward · · Score: 0

    I read a great quote once, probably in someone's slashdot sig:

    Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. - John F. Woods

  81. Just Don't by cratermoon · · Score: 1

    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.

  82. Tombola! by TimTheFoolMan · · Score: 1

    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

  83. comment my CODE??? by AVryhof · · Score: 1



    Later on. . .

    *scratche head* Hmm....why doesn't my Important Information show up?

    1. Re:comment my CODE??? by AVryhof · · Score: 1

      HAHAHAHA, That's funnier than my comment actually working... I commented out a function ans posted it and the damn thing didn't show up.

  84. Unmaintainable code by Spez · · Score: 1

    If you want to write perfectly unmaintainable code, you should follow these guidlines

    They explain how to write perfectly unmaintainable code. Suggestions range from naming variable (re-using variables outside of scopes, using single lettre names, using people name), camouflage (using #defines, etc), and many other perfectly normal (albeit evil) strategies

    --
    I wouldn't mind you in my head, if you weren't so clearly mad -Lews Therin Telamon
  85. Successful commenting... by pieterh · · Score: 1

    It's as much about what you leave out...

    The biggest mistake people make is to use comments to try to explain unreadable code. It fails because the comments invariably fall behind the code and after a while become worse than useless.

    My advice:

    1. Comment all variables
    2. Be 100% consistent with variable names so that the same data always has the same name
    3. If your code is too complex to understand without comments, rewrite it and keep rewriting it until it's clear
    4. Comment the unusual, do not comment the obvious
    5. Style, clarity, and consistency in your code are worth much more than comments.

    In summary: if you write code so that it looks *perfect*, very often it will be perfect and comments will be superfluous.

    Writing perfect code is hard work. I do it. Few on my team can, but it's always worthwhile.

    Ironically, we also rewrite most of our code many times. The biggest benefit from consistency and clarity comes not from getting working programs but from getting code you can lift and reuse with trivial effort.

  86. Most common strategy by CrazyTalk · · Score: 1

    None.

  87. Abu Ghraib style comments by Fr05t · · Score: 1

    if(!comments)
    {
        return brokenlamp + testicals;
    }

  88. Formatting by Java+Pimp · · Score: 1
    // make sure you test your code comment exampl
    // submitting it to a site using css might cho
    // end of your comment lines leaving you looki
    // stupid.
    --
    Ascalante: Your bride is over 3,000 years old.
    Kull: She told me she was 19!
  89. Obfucksucated code contest by jurt1235 · · Score: 2, Funny

    This kind of reviews are really destructive for my goal of winning the obfuscated code contest (http://www.ioccc.org/ can not read any further.

    --

    My wife's sketchblog Blob[p]: Gastrono-me
  90. Midnight apertyx by Kohath · · Score: 1

    /* If you're reading this comment, that means I
       am dead.  Go to the Wells Fargo bank on
       Huffman street in Peoria, Illinois and open
       my safety deposit box

       ...

       find the decryption key to decipher the rest
       of the comments in the code.  They will
       provide further clues

       ...

       stage of enlightenment, you will understand
       the purpose of this code.  I think you'll
       find the algorithm interesting. */

  91. Code explains comments by ewg · · Score: 1

    I had a coworker whose comments were so obscure, you had to read the code to understand what he meant.

    --
    org.slashdot.post.SignatureNotFoundException: ewg
    1. Re:Code explains comments by Syrae · · Score: 1

      I had a professor whose comments were so poorly writen that I had to wade through the code that was poorly explained to understand that the code itself was poorly written and I should have just Googled for a simpler implementation in the first place.

  92. My Advice by bobej1977 · · Score: 1
    Use UML object models and do all of your high level comments (Object, Method) in there. Use a code generator (or write your own, a UML designer with XML file format makes this actually quite simple) that spits your comments into the code.

    In this way, you get a nicely documented design that's written right where the developers need it (in the code), you enforce your (presumably good) design with the team as a whole by laying out all the important objects and functions ahead of time, you remain at a high level in comments (since no code is written yet) that is more likely to include information about how functions are used and interact, and you don't force the developer into the position where they have to explain what you, the designer, were thinking.

    When you get down to coding, you block out the code in pseudocode comments before you start to coding. I usually like a comment every 10-12 lines of code.

    The only pain in the ass is keeping comments up to date as the design evolves, but until there is such a thing as a true Visual IDE (think UML compiler) not much to be done about it except to hound people to do it.

    --
    The meek shall inherit the earth, in 3 by 6 plots. - Lazerus Long
  93. Commenting perl by svanstrom · · Score: 1
    their horribly written Perl

    Perl is beautiful, the problem is reading perl written by someone without a style of his own...

    When a logical person with a clearly defined (perl)style of his own writes perl, the code itself becomes to greatest comments you could ever want.

    It might take a while to get used to his style (esp. if the code is more "advanced" than you're used to, and there's a lot of it); but once you're used to his style it's a lot easier to just read the code, than to have to read comments and figure out how they related to the actual code.

    --
    perl -e'print$_{$_} for sort%_=`lynx -dump svanstrom.com/t`'
    1. Re:Commenting perl by lukewarmfusion · · Score: 1

      I'll give you that. I'm new to Perl - so that's probably part of it. But this code was modified five or six times over the last six years and was neither clean nor elegant. It is probably 20 separate files (HTML and Perl) and 2000 lines of code.

      Oh well. I hope to replace it with PHP or ASP (one file, approximately 500 lines) in the next few months. While Perl has excellent uses, this is not one of them.

      I usually try to make my code self-explanatory (and thus comment-free) except on complex areas or custom functions.

    2. Re:Commenting perl by geoffspear · · Score: 1

      Right, and Finnegan's Wake is a beautifully-written novel that's easy to read once you're used to Joyce's advanced style.

      --
      Don't blame me; I'm never given mod points.
    3. Re:Commenting perl by svanstrom · · Score: 1

      It is probably 20 separate files (HTML and Perl) and 2000 lines of code.

      [...]

      I hope to replace it with PHP or ASP (one file, approximately 500 lines) in the next few months. While Perl has excellent uses, this is not one of them.

      Weeeell... Since perl can be used for a lot of things and in many different ways, it's very easy for people to use it the wrong way; and if people just keep adding to what started as maybe a quick hack, then things can pretty quickly get ugly.

      Before switching to PHP or ASP, go have a look at Mod perl; it might not be right for your situation, but it might also change your view on what perl is/can do.

      --
      perl -e'print$_{$_} for sort%_=`lynx -dump svanstrom.com/t`'
  94. Lazy + Arrogant vs Lazy + Humble by Anonymous Coward · · Score: 0

    I agree completely with your statement. I only comment because I've learned that 6mo down the line, I won't immediately remember all of the details, particularly if it involved some subtle interactions or assumptions. So I comment because I am humble enough to realize that I'll forget, plus lazy enough not to want to do that work over.

    However, until you reach that realization, most folks are arrogant enough to think that they will remember all of the details and lazy enough not to want to do the work now ...

  95. Of course, most slashdot readers by callipygian-showsyst · · Score: 1

    REM MOST /. Readers
    REM would write comments
    REM like this

    ' and maybe some very advanced ones
    ' would use this

  96. torrent? by OsirisX11 · · Score: 1

    torrent?

  97. less comments, clearer code by Uksi · · Score: 1

    Write smaller methods. Give those methods clear names. Give clear names to identifiers. Do not repeat the type in the identifier name if it doesn't help identify the purpose of the identifier.

    All of these steps lead to code much clearer than similar comments, in my experience.

    1. Re:less comments, clearer code by MickoZ · · Score: 1

      I completely agree with you there. The best documentation should at first be the code. So always try to make the most readable code (when you can) and that code being the comment itself.

      You should also know from now, that a comment is not good if you don't update it. Some people tend to update the code and not update the comment (if there is too much comment, you can be they will get desynch too. I don't want to comment all line of code, but block of code that is ok.)

      However, there is moment (time pressure, bad code hack, etc.) -- where comments are really helpful, at less as personal notes.

      Now if only I could read the slashdotted article!

  98. Comments: Why, Sometimes What, Never How by Bob9113 · · Score: 2, Interesting

    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.

  99. commenting conditionals by kae_verens · · Score: 1

    I'm as guilty as the next folk of not commenting my code. However, I've found that the new Folding ability that vim has really helps me to get into the habit. I tell the editor to fold all {..} blocks, then I can comment arbitrary blocks of code.

    Here's a block:

    var x=x2-x1;
    var y=y2-y1;
    var x2=x*x;
    var y2=y*y;
    var dist=Math.sqrt(x2+y2);

    And here it is, commented:

    /* dist = distance from (x1,y1) to (x2,y2) */ {
    var x=x2-x1;
    var y=y2-y1;
    var x2=x*x;
    var y2=y*y;
    var dist=Math.sqrt(x2+y2);
    }

    In vim, that folds up into this:

    /* dist = distance from (x1,y1) to (x2,y2) */ { ----
  100. I don't like comments by OrangeTide · · Score: 1

    I prefer a design spec before any code is written. And code without comments. and revisions to the design spec to reflect any *minor* changes that happened during implementation.

    If you're really lazy putting a short comment infront of every function describing what it does and what it returns is fine. But if you have to describe what the function does maybe you need a less complicated function that can easily be described in its own identifier.

    Comments can rarely be trusted anyways. Often code is updated, and nobody bothers to update the comments because they don't care or they aren't even sure what the comments mean. At least with a design spec you have a way to track the design and implementation indepedently. A design spec is always out of date, but at least you know how out of date it is. (please put revisions and dates in your design spec, if your source control doesn't do it for you).

    --
    “Common sense is not so common.” — Voltaire
  101. Slashdotted by Kremit · · Score: 1

    -   /* Slashdotted? */
    +   echo "Slashdotted!";

  102. Klingon warrior by Anonymous Coward · · Score: 0

    We do not have parameters, we have ARGUMENTS. And we ALWAYS WIN THEM!!!

    1. Re:Klingon warrior by Anonymous Coward · · Score: 0

      We do not "release" our software - it escapes, leaving a bloody trail of QA engineers in its wake.

    2. Re:Klingon warrior by Anonymous Coward · · Score: 0
      Speaking of a bloody trail...

      You question the worthiness of my code? I should kill you where you stand!

  103. Commenting at School by 1337+man+of+steel · · Score: 1

    I comment because it is 50% of my grade.

  104. Macro-scale commenting by Dormann · · Score: 1
    The article provides some good style, but also some old habits that should probably be downplayed with modern languages. I wish I was taught good commenting techniques while at school. What I was told by nearly every professor boiled down to "Write everything twice. Once in the computer's language and once in human language."

    A software engineer with enough experience learns that objects and functions should have a clear, singular purpose. The names of these functions and objects should convey this singular purpose. You can see why each of us has at some time probably wrestled with the concept of "self documenting code". We've all seen code like this and thought "Thank you, commenter. You must love to type."

    /* Increment the widget's counter */
    void Widget::IncrementCounter()
    {
    ++this->counter;
    }

    I've found that once you have the skill to organize your thoughts enough that functions and object definitions don't ramble on forever, the documentation for each function becomes less important. I would assert that even without looking at the body of the above function, the function's name and scope does a very acceptable job of documenting what's going on.

    With many small objects and many small functions (which is what I see many "good engineers" doing), the heart of your code's behavior lies more in how your objects interact. I've gotten more in the habit of creating macro-documentation just as much as micro. Instead of repeating myself with every line and function, I describe an overview for each tiny system. If you're looking at my object definition, you will see it prefaced with a comment block to the effect of this:

    This object does ____. It may be used for purposes such as ____. It was not designed for _____ because _____. This object relies on these objects _____ for _____. For background on this solution/design pattern/general algorithm, see h t t p : //___________.

    It's nice to be able to revistit some year-old system and have a single paragraph in a predictable location refreshing me on exactly what the hell is going on.

  105. Start in plain english by HellPhish · · Score: 1

    I admit I'm not a very experienced coder, but something I find helpful is to write exactly what I want to happen in the program in plain english. Then I go through it all and translate the english into code. You can easily save all the natural language and turn them into useful comments.

  106. You can do it in VIM. by Anonymous Coward · · Score: 0

    :set expandtab :retab

    You might need to do :set expandtab=8 or :set tabwidth=8 or whatever, but I think that should do it.
    -gptelemann

  107. doxygen by Wescotte · · Score: 2, Informative

    You still need to know how to write good comments but I find using doxygen is a great tool for generating useful documentation directly from comments in your code. If you haven't heard of it give it a shot.

    http://www.stack.nl/~dimitri/doxygen/ Doxygen homepage.

  108. The Wrong Way by Sparr0 · · Score: 1

    The Daily WTF is an excellent site that catalogs how NOT to write code and comments.

  109. Dammit... by Jonsey · · Score: 1

    If it was hard to write the code, it should be hard to understand the code! It's only fair, dammit. : )

    --
    I assert that my comment is only my opinion, not that of any employer, past, present or future.
  110. English words with Hindi grammar by fabu10u$ · · Score: 1

    Come on, somebody had to say it...!

    --
    They say the mind is the first thing to ... uh, what's that saying again?
  111. Use Log Statements to Comment Too by irritating+environme · · Score: 1

    If you have to log, and really you should for anything even remotely enterprise or product level, then you have to do a lot of log statments (beyond the braindead stuff that AOP'ers do)

    good debug and trace logging statements are about as frequent as comments should be anyway, and the outputted message is usually approximate to the comment message anyway.

    unless you're doing resource-managed trace logging, in which case, you crazy man.

    --


    Hey, I'm just your average shit and piss factory.
  112. Here's a hint... by suitepotato · · Score: 1

    ...don't write things like...

    /* I have no idea what this portion does and I wrote it, but my daughter says it is good so I guess I'll leave it in but I hope my boss never has to read this in court on the stand in a lawsuit */

    Bad idea.

    --
    If my grammar and spelling are off, I am [distracted/tired/careless] (take your pick)
  113. Klingons and code documentation by Anonymous Coward · · Score: 0
    The Klingon attitude to code documentation can be described by the top 12 Things A Klingon Programmer Would Say:

    12. Specifications are for the weak and timid!

    11. This machine is a piece of GAGH! I need dual Pentium processors if I am to do battle with this code!

    10. You cannot really appreciate Dilbert unless you've read it in the original Klingon.

    9. Indentation?! -- I will show you how to indent when I indent your skull!

    8. What is this talk of 'release'? Klingons do not make software 'releases'. Our software 'escapes' leaving a bloody trail of designers and quality assurance people in its wake.

    7. Klingon function calls do not have 'parameters' -- they have 'arguments' -- and they ALWAYS WIN THEM.

    6. Debugging? Klingons do not debug. Our software does not coddle the weak.

    5. I have challenged the entire quality assurance team to a Bat-Leth contest. They will not concern us again.

    4. A TRUE Klingon Warrior does not comment his code!

    3. By filing this SPR you have challenged the honor of my family. Prepare to die!

    2. You question the worthiness of my code? I should kill you where you stand!

    1. Our users will know fear and cower before our software. Ship it! Ship it, and let them flee like the dogs they are!

    1. Re:Klingons and code documentation by tomhudson · · Score: 2, Funny
      1. Our users will know fear and cower before our software. Ship it! Ship it, and let them flee like the dogs they are!
      Bill Gates is a Klingon? I thought he was a Borg?
    2. Re:Klingons and code documentation by trmcdougle · · Score: 1

      Ah, but what species was he before assimilation?

  114. how about expressive coding? by nonword · · Score: 1

    You can go back and forth about which is more important - the code or the comments - but why not harness the capacities of modern programming languages to achieve both? Expressive programming. Well-planned naming conventions and code organization can speak volumes more (and quicker) than the mini whitepapers that often preface blocks of unintuitive code. If the variable 'i' is the current index in the collection, why not just call it 'collectionIndex' afterall?

  115. Comments? We don't need no stinkin' comments! by davidwr · · Score: 1

    Sometimes even copious comments aren't helpful. I've seen too much code that looked like this: // include system header(s)
    #include // main program
    main(
    int argc, // number of arguements in argv array-of-strings
    char **argv //array of string arguements
    )
    {
      magic(argc,argv) //do magic, James said to put it here. He quit last month. Don't laugh, it breaks if you take it out.
    } //end

    --
    Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
  116. Flip the Script by Doc+Ruby · · Score: 2, Interesting

    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.

    --

    --
    make install -not war

    1. Re:Flip the Script by William+Tanksley · · Score: 2, Interesting

      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

    2. Re:Flip the Script by Doc+Ruby · · Score: 1

      Consider that I wrote that code off the top of my head. Of course it could be factored. In fact, the entire algorithm could be revised to take advantage of Perl's grep() and regexp APIs. But you can tell that by looking at the comments, and knowing Perl. My example doesn't show that coding the comments first makes better code. It makes more readable code. Which then can be revised, by the original programmer, after a code review, weeks later, by another team, whatever. The better comments make it easier to write better code. Especially considering the lifetime of the code, including ports (which comments should largely survive, at least the higher-order ones).

      BTW, no one yet has remarked that my code doesn't actually produce anything, because the local-scoped arrays go out of scope at the end of the block. It's not obvious, as scopes come and go without comment as to their contents' expiration. Which is one reason why I have come to detest lexical programming, and am dying for graphical (flowchart) programming. Flowcharts are almost self-commenting, and comments are much more easily related to the data and operations. I'm looking forward to yet another skillset, lexical commenting, going the way of the dodo, or the DCL.

      --

      --
      make install -not war

  117. Geekiest code commentary I've ever written... by StressGuy · · Score: 1

    From the article:

    "Code Commenting - This refers to writing descriptive variable names that are self explanatory."

    I once had to work with the derivative a complex equation that was basically on long complicated polynomial divided by another polynomial, so I did the following:

    hi = [Long numerator polynomial]
    ho = [long denominator polynomial]
    dhi = [derivitave of numerator]
    dho = [derivative of denominator]
    dhiho = [ho*dhi - hi*dho]/[ho*ho]
    ## corny, but I'll remember it

    --
    A goal is a dream with a deadline
    1. Re:Geekiest code commentary I've ever written... by justfred · · Score: 1

      $hellfreezesover = 0;
      repeat until $hellfreezesover { ...code...
      }

  118. Emory and Oglethorpe by pizen · · Score: 1

    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.

    Furrow their brows to express the anger they are feeling? They just need a baby-T and a visor.

  119. Unmaintainable Code Article (Funny) by antdude · · Score: 1

    I got this from a co-worker last week...

    Unmaintainable Code article gave tips from the masters on how you write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldn't be able to maintain the code!

    --
    Ant(Dude) @ Quality Foraged Links (AQFL.net) & The Ant Farm (antfarm.ma.cx / antfarm.home.dhs.org).
  120. No... by einhverfr · · Score: 1

    Good comments should explain these areas:

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


    In any reasonable program, a should be pretty obvious what you are trying to do. If you include descriptive variables and comment names as comments, I can see that. But a dedicated comment? Sorry. If it gets out of sync with your code, you are !@#$ed. I will admit that sometimes I use comments to give some structure to my code and make sure that I am placing stuff in areas where they can be easily read.

    As for why you are doing it. This is the best reason for comments, IMO. Comments that tell you something about why, or what else needs to be done greatly increase the maintainability of the code because they provide a window into what the programmer was thinking when the code was written.

    As for how you are doing it? Certainly not. If you must use comments here, then I think your effort is better spent on code readibility in general.

    When I have to debug other people's code, I start off by ignoring the comments. When I start to ask myself "WTF?" then I look at comments to see if they provide a reasonable explenation. I also read comments before I make changes. But not when I am tracking down bugs.

    I find many programmers provide too many of the wrong types of comments, trying to tell me how their program works rather than telling me why they decided to do one thing or another.

    --

    LedgerSMB: Open source Accounting/ERP
  121. The only comment you need by mattACK · · Score: 1

    // TODO: Comment code.

    --


    "My God, this must be a truly remarkable corn chip, to be so widely and confidently touted."
  122. If you see bad code don't comment, refactor please by BlueYoshi · · Score: 2, Insightful

    OK, it s not always possible and/or desirable. If it is not broken don't fix it. When I see comment in code because the developer don't understand what happening in 8 level deep statement or in the little function of 10000 lines of code, please fix the code.

    there is basic rules to follow; not all exposed here it would be tooooo easy and me way too lazy :) :

    • Think before coding
    • good variable and function names
    • short function is desirable
    • don't do more than 4 level-deep statement
    • use javadoc for describing function and their parameters
    • Think before coding
    • use metrics to analyze code
    • use junit or other technique to have simple example of use of the code.
    • Think about the children^W maintainer
    • Think before coding (did I mention it?)

    Comments are there to

    • javadoc standard formal description for procedure paremeter,...
    • tell Why not How
    • explain code to avoid bugs in a library or third party code (if (UserAgent == NETSCAPE4) heightOfBox = heightOfBox * 10 /7) // to go around "feature" in netscape about the calculation of (...) see [browser bug workaround 3.2.5]
    • place inside method that need to be implemented or overrided
    • to explain very particular code for specific constraint like optimization or obscure technique but that need to be avoided and maybe the comment could be a reference to some more advance documentation

    NB: I know javadoc, junit and metrics is for java but...

    --
    "Use cases are fairy tales..." I. S. 2005
  123. cycnicism will get you nowhere. by museumpeace · · Score: 1

    One company I worked for had a way of dealing with people like you...the rule was:

    if a programmer has become indispensible, fire him!

    that company, I might add, is still in business, unlike some of the biggest [remember DEC?] I have worked for. Funny thing, now that I think of it. I remember trying to read device driver code for RSX-11 that had hardly any comments in it....my point being most of you will be saying "RSX what? whats he talking about?" Uncommented code dies young. and does nothing for the longevity of the company that tollerated its creation.

    --
    SLASHDOT: news for people who can't concentrate on work or have no life at all and got tired of yelling back at the TV.
  124. Argh... That'll teach me to RTFA... by ovit · · Score: 1

    "Code Commenting - This refers to writing descriptive variable names that are self explanatory. This is a minimalist form of commenting, and looks like this:

    function addUserToDatabase(userName, userAge)

    Without any additional information, you can tell that the function will add a user's name and age to a database. A common implementation of this is called Hungarian Notation."

    Hungarian my ass.

    This is Hungarian:
        lpszname

    What he describes is simply good variable naming.

  125. Todo and error comments by justfred · · Score: 1

    I'm working with a mass of code (php, perl) that has no comments at all. Like, none. And generic variable names ($counter, @array). My first task as I try to determine what the code does is to run through it and add comments.

    I tend to use many types of comments. This way I can find and see the #!errors or #?todos - and at least in PHP I can tell long-term //comments from quickie #!comments. //Notes about how the program does its thing

              #dates mod'd, etc.
    /* big notes; headers, etc. */

    //? Todo - Places I need to come back to and figure something out

              #? or I'd like to rewrite for speed, etc.

    //! Error - Places where something is wrong

              #! or an error occurs/might occur

    # (commented-out code)

    /*

    Commented out code

              (big blocks of commented-out code)

    */

    It's fairly frustrating that comment syntax differs btw perl and php since I go back and forth a lot.

  126. The all time winner: Linus by Anonymous Coward · · Score: 0

    After all, Linux 2.6 is mostly obfuscated OpenServer (well, the multiprocessing parts at least).

    1. Re:The all time winner: Linus by jurt1235 · · Score: 1

      That is not really winning, he clearly got help from a lot of people to get it that far. You do not do that by yourself in a weekend or so.

      --

      My wife's sketchblog Blob[p]: Gastrono-me
    2. Re:The all time winner: Linus by Reverend528 · · Score: 1

      Forget Linus. Larry Wall is a 2-time winner of the contest.

    3. Re:The all time winner: Linus by Anonymous Coward · · Score: 0

      Nor on a budget of $100...

  127. Y2K by Durzel · · Score: 1

    I once came across this particular "gem" in a system I was tasked with taking on from a defunct software house: /* TODO: Fix to work after 1999 */

    The system in question was a financial brokerage tool which, needless to say, had plenty of chunks of code that subtracted and added arbitrary numbers to 2-digit years before reconstituting it again. What made it worse was that instead of using established library functions (it was written in Perl), or even custom written functions, these mistakes were repeated and duplicated hundreds of times throughout the codebase.

    To be fair the author had the foresight (laziness?) to comment all of the sections which weren't Y2K compliant with "TODO" comments, which made it marginally easier to fix.

  128. CSS by t_allardyce · · Score: 2, Interesting

    would this be a good time for someone to explain to me why CSS doesn't support // comments, only /* ?

    --
    This comment does not represent the views or opinions of the user.
  129. Variable names by Macrobat · · Score: 1
    I just make sure my variable names are meaningful, and that's all the documentation I need.

    For instance:

    int xIsanIntegerIWantedToMakeItAFloatButBobFromTheUser TestingGroupSaidWeDidntNeedToBeThatPrecise

    Simple, clear, no need for comments.

    --
    "Hardly used" will not fetch you a better price for your brain.
  130. Comments are good, mmmkay? by dens · · Score: 0

    I sure wish the guy who originally wrote the program I'm currently debugging knew what a comment was. He constantly did random weird stuff and never commented any of it. That's real fun -- I now have lots of comments in the code like:
     
    // I have no idea what the point of this is, but it seems to be screwing up {whatever}.
    // I'm going to try to comment this block out to see if it fixes the problem.

    Not to mention the amount of time I have to spend to implement what ought to be trivial changes to this project. ARGH! ;-)

  131. Since When? by nate+nice · · Score: 1

    "Commenting your code is like cleaning your bathroom"

    Since when does my girlfriend comment my code?

    --
    "If you are a dreamer, a wisher, a liar, A hope-er, a pray-er, a magic bean buyer ..."
  132. Ideally by Anonymous Coward · · Score: 0

    commented code should look like it was a technical paper or article. The problem is IDEs and code editors don't support this very well. You really want some sort of view control that lets you keep the comments out of the way. Or some way of annotating the code without cluttering it up, ie. keep the comments out of line unless you want to see them. Hyperlinks maybe. A source file is just a data structure but we haven't progressed very far since punch cards.

  133. more than 60% by lebow · · Score: 2, Insightful

    I recently took a contract somewhere as an 'engineer' where I was probably the only one who had an engineering degree. Also the work I was doing was far from engineering (web programing). Also I've been on interviews where the client sets me up to talk with their "engineer" who probably doesn't even have a college degree. The problem I've run into is that many times the ones doing the hiring have no idea what they are talking about. To them the engineer is the guy who can use the terminal, or can write HTML by hand.
    Another problem ( I think I'm on a rant here ) is that some people say they want an engineer when what they want is a designer, they want someone to make their site look pretty, and they really don't care about functionality. They just figure "Its too technical for me so I must need an engineer."
    (The situation isn't helped by people who use flash and call them selves an engineer)

  134. What's the economic value of comments? by Anonymous Coward · · Score: 0

    Unless the economic value of comments in code is quantified, one should take care not to comment it. I don't know of any study demonstrating this value. Any pointer?

  135. My favorite comment by Jack+Auf · · Score: 1

    IIRC it was in Enlightenment, around v15 or so

    /* Drunk, fix later */

    --
    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety" - BF
  136. What makes you think you can read the comments? by Latent+Heat · · Score: 1
    All humor aside, whenever the discussion of comments comes up it takes on the character of instructing one's disciples on Holy War.

    I can understand where people are coming from that they fume about having code without comments dumped on their laps. On the other hand, how do they know they will understand the code with the comments? Or even understand their own comments a year from now?

    I am more in the lean-comment rely-on-descriptive-variable-and-function-name camp, and if there is commenting, it should concentrate on interfaces or on broad architectural outlines. If I find myself commenting on how I did a hack, I ask if I can rewrite the code in a non-hacky way.

    By the way, for all you Delphi programmers out there, is the VCL source code from Borland commented? Not really. It may have banner copyright notices but it is pretty comment spares. And when there is a comment, it is usually a pretty gross hack they are rationalizing.

  137. Read my sig! by N8F8 · · Score: 1

    See below.

    --
    "God fights on the side with the best artillery." - Napoleon, Marshal of France - speaking truth to power
  138. comments by drfrog · · Score: 1

    first use something like ruby , where commments are turned straight into documentation

    also if your code is using useful variable names and function calls everything should be self explanitory

    less spagetti, more cowboy

    --
    back in the day we didnt have no old school
  139. Write Smaller Functions/Methods by Anonymous Coward · · Score: 0

    In my experience, I've found that a lot of people write functions that are too damn long. Sometimes this is because a shoddy programmer got into a cut-n-paste session when he should have used abstraction, or someone just gets in a hurry and tries to do too much at once.

    I, as a rule, try to limit any one function to a page of code; if if starts to get longer than that, I start looking to see if I can break things down into smaller steps. The benefit of this approach is that functions are small enough to be easily unit tested and the code is short enough that you can't get too confused about what it's doing. Add a header comment describing what the function does, what the inputs are and any gotchas (eg. this function bombs on null input values) and you're golden.

  140. My Reply,; by crovira · · Score: 1

    'No Comment'

    --
    MSBPodcast.com The opinions expressed here are my own. If you don't like 'em... Think up your own stuff.
  141. What about the bug in his sample code? by Dr.+Manhattan · · Score: 1

    He's testing and indexing on "teamCount" but incrementing "i". Am I missing something? Is there something about JavaScript that will make this loop terminate someday?

    --
    PHEM - party like it's 1997-2003!
  142. Comment found in a switch's default by SpeedyGonz · · Score: 1

    // For everything else, there's Master Card

  143. The Ultimate Comment by no_pets · · Score: 0

    Okay, I don't really "code" but I do write scripts. They too should be commented. I prefer to put the date and my initials in the comment as well as what changes or additions that I have made. I usually comment at the top of the script then make a place marker by the section that was modified.

    But, I must admit that the ultimate comment is the name of the file/script itself.

    If it is a script that the boss made me write, then I'm screwed so I name it the obvious like "scriptbossmademewritethatdoesthisandthat". But, on the other hand, if it's a script that I wrote to make my life easier (and this is important) do not name it something obvious that will draw attention to itself, cause questions to be raised, etc. Name it something that will make sense to yourself and not your enim...err... boss.

    For example instead of name naming it "findpayrollfile" name it "whereiswaldo"? BTW I actually did this.

    --
    "A government is a body of people, usually notably ungoverned." - Shepard Book Quoting Malcolm Reynolds
  144. I Predict by Brandybuck · · Score: 1

    I predict, without reading other post, that there will be one or more posts here claiming that comments are bad. Furthermore, I predict that at least one of these posts will be modded up.

    How can I predict this? Easy! We always get them everytime the subject of code commenting has come up on Slashdot. Some will be touting the moral superiority of literate programming, others will be giving anecdotes about excessive comments as an excuse not to comment, and still others will claim that comments are bad because no one ever updates them when they update the code.

    Now let me go read the comments and see if my prediction was correct...

    --
    Don't blame me, I didn't vote for either of them!
    1. Re:I Predict by Anonymous Coward · · Score: 0

      > Somewhere in Massachusetts a village has its idiot back

      Such a resonable comment on the slash dot comments
      from what seems to be a Republican MoFo. A Bush
      supporter capable of intelligent commentary!
      Who knew?

      Ah, by the way, where were those weapons of
      mass destruction? And why are we spending billions
      and thousands of lives just to create an
      islamic "republic" allied with Iran?

    2. Re:I Predict by Anonymous Coward · · Score: 0

      Yet another Democrat posting anonymously from his parent's basement...

  145. How to write unmaintainable code by ari_j · · Score: 1

    How to Write Unmaintainable Code. Enough said. Read it.

  146. Depends on complexity and maintainer knowledge. by Anonymous Coward · · Score: 0

    One reason why the 'code should be commented' versus 'code should be self-documenting' debate refuses to die is that different programmers are exposed to wildly different programming environments. I don't mean languages and IDEs, though that's a factor, but rather things like a) amount of time maintaining code as opposed to writing it, b) amount of time maintaining /other/ people's code rather than own, c) variety of styles seen in other people's code versus everything conforming to strict guidelines, d) variety of application types maintained and most importantly e) raw complexity and counterintuitiveness of the application domain.

    No, you don't usually need much in the way of code comments for your cookie-cutter timesheet app, PHP forum or IRC client. A page or two of overall design documentation probably covers the essentials. But if you're designing a 3D engine, an optimised IP stack or a virtual memory manager then you're probably going to have some serious magic that merits explanation. In my field (experimental artificial intelligence) it's usually extremely hard to understand what other coders are doing even in principle, and detailed comments are damn near essential.

  147. Every bit of code I write includes the following.. by mmell · · Score: 1
    # This comment serves no purpose.

    Nobody has ever asked me about it - I wonder if anybody has ever seen it?

  148. Comments translating assembly into C by Shazow · · Score: 1

    I found it useful to comment segments of my assembly code with its C (or your favourite more readable language) counterparts, since it's easier to read.

    This way, I'd have a column in assembly, and a column of C code doing the same thing (commented out), so I can figure out what's going on.

    - shazow

  149. Smalltalk documentation by crovira · · Score: 1

    doesn't even come close to being complete without some discipline. (Sort of like B&D/S&M for your code. :-)

    I've found that while you can come up with 'accurate'
      class 'noun' names, and sometimes meaningful
    - class,
    - classInstance and
    - instance variable 'moun' names, and sometimes meaningful
    - class and
    - instance method 'verb' names, and once in while an insightful
    - method parameter 'adjective' names,
    they are NEVER placed in an explicit context.

    That gives me 'cerebral hives' when the darn thing blows up because something happens that you weren't expecting.

    I write my comments in a class method called 'comment' where I describe all of the other classes that this class is expecting to collaborate with.

    Then for each variable, I describe what classes it can be expected to hold as a value.

    Then for each method, I describe the inputs, if any, (and what classes they can be expected to hold) outputs, if any, (and what classes they can be expected to hold) and a description of the algorithm implemented (not the algorithm itself).

    Whenever, in a method, I have an internal loop of any size (like 2 lines sometimes), I break if into a separate 'loop method' (subject to the same 'verb' naming constraints of the method of origin.)

    I use accessor methods (all variables are provided with a 'get' and a 'set' method which really don't need *much* documetation :-)

    Sometimes, I create 'aggregator' classes for the parameters in and out in the package or parcel.

    Then before I release the code, I go back and make sure that the changes are reflected in the class comment.

    --
    MSBPodcast.com The opinions expressed here are my own. If you don't like 'em... Think up your own stuff.
  150. Here's a handy tip by gooogle · · Score: 1

    If you're going to comment out an entire block of code, do it as: /*
    foo
    bar //*/

    now if you want to uncomment the whole block, you simply add another whack to the top comment //*
    foo
    bar //*/

    foo bar is no longer commented out. this comes in very handy when commenting/uncommenting entire blocks of code.

    --
    -- Binary Finary
  151. Joke by Coppit · · Score: 1

    Comments are like sex. When they're good, they're great. When they're bad, they're better than nothing.

  152. I agree completely by benhocking · · Score: 1

    Comments shouldn't tell you what the code does, they should tell you what you wanted the code to do. That way, if there's a bug and what the comment says the code should do disagrees with what the code is actually doing, then you know you've likely come to the right place!

    --
    Ben Hocking
    Need a professional organizer?
  153. frotz the grue by Anonymous Coward · · Score: 0

    I like the idea of putting completely random nonsense words, often things taken from games, in strange places, just to make people wonder what the hell I was thinking when I wrote it, even though I write otherwise intelligible code.

  154. Comments are very helpful for... by Lodragandraoidh · · Score: 1

    I find it extremely useful to document the data structure returned from some funky API call - particularly useful for date/time constructs and other things where what is returned is not at all intuitive and/or riddled with exceptions:

    # The datetime() subroutine in date.pm returns the following array items:
    #
    # 0 = year in blecherous two digit format: 05 = 2005 or 1905 (need conversion utility for that!)
    # 1 = month in the following format: 0=January, 1=February, 2=March, etc...
    # 2 = day of the month. Note: days 10 have no leading zero!
    # 3 = day of the week in the following format: 0=Sunday, 1=Monday, etc...
    # 4 = hour. Note: hours 10 have no leading zero!
    # 5 = minute. Note: minutes 10 have no leading zero!
    # 6 = second. Note: seconds 10 *DO* have leading zero!
    import date;
    @mydate=datetime;

    Later, when I have to extract the data out of the array - or more importantly have to troubleshoot why the output date/time information is off, I can easily interpret the results (e.g. why is $mydate[0] a 4 digit number? Did someone change the library module?).

    # Note: Non-functional example code for illustrative purposes only...

    --

    Lodragan Draoidh
    The more you explain it, the more I don't understand it. - Mark Twain
  155. Threadeds theory of coding states... by threaded · · Score: 1

    Threadeds theory of coding states that a High Level Language is only for communicating what you intended for the computer to do to another programmer.

    What the computer actually does although superficially adhering to what the programmer intended does at numerous points diverge.

  156. Inadequate by cdn-programmer · · Score: 1

    I glanced through the essay and while there are some good suggestions the suggestions are inadequate.

    Lets look at the function call for instance.

    1) the data type of the parameters is not given and the method how these parameters are passed is not given.

    2) we do not know if data is sent into the function via certain parameters or if the function returns data via certain parameters. We have no idea of the valid range of values and what units the parameters are expressed in. With (1) above - we have no idea how to call the function.

    For instance suppose the function is to check the depth of something. We might expect the depth to be passed in as float, but what precision? Is the depth in inches, cm's, meters, feet, KM's? Nasa lost multi-million dollar probes because of this.

    3) there should be a description of the function and any limitations, exceptions etc. in its operation.

    4) preferably there should be some outline of the algorithm used so we know if the function has a chance of performing satisfactorally.

    5) there should be date created and last revision information and a note why and by whom.

    6) we should be able to extract the function documentation in a printed form - preferably with a decompiled call sequence and a list of all functions our function may call - system generated - and suitable for a manual with PAGE FORMATING inserted as requited by the utility that does the extract.

    In this way if an up-to-date manual is required of our library then we can generate it simply and completely and instantly from one source: the code. Look at Doxygen for ideas in this area.

    ----------------

    Consider what would happen if a carpenter documented a house. Would it be appropriate to write notes like: /* Install window frame */ just before the hammer strokes? Well - this is why the analogy between a technical writer's world and a carpenter's world is weak at best even though it is overused.

    However - the construction of a house is usually documented and its called the blue prints. Most carpenters do not dive into the construction of a house without a blueprint (although some can do a masterful job even if this step is skipped). Unfortunately most programmers are too optimistic.

    The best program documentation is done BEFORE the program is written and takes the form of the skeleton I described about. With this skeleton in the form of comments in the sources - the library manual(s) can be printed off and reviewed and it becomes apparent to all what the library is going to do and how it is going to do it. Weaknesses can be easily corrected often before any significant amount of code has been committed.

    Also with the code in the sources we are left with the situation that inconsistancies can be corrected easily.

    BTW - I have written the vast majority of my code in this fashion for the last 20 years and it has saved my bacon many times. Also being in the position to tell management that a fully up-to-date manual can be printed off at any time with an hour's notice seems to instill a lot of confidence.

  157. "Don't insult anyone's intelligence" is key by Pheersome · · Score: 1

    I was a grader last semester for an upper-division operating systems course that I'd taken a couple semesters earlier. Here's my implementation of a certain function:

    int lock_do_i_hold(struct lock *lock)
    {
      return curthread == lock->holder;
    }

    Here's how it was implemented in one of the assignments I was grading:

    int
    lock_do_i_hold(struct lock *lock)
    {
            /* if am holding the lock to this thread */
            if (lock->curthread == curthread)
            {
                /* returns true if the lock is being held */
                return 1;
            }
            else
            {
                /* false if not */
                return 0;
            }
    }

    It took great strength of will to keep my grading comments civil.

    --
    Better to light a candle than to curse the darkness.
    1. Re:"Don't insult anyone's intelligence" is key by pommiekiwifruit · · Score: 1
      Too K and R!

      Why not have the signature:

      bool lock_do_i_hold(const struct lock* lock);

      To make the types more obvious :-)

  158. Maintaining Comments is EXPENSIVE by lordmage · · Score: 1

    Fix a bug and then fix the comments..

    Lots of Comments are a big hassle.. I am willing to say around 20% Maximum of your code should be extra comments.. the rest better be in the code.

    Maintaining comments is just as bad as code.

    --
    I can program myself out of a Hello World Contest!!
  159. If you didn't get it already by tod_miller · · Score: 1

    Code should be a mix of self commenting, and comments where a non-obvious work around was applied.

    Here is the answer to your question:

    public int getAge() {
        return age;
    }

    public int getNumberOfDaysUntilNextBirthday() {
        return nextBirthday - today;
    }

    You see, self documenting, now a bad example: (IMHO) /**
      * Dispose method that calls a cleanup method.
      * This method is called when the object is
      * disposed
      * @author Suck
      */
    public void dispose() {
        cleanup();
    }

    You see, bad because: the comment is bigger than the method, the person who wrote the comment didn't even write the method, but put an attribution for writing this comment... the existence of a comment would draw undue attention as a seasoned programmer would think it must be a special case to warrant such an epic description. The method itself is a simple built in method overridden to possibly cleanup some resources in a nice error friendly way (in case of borking). The comment literally describes the code, not the function (syntax not semantics). The person who wrote it was an arrogant twat.

    I could go on, but an example where code is necessary is when you want to clarify the possible return conditions (if a method is null safe etc)

    if you do have a largish method, write the meat of it in a line, so you know how to use it. If you have a 10 parameter graphics method that draws a boofork on the screen, desribe those parameters, dont write:

    @param String[] args The arguments

    tsk. Code should be written neatly so it is self commenting like:

    if (condition)
        loads of lines of code
    else
        loads of lines of code

    becomes

    if(condition)
        callMethodA();
    else
        callMethodB();

    Now a maintainer would see, ok, if X then this or that, and can skip over now, as the NAME of the method becomes a nice double edged weapon - it comments the code, and removes the complexity from the method, and now you have two simpler methods with nice names that say what they do.

    A method that should be called checksTwoConditionsAndThenDoesTheAppropriateAction sAndReturnsTheRightValue obviously might need some reworking if it is too complex, an can be broken up neatly.

    It helps - software engineering is more like writting a novel than building an engine.

    To confirm you're not a script,
    please type the word in this image: groups

    --
    #hostfile 0.0.0.0 primidi.com 0.0.0.0 www.primidi.com 0.0.0.0 radio.weblogs.com
    1. Re:If you didn't get it already by RetroGeek · · Score: 1
      if (condition)
          loads of lines of code
      else
          loads of lines of code
       
      becomes
       
      if(condition)
          callMethodA();
      else
          callMethodB();


      Yes. Except where there are a LOT of variables being used in the intervening code. Then the method signatures for callMethodA() and callMethodB() become really long, and add to the run time.

      Life is full of compromises....
      --

      - - - - - - - - - - -
      I am a programmer. I am paid to produce syntax not grammar. Deal with it.
    2. Re:If you didn't get it already by pommiekiwifruit · · Score: 1
      That's what macros are for

      *ducks*

    3. Re:If you didn't get it already by petermgreen · · Score: 1

      * Dispose method that calls a cleanup method.
          * This method is called when the object is
          * disposed
          * @author Suck
          */
      public void dispose() {
              cleanup();
      }
      did this comment by any chance begin with /**

      this looks like a javadoc comment. The idea of javadoc is to keep the source for the documentation and the code together in a single file to increase the chance that the documentation actually gets updated when the functionality changes.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    4. Re:If you didn't get it already by junkgui · · Score: 1

      Thats what value objects are for... *ducks, but doesn't feel that he should have to*

    5. Re:If you didn't get it already by RetroGeek · · Score: 1

      Sure, but who sets up an object for local variables?

      I follow rules where they make sense. OOP is OK, except where it is not. If the logic process makes OOP awkward, well use procedural.

      I find it makes code easier to, well, code, and much easier to read.

      --

      - - - - - - - - - - -
      I am a programmer. I am paid to produce syntax not grammar. Deal with it.
    6. Re:If you didn't get it already by tod_miller · · Score: 1

      I know, but this was a redundant method to comment, that was my point. I know javadoc.

      --
      #hostfile 0.0.0.0 primidi.com 0.0.0.0 www.primidi.com 0.0.0.0 radio.weblogs.com
    7. Re:If you didn't get it already by tod_miller · · Score: 1

      Then the method signatures for callMethodA() and callMethodB() become really long, and add to the run time.

      It will not have any impact on performance, if you want to 'final' the methods, go ahead (the byte code will be indistinguishable then), but any programmer (who is not working on real time or signal processing applications, FFT's, or wavelet transforms or fractal processing) who thinks about performance before he sees a performance bottle neck is not a programmer. He is a PHB.

      --
      #hostfile 0.0.0.0 primidi.com 0.0.0.0 www.primidi.com 0.0.0.0 radio.weblogs.com
    8. Re:If you didn't get it already by petermgreen · · Score: 1

      if your going to use something like javadoc you really have to put a javadoc comment for every function otherwise functions will be missed from the documentation.

      this is true even if what the comment says would be obvious from reading the code.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    9. Re:If you didn't get it already by RetroGeek · · Score: 1

      Um, performance is always in the back of my mind.

      I am not saying that I spend huge amounts of time, but I AM aware of it. Good programmers are.

      But you are right that the methods could be made final. But still, reading code where methods have more than 5 parameters, the method should be using an object instead. Which brings me back to my original point.

      --

      - - - - - - - - - - -
      I am a programmer. I am paid to produce syntax not grammar. Deal with it.
    10. Re:If you didn't get it already by tod_miller · · Score: 1

      Did I say they need 5 parameters? I am just saying if you have a block of logic, readability can sometimes be improved by naming two methods the outcome of one key decision block, then the rough work gets done, but you keep the individual method simple, so when someone wants to double check a part of that method they can easily ascertain (human readability) the intent, and logic of that method (and if it is null safe, handles certain conditions you are checking for).

      Yes, it isn't for 100% of the time, but I didn't say that.

      --
      #hostfile 0.0.0.0 primidi.com 0.0.0.0 www.primidi.com 0.0.0.0 radio.weblogs.com
    11. Re:If you didn't get it already by tod_miller · · Score: 1

      You can have empty Javadoc comments, and I am not ENTIRELY sure you are correct - does javadoc binary reflect all methods, even those without comments?

      If it doesn't, then there are still empty comments - and I am not 100% for or against Javadoc, I preffer the code is clear and readable, but on top of that I appreciate Javadoc immensly (just look at some good example Javadocs in the JDK itself and many libraries)

      --
      #hostfile 0.0.0.0 primidi.com 0.0.0.0 www.primidi.com 0.0.0.0 radio.weblogs.com
  160. Humor! by spaceman375 · · Score: 1

    Yes all the other well meaning advice is good, some of it essential to good code/comments. But it always pays to put some humor into your code, be it funny variable names (that don't sacrifice clarity!) or entertaining commentary. With proper variable assignment, I've written lines that said open("the_pod_bay_doors", HAL) else print ImSorryDaveICantDoThat;
    My favorite opportunity is when you want to say something to the user and have them hit the any key so you can continue. The input statement needs a variable, the enduser will never see it's name, and you'll never need to reference it anywhere. Perfect for one liners laid like a bomb waiting for some co-worker to find. "Ira_eats_pork", "Diane_wears_army_boots", and "Kamal_loves_the_Backstreet_Boys" have all brought great exclamations from other cubicles where I've been working.

    --
    On the one hand you take life too seriously, and on the other, you do not take playful existence seriously enough. Seth
  161. A long time ago in another ... by muchtooold · · Score: 1

    In the late 60's a friend came up with a comment that has lived with me since (on an assembler code electronics equipment simulator) " Don't touch the r-register" We worked hard to fit the stuff in the available 8k or so words (18 bits?) in those days.

  162. His examples are broken by iabervon · · Score: 1

    The example at the end that show how he thinks you should do things are broken. While it is useful to give your variables meaningful names, it is less useful if you give the same variable different names.

    For that matter, I think that, if something is a simple loop counter, it should has a one letter name like 'i', so that someone reading the code can tell at a glance whether you're doing anything unexpected. Also, it's confusing to reuse a variable for a different purpose, and dead assignments are also bad. (isAlive has the liveness of different participants at different times, and ends up with the attacker's liveness if the defender's teammates attacked or if the attacker was killed before attacking, and the defender's liveness otherwise. Also it depends on the variable being initialized silently to true; otherwise, attackers don't attack unless defenders did a preemptive strike that didn't kill them.)

  163. Parent post is spot on. by tshak · · Score: 1

    If I have to comment on what my code is doing, in the majority of cases there is a problem with how my code is written. Comments for why something is done in code is a lot more useful when the why is not obvious. That and API documentation (publically explosed method headers, for example) are where I see comments being uself. The article takes commenting to an extreme, and ignores the real problems which create the desire to comment heavily. From TFA:


    function beginBattle(attacker, defender) {
            var isAlive; // Boolean inidicating life or death after attack
            var teamCount; // Loop counter // Check for pre-emptive strike
            if(defender.agility > attacker.agility) {
                    isAlive = defender.attack(attacker);
            } // Continue original attack if still alive
            if(isAlive) {
                    isAlive = attacker.attack(defender);
            } // See if any of the defenders teammates wish to counter attack
            for(teamCount = 0; teamCount < defender.team.length; i++) {
                    var teammate = defender.team[teamCount];
                    if(teammate.counterAttack = 1) {
                            isAlive = teammate.attack(attacker);
                    }
            } // TODO: Process the logic that handles attacker or defender deaths

            return true;
    } // End beginBattle


    All of these comments get in the way of reading the code. However they're required because this method is not written well. The variable names are not self describing. The method also violates the Single Responsibility Principle on multiple counts. The method is also too long (mainly due to the SRP violations). Instead of spending the time mudding up the code with comments, spend the time refactoring the code so that the majority of the comments aren't necessary in the first place. Comments main purpose is to assist a developer in understanding the code. If too much of this assitance is necessary, it is probably due to problems with the code itself; even problems which may have a negative impact on the codebase beyond readability issues.

    --

    There is no longer anything that can be done with computers that is nontrivial and clearly legal. -- Paul Phillips
  164. Re:What makes a good Comment? AGREED 110% vivin by Anonymous Coward · · Score: 0

    Agreed 110%, even from code I wrote only a year or two ago, I too agree on your statement:

    " 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?!'" - by vivin (671928) on Monday August 01, @01:10PM

    You've been there, done it, & from one coder to another? I can tell... been there myself!

    My compliments to you, and well said reply!

    * :)

    APK

    P.S.=> I appreciate especially your comments about Asm NOT being "that intuitive" because compared to HLL's (like BASIC, PASCAL, etc., especially RAD & OOP modern 4th gen stuff) it's FAR from it, & also how you stated that even 'bastardizing' the code (assuming via #defines & Macros), good commentary can get ANYONE (especially later generation maintenance coders) thru it... or @ least help!

    I don't know about you guys, but I contract out a LOT, and have to maintain the code of others. This takes grasping what they were up to, and without comments? Well, it takes more than that it should... commentary, SOLID commentary? Helps large! Right in the code... apk

  165. Ehem .. really bad example by TekGoNos · · Score: 1

    While it was nice to see self-commenting code as the first item, WHAT'S THIS???

      * Return: Boolean indicating life or death
      */
    function calculateHitPoints(cUser) {


    If this function tells me whether the user survives the hit or not, name this function isHitFatal, or something like this.
    Yes, I'm nitpicking. Because this is supposed to be an exemple of a good comment. And while the comment is good, the function name is not.</rant>

    --
    I have discovered a truly remarkable proof for my post which this sig is too small to contain.
  166. Hungarian Notation by peterpi · · Score: 1
    Hungarian notation is wrong.

    Anybody who uses it is a terrorist. (Or a pEvilbeardTrrist, as they like to call themselves)

  167. The real trick... by db10 · · Score: 1

    ...is to put in comments that obfuscate, rather than clarify. I mean, the only people making use of your comments will be: You (ok fine), and the ones that replace you (screwem!). /* pwnage! */

  168. corporate amnesia by grikdog · · Score: 1

    Comments are designed to mitigate brain drain, at least in theory. All management wants comments, but no management is willing to extend a deadline to allow coders to comment. This is a lot like ISO 9660 -- in theory, the procedure manuals match praxis, but in practice, the trolley left for La La Land when the night shift cleaned up the empty plastic champagne cups, and won't be seen again until certificate gets revoked. On the other hand, the guy most likely to appreciate the distance between documentation and disaster is you -- but only checking yourself into Four Years Ago will ever help you understand your own notes.

    --
    ``Tension, apprehension & dissension have begun!'' - Duffy Wyg&, in Alfred Bester's _The Demolished Man_
  169. Comments have many functions... by Hosiah · · Score: 1
    But let's not forget the most entertaining: blowing off steam in mid-hack!

    /* Wheee! bsetroot insists on getting it's gradient values in "rgb:xx/xx/xx" format where tk_chooseColor has returned color values in canonical "#xxxxxx" format. So we get to play "sausage-factory" with the strings when we should be done by now! */

    Anybody ever seen the comment header at the beginning of screenhack.h of Xscreensaver fame? Any comment that includes that many appropriate references to Monty Python deserves some kind of award!

  170. /*Deep Breath*/ by ToasterofDOOM · · Score: 1

    In Soviet Russia, code comments you! In Korea, only old people comment code (I, for one, welcome our new code-commenting overlords)

    --
    I am Spartacus
  171. Another commenting maxim by DragonHawk · · Score: 1

    " find the best advice I've ever gotten on commenting code is very simple - Comment the why, not the how."

    Another one I like is:

    "Comments on data are usually much more helpful than on algorithms." -- Rob Pike

    I can't count the number of times where I've been reading through some code which has comments like "transform foo for the analysis loop" and "write foo to the instrument buffer" while all the while I'm wondering, "What the hell is 'foo' and where the hell did it come from?"

    --

    dragonhawk@iname.microsoft.com
    I do not like Microsoft. Remove them from my email address.
  172. Call Bob by DragonHawk · · Score: 1

    We've got a program at work that, once in a great while, aborts with the message, "Call Bob".

    Bob hasn't worked there in years.

    *sigh*

    --

    dragonhawk@iname.microsoft.com
    I do not like Microsoft. Remove them from my email address.
    1. Re:Call Bob by Anonymous Coward · · Score: 0

      Have you considered hiring a new Bob?

  173. sex with a chanisaw, anyone? by thedustbustr · · Score: 1
    Obligatory best comment ever...
    arch/sparc/kernel/ptrace.c: /* Fuck me gently with a chainsaw... */
    --
    This sig is false.
  174. My poor comments by dtfinch · · Score: 1

    // how not to do it

    // planned to fix something here, but now can't remember

    So far I've just been using comments as reminders to myself. Sometimes I don't use any comments at all, and have almost entirely single letter variable names, and the thing works on the first compile. If I do use a lot of comments, it'll be to create a skeleton of something before I fill in the code.

  175. Navigator for Backend data==Lemiwinks by HornWumpus · · Score: 1
    Lemiwinks = BackEnd.CreateNavigator();

    Also point 10a. Threaten the original coder in comments.

    I once told the author of an offending piece of code that if I ever found out who (s)he was I would break all ten of their fingers so they could'nt code again. A page down I told him I would also be breaking his toes so he could not code with his feet.

    --
    John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
  176. This is a fucking unbelievable screwed up mess by HornWumpus · · Score: 1
    Close your eyes and hit page down five times to preserve your sanity.

    Sometimes I think that was the most usefull line I wrote in that whole job. Then I think some more and I'm sure of it.

    --
    John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
  177. Commenting after by oo_waratah · · Score: 1

    When I do analysis I add comments to code as I understand what parts do. If I have spent the time to figure it out, even if I do not need to change the code then my time is valuable and it is worth leaving breadcrumbs for the world to follow later.

    This is the best article on comments I have seen. Not a perscription just a collection of techniques.

  178. Just not too small. by HornWumpus · · Score: 1
    Otherwise you (especially in an OO language) will make everything an object.

    Leaving your code spread in tiny pieces all over the project and bogging your CPU in call overhead.

    The right size for a function? As big as it needs to be. Splitting a single function at an arbitrary point is misguided. Split along functional lines. Sometimes it IS that complicated.

    That said it usually is'nt that complicated and a page or two is a good place to start to look for a place to split on functional lines. But if everything is interdependant leaving the solution in one place to be understood can be a better solution then hiding parts of the solution from the coder.

    Complexity hiding is good. Complexity obfuscation is bad. Reconciling these two points is part of what makes design an art.

    --
    John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
  179. Nice theory by HornWumpus · · Score: 1
    Refactor anything you don't understand? LOL

    The point is you don't understand it. How much time should you spend refactoring working but shitty code? (Knowing that this type of code has usually evolved to the point it is at. No one actually created a public called aLocalArray, someone changed the scope. That is not a joke, I've seen it. See my comments on threats of bodily harm in code.)

    In practice the best you can do is add comments with questions when you don't understand. Hopefully someone who does will add a comment, at least you will be reminded to continue thinking about WTF is going on.

    --
    John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
  180. Linux commenting style by jawahar · · Score: 1

    I believe we can learn a great deal on how to write good comments by studying the kernel coding style at http://lxr.linux.no/source/

  181. Bela and Lugosi by jtcedinburgh · · Score: 1

    Best I saw was in a sorting algorithm. It had some nested loops going on, and two of the variables named as such:

    bela ...and...
    lugosi

    Puzzled, I dug a little deeper and found the curious explanation: // Count variables.

    Boom boom, the children of the night, what music they make...

    John

  182. Bass ackwards by hippo · · Score: 1
    I don't comment my code, I code my comments, it's much better:
    • Writing out the comments first is bug-free.
    • Writing out the comments first is really fast.
    • You don't have to go through and add comments to code you wrote in a panic and don't really understand.
  183. "0 but true" by 00lmz · · Score: 1

    $rv = "0 but true";
    if ($rv) {
        print "yup\n";
    }

    if ($rv == 0) {
        print "uh-huh\n";
    }

  184. The new AMAZING comment plan by lackita · · Score: 1

    That's right kiddies, lose weight, code better, and feel better. Commenting does it all, it's the new miracle cure. All you have to do is spend hours a day adding useless comments to your code like "The function addUser adds a user" and your standard of living will increase ten-fold. While you're at it, why don't you try our miracle weight loss pill; lose 50 pounds in a week and it automatically comments your code for you.

    Seriously though, comments do have their place, but when every line of code is dwarfed by ten lines of comments, it's hard to follow the code. Also, people need to stop taking up entire lines with - and stuff like that. Between that and slashdot, I think I've sprained my mousewheel.