Slashdot Mirror


How to Write Comments

Denis Krukovsky writes "Should I write comments? What is a good comment? Is it possible to comment a class in 5 minutes? See " Everybody knows that good code is self documenting- which is why my prof in college demanded we write in Ada. I instead suggest commenting in haiku.

556 comments

  1. Reading by Southpaw018 · · Score: 5, Funny

    Code should read easy Like many Slashdot comments See? It's not so hard.

    --
    ACs are modded -6. I don't read you, I don't mod you, I don't see you. Don't like it? Don't be a coward.
    1. Re:Reading by Southpaw018 · · Score: 5, Funny

      *grumble* Forgot the
      s.

      Code should read easy
      Like many Slashdot comments
      See? It's not so hard.

      --
      ACs are modded -6. I don't read you, I don't mod you, I don't see you. Don't like it? Don't be a coward.
    2. Re:Reading by jmony · · Score: 3, Interesting

      Problem with Slashdot comments is like code comments... too few is bad, too much is bad. // This line outputs the result

      How many times can we see a line like this... that's just writing comments without any reason.

      I prefer function header comments which describe what the piece of code as whole does. Not everyline, as teachers say it should be done.

    3. Re:Reading by $RANDOMLUSER · · Score: 1

      Silly sysadmin! LART is always true!

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    4. Re:Reading by tallguy81 · · Score: 1

      All the comment rules
      in the world cannot prevent
      The Slashdot Effect.

    5. Re:Reading by The+Famous+Brett+Wat · · Score: 2, Funny

      A race for karma
      Carelessness surely follows
      Always preview first

      --
      proof, n. A demonstration that a conclusion is implied by certain premises and axioms.
    6. Re:Reading by Anonymous Coward · · Score: 0

      You *still* don't get karma for funny posts.

    7. Re:Reading by meringuoid · · Score: 5, Funny

      Post with bad format
      Then rewrite it correctly
      Get double karma

      --
      Real Daleks don't climb stairs - they level the building.
    8. Re:Reading by meringuoid · · Score: 5, Funny
      * bah *

      My haiku is rotten
      I hang my head in sorrow
      Forgot the season.

      --
      Real Daleks don't climb stairs - they level the building.
    9. Re:Reading by Anonymous Coward · · Score: 0

      But you do get your ego stroked, which has about the same value.

    10. Re:Reading by InvalidError · · Score: 4, Informative

      Same for me.

      Having one-liner comments all over the place makes comment maintenance more troublesome and can distract from actual comprehension of what is going on while reading the code, particularly when there are bits of orphaned antique leftover comments. A single comment blob before a function or large code sections tells the reader about the spirit of code to come without interfering with reading beyond there and makes it easier to maintain comment coherence when changes are made.

      For more convoluted code, I often add blobs before major loop/switch/etc. too - adding comments while I write these things takes less time than what it may take me to re-read the code until I remember exactly what it does and how. (inputs, outputs, side-effects, etc.)

    11. Re:Reading by Anonymous Coward · · Score: 0

      Too many people
      Are ignorant of this fact
      "Funny" does not count

    12. Re:Reading by Spy+der+Mann · · Score: 1

      *grumble* Forgot the <br>s.

      Posting on Slasddot
      Always post as 'plain old text'
      See? Not the big deal.

    13. Re:Reading by IngramJames · · Score: 4, Insightful

      an distract from actual comprehension of what is going on while reading the code, particularly when there are bits of orphaned antique leftover comments

      I know this is a religous topic, but I personally would say that old, left-over comments are simply bad practice. Well-maintained comments and well maintained code are the ideal solution. I don't think there's any excuse for not updating a comment which is right there, in the code you're about to change.

      I've suffered from antique comments, and also no comments; IMHO, they are both as bad.

      Feel free to flame me now :)

      --
      'No rational religion claims "supernatural" exists, that's an atheist slander.' - seen on slashdot.
    14. Re:Reading by Anonymous Coward · · Score: 0

      /*
      Haiku is so hard.
      I must try my best to make it happen.
      See? I got it all wrong again.
      */


      Argh...
      I was never a good coder anyway.
      Move along!

    15. Re:Reading by gstoddart · · Score: 4, Informative
      My haiku is rotten
      I hang my head in sorrow
      Forgot the season.

      For anyone not getting this, a traditional Haiku always contained references to the season.

      --
      Lost at C:>. Found at C.
    16. Re:Reading by Dachannien · · Score: 1, Informative

      Six syllables in
      The first line of your haiku
      Also, winter sucks.

    17. Re:Reading by ebh · · Score: 5, Insightful

      Code should tell you what
      And the code should tell you how
      Comment tells you why

    18. Re:Reading by Anonymous Coward · · Score: 0

      +5 - Unintentionally funny.

      In this case, the first one was better, considering the typical post here.

    19. Re:Reading by bgalbrecht · · Score: 5, Funny

      Karma is quite nice
      But funny gets no karma
      Snow falls slowly here

    20. Re:Reading by eclectic4 · · Score: 1

      Profit!

      --

      "The greatest obstacle to discovery is not ignorance - it is the illusion of knowledge." - Daniel Boorstin
    21. Re:Reading by Anonymous Coward · · Score: 0

      Well.... we're waiting...

      How about:

      1) Post with bad format
      2) Then rewrite it correctly
      3) Get double karma
      4) Profit?
      5) Move to Soviet Russia.
      6) In Soviet Russia, the profit owns you!
      7) All your format belong to us.

    22. Re:Reading by Mr.+Bad+Example · · Score: 1

      > Six syllables in
      > The first line of your haiku
      > Also, winter sucks.

      Too many syllables
      Means a defective haiku.
      Return for refund.

    23. Re:Reading by Anonymous Coward · · Score: 0

      1) Write a bad haiku
      2) Add too many syllables
      3) get a PROFIT!!!

    24. Re:Reading by Anonymous Coward · · Score: 0

      Dang. On second thought.

      1) Post with bad format
      2) Then rewrite it correctly
      3) Get double karma
      4) Profit?
      5) Move to Soviet Russia.
      6) In Soviet Russia, the post formats you!
      7) All your profit are belong to us.

    25. Re:Reading by weeboo0104 · · Score: 0

      To give good Karma
      Mod the parent insightful
      Funny does not count

      --
      It is easier to build strong children than to repair broken men. -Frederick Douglass
    26. Re:Reading by Sax+Maniac · · Score: 2, Funny
      I hate one-liners. Here's a fake example of stuff I see all the time:

      if (foo) { /* OHO! */
      if (bar) return; /* Well, well, false alarm. */
      if (!x) /* Class is bogus. */
      z=y; /* Did we already have one? */
      }
      Great, I'm sure this Howard-Cosell running commentary is cute if you already know what the code is doing, but it means nothing to everyone else. Comments are not for you, they are for other people.
      --
      I can explanate how to administrate your network. You must configurate and segmentate it, so it can computate.
    27. Re:Reading by dgatwood · · Score: 2, Funny
      This method is the
      winter of our discontent.
      Hell freezeth over.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    28. Re:Reading by pchasco · · Score: 1

      Beautiful Haiku.

    29. Re:Reading by kula.shinoda · · Score: 1

      Comments are good.
      Are they formatted though?
      That is the question to ask.

      --
      Real men don't write sigs
    30. Re:Reading by David+Gould · · Score: 1

      Sometimes seventeen
      syllables aren't enough to
      express a complete

      --
      David Gould
      main(i){putchar(340056100>>(i-1)*5&31|!!(i<6)<< 6)&&main(++i);}
    31. Re:Reading by dcam · · Score: 2, Informative

      I'd largely agree with this.

      One helpful practice I picked up (see Code Complete, Steve McConnell) was to design functions in advance and use the design a the comments.

      eg
      function foo()
      {
       
      // open input file
       
      // parse into local variables
       
      // print result

      }

      --
      meh
    32. Re:Reading by hanavi · · Score: 1

      Why write in haiku? It takes way too much effort besides it.... summer

    33. Re:Reading by Voice+of+Meson · · Score: 1

      This brings up a good point for code bases of any reasonable size. The majority of the time people will not be reading every line of your code and trying to work out what each line does, but stepping through huge chains of functions trying to work out what is going wrong. (yes I spend a huge amount of time debugging)

      So I find having a huge comment at the start of a function that describes exactly what it does and the inputs and outputs is invaluable. Then you can quickly determine if this is the problematic function or not. Obviously any code that is particularly complex or unobvious (eg using unusual form methods or third party library methods that do magic) should have large commehts. But dont over comment because it just pissed me off. I know the language and if I don't talk to HR because I shouldn't be in the building.

      It's here that I agree with the style that Visual Studio suggest where they encourage you to comment the inputs, outputs, exceptions thrown etc. of each method. It's not always applicable but when it is do it.

      --
      Dammit! I had a good one.
    34. Re:Reading by Canadian_Daemon · · Score: 1

      Mod funny please

      --
      This sig is definitive. Reality is frequently inaccurate.
    35. Re:Reading by Anonymous Coward · · Score: 0

      Code should tell you what
      Code should also tell you how
      Comment tells you why

    36. Re:Reading by @madeus · · Score: 1

      I agree, I always build more complex applications like this (though I haven't had to use it of late due to the type of work I've been doing).

      When you know you'll be writing a large or complex program from scratch, especially one with with quite a few libraries this is a great way to go. Creating dummy functions, with comments indicating what you want to do in each, and indicating what the input and output and end result should be, before you even start any real coding is a great idea.

      It can also prove useful as way of validating or revising your original design, as it forces you to think through the implementation fully and can help you realise potential limitations.

    37. Re:Reading by BlankVerse · · Score: 1

      December moon...
      my commments are lost
      to the wind

      BlankVerse

    38. Re:Reading by Alomex · · Score: 1

      I agree, yet looking over my best code it is the complete opposite: my best code has a nearly a one-to-one line of code to comment ratio... The code is very succinct as most low level instructions have been abstracted into their own methods/subroutines.

      As other have said the comments indicate the strategy rather than the tactics. The tactics are derived from good function and variable names. E.g. if the program iterates over each element of a list object and computes its absolute value should be totally readable from the code. What the comments say is: we compute the absolute value since at this time we only care about the total amount of buckets we need to allocate, later on we will distinguish between positive and negative entries...

    39. Re:Reading by IngramJames · · Score: 1

      "To write a poem
      In seventeen syllables
      Is very diffic"

      -- John Cooper Clarke

      --
      'No rational religion claims "supernatural" exists, that's an atheist slander.' - seen on slashdot.
    40. Re:reading by spring.java · · Score: 1

      If the name of method can tell you what to do, I think that you may not read the comments. because writing comment is very pain......hehe.

  2. Comments by LiquidCoooled · · Score: 5, Funny


    <!-- why don't they ever RTFA? -->
    <b>Nothing for you to see here. Please move along.</b>

    --
    liqbase :: faster than paper
    1. Re:Comments by Anonymous Coward · · Score: 0

      REM Mod parent up.
      REM Yeah, I know this is in BASIC, so bite me

    2. Re:Comments by Golias · · Score: 5, Funny

      /*
      This is my comment. There are many like it, but this one is mine.

      My comment is my best friend. It is my life. I must master it as I must master my life.

      My comment, without me, is useless. Without my comment, I am useless. I must author my comment true. I must write clearer than my code which is trying to obfuscate my efforts. I must comment in before it gets me fired. I WILL...

      My comment and myself know that what counts in this job is not the lines we write, the size of our file, nor the time to compile it. We know that it is the completed change requests that count. WE WILL COMPLETE...

      My comment is human, even as I, because it is my life. Thus, I will learn it as a brother. I will learn its weaknesses, its strength, its words, its letters, its punctuation and its opening & closing tags. I will ever guard it against the ravages of re-edits and cruft as I will ever guard my legs, my arms, my eyes and my heart against damage. I will keep my comment clean and ready. We will become part of each other. WE WILL...

      Before God, I swear this creed. My comment and myself are the defenders of my department. We are the masters of our code. WE ARE THE SAVIORS OF MY LIFE.

      So be it, until the beta goes gold and there are no further patch requests, but sales!

      --

      Information wants to be anthropomorphized.

    3. Re:Comments by Golias · · Score: 4, Funny
      Oh... and this is a closing tag for my comment. ---> */

      // I guess I should have used one-liners.

      --

      Information wants to be anthropomorphized.

    4. Re:Comments by Anonymous Coward · · Score: 0

      You forgot to close the comment. */

    5. Re:Comments by BrockH01 · · Score: 1

      You, sir, are my hero.

      --
      To shreds you say...
    6. Re:Comments by Anonymous Coward · · Score: 0

      Erm... you forgot to close your comment.

      Here, lemme do it for you:

      */

    7. Re:Comments by Anonymous Coward · · Score: 0

      ' Or you could write Visual Basic comments.
      '
      ' I find it handy to write comments first,
      ' and then fill in the comments with some code to go with it.
      '
      ' That way, the code is documented, and I don't forget to write part of it.
      '

    8. Re:Comments by bogado · · Score: 0, Redundant

      And, by closing his comment, you ruined his attempt to mark all of the comments bellow his as his own. :-)

      1) start a coment.
      2) write stating that this is your comment.
      3) don't close the comment, so that your comment is unbounded.
      4) claim copyrigth of your comment.
      5) ???
      6) profit!!!

      --
      []'s Victor Bogado da Silva Lins

      ^[:wq

    9. Re:Comments by zlogic · · Score: 1

      Hey! You forgot to close the comment with */
      And now everything on this page will be commented out.

    10. Re:Comments by artitumis · · Score: 1

      That is the funniest comment I have ever seen. Sad part is I read the first line as the actual Rifleman's Creed instead of what you wrote. :\

    11. Re:Comments by Anonymous Coward · · Score: 0

      Hey! You forgot to close the comment with */

      Hey! You forgot to read the whole thread before clicking on "Reply to This."

    12. Re:Comments by Anonymous Coward · · Score: 0

      Wow, this really works!

    13. Re:Comments by Anonymous Coward · · Score: 0

      "Funny" mods yield no karma.

      At least not in the Slashdot sense of the word.

    14. Re:Comments by MonkWB · · Score: 0

      Parent funnier then grandparent... Now that is funny.

  3. Back in grade 12 by Data+Link+Layer · · Score: 1, Informative

    There was a final project worth 50% of our final grade (it took 3 months todo) I didn't comment and I fail it.

    1. Re:Back in grade 12 by Anonymous Coward · · Score: 0

      I'll bet you failed English, too.

  4. Haiku Commenting? by drewzhrodague · · Score: 4, Informative

    Actually, that would give some of us that have to review code something interesting to look at. Those that think code is self-commenting, forget that there are people like me, who aren't great programmers, who have to either fix your bugs, make simple modifications, or add really simple things. When there aren't comments, it is hard to figure out what parts of what do which.

    --
    Zhrodague.net - I do projects and stuff too.
    1. Re:Haiku Commenting? by mcvos · · Score: 4, Insightful

      When there aren't comments, it is hard to figure out what parts of what do which.

      What parts do what should be clear from the names of function calls and variables, but whenever a function becomes longer than something really short, yes, it needs comments describing what happens where. If a function does something complicated, it's worth starting with a comment describing pre- and post conditions.

      That said, before you add a comment, first check if you can make the various identifiers any clearer. And then still add the comment, unless it's suddenly become really stupid.

    2. Re:Haiku Commenting? by PsychicX · · Score: 5, Insightful

      Possibly the best advice I ever read/heard (I can't remember the origin), is to assume that the guy reading your code is perfectly familiar with the language. (Sadly this is usually inaccurate, but moving on.) So he can see what, mechanically, your code is doing. The idea of a comment is to explain how and why you are doing something. What is usually clear from the function name and accompanying documentation (be it doxygen/javadoc style or MSDN style or something else). I.e. if you have some jacked up mega-compound for-loop, a good comment explains why that loop is the way it is, and how it's achieving its goal (and possibly what precisely it's doing). A bad comment would be "this loop increments i, j, k, theta, and cheez_it until the cheez_it is failing to exceed the sum of i, j and the product of i, j, and k". That kind of information is right there in the code.

      In short, comments convey concepts and explanations, not mechanical descriptions.

    3. Re:Haiku Commenting? by Rorschach1 · · Score: 4, Insightful
      I'd suggest an exception to this for embedded code. When I'm writing something for a PC, sure, there's no excuse for not making the code readable. But when you're squeezing as much functionality as possible into a chip with maybe a couple hundred bytes of RAM and a few KB of flash, things get ugly.

      It's not uncommon for my code to do something really non-obvious to accomplish a task in a more efficient way. Processing sensor readings, for example - on a PC it'd be a simple floating point math operation. On the chips I use, the floating point library would itself fill the entire available memory. Instead, I wind up with a bit of hard-to-read code that accomplishes the same thing using the shift and multiply operations the CPU is good at. For my own sanity I leave very specific comments about what's going on and what the equivalent calculation is.

    4. Re:Haiku Commenting? by Coryoth · · Score: 4, Informative

      What parts do what should be clear from the names of function calls and variables, but whenever a function becomes longer than something really short, yes, it needs comments describing what happens where. If a function does something complicated, it's worth starting with a comment describing pre- and post conditions.

      Now there is an excellent idea! It doesn't take a lot of effort - you should be able to come up with some basic constraints on inputs and outputs if you have any decent idea of what the function does - but it is very helpful documentation to anyone else, particularly for people who have to call the function (as it clerly delimits exactly what they need to provide, and exactly what they can expect to get back). Better yet, as long as you use a system that supports it you can get a whole lot of benefits in terms of automated checking and debugging of your code, saving you a lot of effort later.

      Eiffel and D support pre and post conditions directly in the code (instead of in comments). Java has JML which is a syntax for writing pre and post conditions in comments, as well as some tools to do extra checking, add runtime checks to your code (or not) based on the conditions, write the conditions into JavaDoc properly, and automatically generate JUnit tests based on the conditions. If you program in Ada there's SPARK which supports pre and post conditions as comments as well as a range of other annotations, and provides extremely powerful tools to do extensive static checking and analysis and even generate automatically simplied proof obligations based on your annotations. If you program in Python there's PyContract which allows you to write pre and post conditions into docstrings and switch on or off runtime checking of those contracts. I expect there are plenty more, so hopefully other people can mention those.

      Jedidiah.

    5. Re:Haiku Commenting? by Anonymous Coward · · Score: 0

      Are you a proponent of comments, commas, or both?

    6. Re:Haiku Commenting? by FooAtWFU · · Score: 1, Insightful
      What parts do what should be clear from the names of function calls and variables

      I've always thought that you should be able to tell what is happening from the code... the comments are supoosed to tell you *why* it's doing what it's doing.

      --
      The World Wide Web is dying. Soon, we shall have only the Internet.
    7. Re:Haiku Commenting? by mytec · · Score: 1
      Those that think code is self-commenting

      The intent of code is important and code cannot always make that clear.

    8. Re:Haiku Commenting? by p2sam · · Score: 5, Funny

      The 1st rule of software engineering is: you do not put hacks in your projects
      The 2nd rule of software engineering is: you DO NOT put hacks your projects
      The 3rd rule of software engineering is: document you hacks
      The 4th rule of software engineering is: one hack at a time
      The 5th rule of software engineering is: if this is your first project, you'd have to do lots of hacks. :)

    9. Re:Haiku Commenting? by Achoi77 · · Score: 1
      This is my rule of thumb:

      Work on some code, and totally forget about it. If I can look at the code and understand what I was doing and why, then no need to comment on it; otherwise, put in comments. Then totally forget about it again. Look at the code once more, read the comments, and if I still don't understand what my function/piece of code is doing, then my comment sucks and it needs to be reworded.

      Simple. Of course, the hard part is always 'totally forgetting about it.' Generally what I do for that is either concentrate on another piece of code, or just leave it alone for an extended period of time. If neither options are feasible for me, then I would ask someone else to critique it. If that's not possible either, then I just roleplay a critic when I go over my notes.

      I hope I'm not the only one that does this..?

    10. Re:Haiku Commenting? by Anonymous Coward · · Score: 1, Interesting
      Actually, that would give some of us that have to review code something interesting to look at. Those that think code is self-commenting, forget that there are people like me, who aren't great programmers, who have to either fix your bugs, make simple modifications, or add really simple things. When there aren't comments, it is hard to figure out what parts of what do which.
      I write lots of code and have done so (professionally too :) for over 10 years. When I started I thought good code was self-documenting too. Of course, going back to code I'd written over a year ago one day I changed my mind completely. The code in question was clean, elegant quality code and it didn't take me long to figure it out, but what took me longer was figuring out *why* the code did what it did (design of the app framework, etc).

      Since then I either write an architecture document when the code is finished or if I make an addition I write up a short semi-rambling essay on why the code is structured the way it's structured in the comments at the top.

      Not only easier on others, but also on myself if I have to go back.

    11. Re:Haiku Commenting? by Anonymous Coward · · Score: 0
      When there aren't comments, it is hard to figure out what parts of what do which.

      Is your wife commented?

    12. Re:Haiku Commenting? by tius · · Score: 1

      The truth is that good or bad code is NOT self documenting because all it tells you is what the code will do. It does not tell anyone what the intention of the code is.

      The intention of the code and the code itself, which is an interpretation of that intention, may not be in agreement. Which is why well documented code provides a clear indication of the intent of the code.

      Really, it's irrelevant how good a programmer you are. The real skill is being able to translate between designs & implementations...and back and forth. Since that takes time even for the quickest people, real design documentation and code comments that explain the intent of the code save time, frustration, and money.

    13. Re:Haiku Commenting? by Anonymous Coward · · Score: 0

      Those that think code is self-commenting, forget that there are people like me, who aren't great programmers

      It's not even that. If the code is of any complexity, it will be hard for anyone to find the bit of code they need. If I can't find anything to add to the code with a comment, I at least try to summarize every 5-10 lines/statements for a bird's eye view. You don't want to have to read the whole novel to find that one typo in chapter 12. Then again, we have technical issues (J2ME) that prevent us from splitting up functions to a reasonable degree.

      Also, I tune the syntax highlighter to make comments stand out more than the code. I can stand across the hallway and still see the comment:code ratio.

    14. Re:Haiku Commenting? by tius · · Score: 0

      Really? So, you unfortunately get run over by a bus, and Joe Coder ends up supporting or finishing your code. You're telling me there's no value in comments? There's no value in describing the intent of your wild funky convoluted code? I strongly suspect that Joe Coder would rather hack off his fingers than spend time trying to decode both the operation and intent of your code.

      Unless my time to market demands are measured in minutes, I would not hire you. I'd greatly appreciate your embedded programming skills, but as an employer you are going to cost me too much money when it comes to supporting your code.

    15. Re:Haiku Commenting? by Alef · · Score: 1
      Those that think code is self-commenting, forget that there are people like me, who aren't great programmers

      I think some would argue that lack of comments is a way to deter people who aren't great programmers from touching the code.

    16. Re:Haiku Commenting? by Anonymous Coward · · Score: 0
      Is your wife commented?

      Hmm... I don't see any comments, but there are some instructions here somewhere... Oh yes...

      (1) Inflate wife-doll.

      (2) Do not allow cat near wife-doll when inflated.

      (3) Clean well when done.

      (4) If warranty repair is required, DO NOT SEND WIFE-DOLL BACK - we will believe you since we don't trust you to follow (3) well.

    17. Re:Haiku Commenting? by Anonymous Coward · · Score: 0

      Nice flamebait, that, totally ignoring the bit where he said For my own sanity I leave very specific comments about what's going on and what the equivalent calculation is. and acting like he's advocating no comments.

    18. Re:Haiku Commenting? by mdecarle · · Score: 1

      You could of course also copy your code to some other software, and add comments to it there, essentially making a developer's guide to your code.

      Then you have both: small and fast code, and decent documentation as to what the code does.

    19. Re:Haiku Commenting? by zootm · · Score: 1, Redundant

      That's the point — inline comments tend to be bad at this ("thingy.Add(whatever); // add whatever to thingy" aids noone and damages the maintainability of the code), but it's important to write down why you are doing something, and what, on a large scale, you are trying to do.

    20. Re:Haiku Commenting? by rgmoore · · Score: 1

      I'd expand the exception a little bit to any kind of work where the exact purpose and mechanism isn't obvious. That may be most common in embedded programming, but it can happen anywhere there's something time critical, like inner loops of number crunching programs. One thing that can help in a case like that is referencing a standard reference on the approach you're taking- like mentioning a chapter in Numerical Recipies in C- rather than giving a complete explanation of the approach yourself.

      Cases like that also show why it's so important to discuss why you're taking the approach you are. A subsequent maintainer may not understand why you're using a tricky approach instead of a simple one and waste time trying to replace your code with a simpler version. A really good comment might even include benchmark data showing just how much time or space is saved by using the tricky version so that a subsequent maintainer can make an informed decision about whether or not to replace it.

      --

      There's no point in questioning authority if you aren't going to listen to the answers.

    21. Re:Haiku Commenting? by chihowa · · Score: 2, Funny

      Maybe I'm just not getting the joke, but if upon re-inspection you don't understand what you were doing and why, how do you come up with the comments to add to it?

      --
      If you want a vision of the future, imagine a youtube comments section scrolling - forever.
    22. Re:Haiku Commenting? by DavidTC · · Score: 1
      People write a comment to tell you what code is doing either need to be shoot or to learn to write less confusing code.

      /* Add one to i */
      i++;

      No shit? Is that what that does? Well, I'll be damned. Good thing you told me.

      The only time people should ever write what code does, on a level smaller than a function, is when they are using some external code that is very confusing, but is needed at that point. Like 'This is Duff's device, which...' or 'This is from the reference implimentation, it does a Fourier transform on the waveform in...'

      And such examples should probably go in functions, so this huge random block of unexplained code isn't sitting there inline. It's not ideal, but stick it somewhere, document inputs and outputs, and at least people won't screw with it.

      And no one should ever have to explain what a single line of code does. If an average programmer, looking at the line, cannot understand what it does, it's too complicated. Break it apart.

      --
      If corporations are people, aren't stockholders guilty of slavery?
    23. Re:Haiku Commenting? by negative3 · · Score: 1

      That's a very good rule that I use often. The one exception I always have is when writing assembly. In my microprocessors class I had to comment almost every line just to remember what I was doing by the time I got to the end of the program. And I've never done assembly since.

      --
      "Physics is to math what sex is to masturbation." - Richard Feynman
    24. Re:Haiku Commenting? by mediocubano · · Score: 1

      In a lot of the code I've seen there is also definitely a difference between what the code does and what the comments say the code does. Poor programming backed up by mistaken comments is possibly more confusing than no comments at all!

    25. Re:Haiku Commenting? by DavidTC · · Score: 1
      The intention of the code and the code itself, which is an interpretation of that intention, may not be in agreement.

      That's actually a fairly good defination of a bug.

      And, yes, if people don't know why the code is doing what it's doing, they don't know when it gets it wrong without having to read all the code.

      If you have 'int c=0' outside a loop, and inside a loop:

      if (++c) {

      Is that an error? Should it be 'if (c++) {'?

      If c had been calculated each time, from something which returns a -1 on failure, and you're adding 1 before checking it to make sure it's not an error, the 'if' would be completely correct.

      However, if you're just starting with c=0, and want to run this code all but the first time, that 'if' is wrong, it will never not run, as 1 gets added before the check.

      A simple comment, or reading the whole function to see if 'c' gets set anywhere else, pick one.

      --
      If corporations are people, aren't stockholders guilty of slavery?
    26. Re:Haiku Commenting? by DavidTC · · Score: 1
      That's what I do. Almost all code has logical blocks to break it up, where you do a bunch of related things and then switch to another set of things. Sometimes these are programmic blocks like 'if' and whatnot, but they tend to exist regardless.

      I try to make sure I say something between each group, just to make sure the reader and I are on roughly the same page. Even if it's 'Now that we've just done X and Y, it's time to start setting up Z.'.

      --
      If corporations are people, aren't stockholders guilty of slavery?
    27. Re:Haiku Commenting? by Anonymous Coward · · Score: 1, Insightful

      I'm sure you're not the only one who does it that way, but I'm one of the people who does it the exact opposite way. When I write [new] code, I make a bunch of comments in plain English summarizing what I need my future code to accomplish. Then I group my comments into logical sections and put the actual code underneath each section.

      One nice thing about doing it this way is that I don't usually need to re-write my comments even if I change my implementation (unless my original comments weren't abstract enough). A downfall is that someone hunting down a bug in my code might rely too much on my comments and not see the bug. But then again, at least the maintenance programmer will know what I was thinking and what I was trying to accomplish, and will hopefully have a better idea of how to fix it.

      I guess my brain just works best if I write the comments first, rather than last. It helps me keep my focus and see the bigger picture as I go...

    28. Re:Haiku Commenting? by Doctor+Memory · · Score: 1

      I would argue that it's a great way to deter people who *are* great programmers from recommending you for that new team lead position....

      --
      Just junk food for thought...
    29. Re:Haiku Commenting? by ajs · · Score: 1

      Perl has a similar thing in the Class::Contract module, which makes it easy to design by contract in Perl. It's actually pretty slick, though the Class features in modern Perl OO programming can take some getting used to for those who are used to treating Perl as an OO-free or just as a roll-your-own-OO-model language. These features are no longer just bolted on inheritance, but a true object model, similar to Perl 6.

      Of course, I'm pretty sure Ruby has such a mechanism as well.

      Assertions have long been a part of C and C++ programming, of course, but that's not really designing by contract, so much as performing error checking. These are different things, though certainly the latter is a superset of the former.

      For assertions, my favorite language these days is C (not C++) using glib's gassert mechanism. It's easy to use, integrates smoothly into GUI applications where dialog-based feedback is needed, and can even deal with external bug-reporting systems. It's also entirely optional, and massive performance gains can be had by disabling some or all assertions when releasing the code (I always re-compile Gnome without assertions, and the speedup is noticable).

    30. Re:Haiku Commenting? by Coryoth · · Score: 2, Informative

      Perl has a similar thing in the Class::Contract module, which makes it easy to design by contract in Perl. It's actually pretty slick...

      I didn't know about that one (mostly because I haven't really done any Perl programming in quite a while) but you're right, it is pretty slick. I like it. definitely a must next time I end up doing any OO Perl.

      Assertions have long been a part of C and C++ programming, of course, but that's not really designing by contract, so much as performing error checking. These are different things, though certainly the latter is a superset of the former.

      My real gripe with assertions as opposed to proper DbC is that it doesn't behave nicely with respect to subtyping/inheritance, or automatic inclusion in documentation, but that's more a matter of ease of use and niceness than actual functionality. As you say, it still does job.

      Jedidiah.

    31. Re:Haiku Commenting? by Alef · · Score: 1
      I would argue that it's a great way to deter people who *are* great programmers from recommending you for that new team lead position....

      Hehe, didn't you see my Fox Newsian prefix: "some would argue..."?

      But seriously, I don't share that point of view myself (even though I also think that code can be self-documenting to an extent). There are generally to few and too bad comments in code that I see. In fact, I am examining candidates for employment at the moment where I work, and I have put strong emphasis on their ability to document the code that they write (work samples are required!). But this also means writing code that doesn't require huge amounts of comments to be comprehensible. Spaghetti code bloated with comments can often be worse than good written code with no comments at all.

    32. Re:Haiku Commenting? by niteice · · Score: 1

      I think he's saying that if it isn't pretty clear what said block of code does within a few seconds, it needs to be commented.

      --
      ROMANES EUNT DOMUS
    33. Re:Haiku Commenting? by Drachemorder · · Score: 2, Insightful

      That's probably useful advice in a general sense, but I can envision examples where commenting a single line might be useful. Consider the case of a complex regular expression: not everyone can glance at one of those monsters and immediately understand exactly what it does. A comment explaining what the thing does and why would be useful to most folks.

    34. Re:Haiku Commenting? by UserGoogol · · Score: 1

      Writing funky code means that if you get hit by a bus, your company will do all it can to make sure you live. :)

      --
      "Never attribute to malice that which can be adequately explained by stupidity." -- Hanlon's Razor
    35. Re:Haiku Commenting? by poopdeville · · Score: 1

      Probably by putting some brain power towards it instead of just reading code like prose.

      --
      After all, I am strangely colored.
    36. Re:Haiku Commenting? by fbg111 · · Score: 1

      In short, comments convey concepts and explanations, not mechanical descriptions.

      Right, so your comments should probably explain what and why, not how and why. The exception is if you're doing something tricky or unusual and you think some reader may not interpret the code entirely correctly in determining how, so you might add the how explanation as well.

      --
      Flying is easy, just throw yourself at the ground and miss. -Douglas Adams
    37. Re:Haiku Commenting? by Nevyn · · Score: 1
      I always re-compile Gnome without assertions, and the speedup is noticable.

      You mean you disable all the g_assert()/etc. stuff? ... do you have any numbers for this as I know when I asked GNOME people at redhat they were convinced that it wasn't noticable.

      --
      ustr: Managed string API with ave. 44% overhead over strdup(), for 0-20B
    38. Re:Haiku Commenting? by cloudmaster · · Score: 1

      The problem isn't that the comments take up space - comments are not included in the bytecode generated by any sane compiler/assembler/etc-er. The problem is that, since there's no tmuch space, the OP can't use algorithms which would be more clear so as to not require such commenting. To save space, there must be some convoluted algorithms whose purpose would not neccesarily need commenting on a PC, but due to their relative complexity in implementation on a microcontroller, they *do* require commenting.

      Of course, *my* PIC assembler never needs commenting - it's always crystal clear. ;)

    39. Re:Haiku Commenting? by Anonymous Coward · · Score: 0

      I thought the first rule of software engineering is that you don't talk about software engineering.

    40. Re:Haiku Commenting? by emurphy42 · · Score: 1

      Whenever a function becomes longer than something really short, you should consider refactoring it into a set of smaller functions. Unfortunately, interpreting "really short" sanely is non-trivial.

      Let's say I need to import a text document into a database, and the layout is Byzantine enough to merit writing a dedicated program for it, rather than just using a standard map-this-field-to-that-field type tool. (This happens with alarming regularity.) I'll write a first draft something like this:

      main() {
      loop through input file
      if header ID is different from last-record-if-any then {
      // 50 lines of header mapping
      write header record
      }
      // 50 lines of detail mapping
      write detail record
      end loop
      }

      and then a quick bit of copy+pasting produces a second draft:

      main() {
      loop through input file
      if header ID is different from last-record-if-any then {
      build_and_write_header_record()
      }
      build_and_write_detail_record()
      end loop
      }

      build_and_write_header_record() {
      // 50 lines of header mapping
      write header record
      }

      build_and_write_detail_record() {
      // 50 lines of detail mapping
      write detail record
      }
      You could also choose to do the refactoring up front, but I find it's easier to do it in a separate pass.
    41. Re:Haiku Commenting? by Kahlus · · Score: 1

      Work samples are required.

      Huh? The code I write at work is the IP of my company. I can't provide it in a job interview. Or are you referring to code your candidates write in their free time?

    42. Re:Haiku Commenting? by try_anything · · Score: 1
      it is hard to figure out what parts of what do which

      ... and what parts are meant to do which.

      Sometimes important organizational insight never gets transferred from a programmer's mind to the code. What's missing are comments like:

      // This is the proper place to check Records for consistency, as it
      // is the only place that ALL records pass through before being
      // committed. Do NOT create a way for Records to bypass this code!

      This prevents maintenance programmers from accidentally adding consistency checks that don't always run, scattering duplicated consistency checks throughout the code to ensure that they always run, or splitting the control flow up so that future consistency checks *have* to be duplicated.

      Because of a lack of comments like this, frequently you find that the original programmer can make a change in a few minutes by adding a few lines of code, while a maintenance programmer takes longer, uses more code, and gets it subtly wrong.

    43. Re:Haiku Commenting? by Anonymous Coward · · Score: 0

      No, but there's a zeroth rule that says that you're not supposed to talk about the zeroth rule (Oops!). The only reason it exists is because computers start counting at zero. A hack, in other words.

    44. Re:Haiku Commenting? by Wavicle · · Score: 1

      My favorite "code not quite commenting itself" example actually came from a slashdot post a few years back that went something like this:

      if ( strcmp(user,"Osama") ) set_uid(ROOT);

      The reply to this went something like "Poor Osama user, everybody gets root but him."

      --
      Education is a better safeguard of liberty than a standing army.
      Edward Everett (1794 - 1865)
    45. Re:Haiku Commenting? by Alef · · Score: 1

      Code they write at their free time.

    46. Re:Haiku Commenting? by mcvos · · Score: 1

      50 lines? Long ago I decided that a good function should be at most 10 lines, preferably containing 1 loop, 2 if-statements and/or 3 calls to functions that handle the details of what needs to be done. It rarely works out that way, though.

      But yes, if a function is long enough that it has different parts requiring comments, give each part its own function. If code it unreadable enough to warrant a comment, make the code more readable. I think the only things that really should be explained in comments are pre and post conditions and the reason why it's being done this way and not in some other way.

      And ofcourse thousands of //TODO:s pointing out where you forgot to program that vital check that's now causing another part of the code to crash.

    47. Re:Haiku Commenting? by SirPavlova · · Score: 1

      Exactly. One sign of a good commentator (or a good anything, actually) is to know when & how to break the rules.

      --
      Yar.
    48. Re:Haiku Commenting? by ajs · · Score: 1

      I had numbers, but they are VERY old. I'll have to perform a test with modern Gnome at some point.

    49. Re:Haiku Commenting? by heson · · Score: 1

      You could write the code twice, one version that's readable (,debuggable and expandable), and one version that is runable on your target system. Then add test code to show that both are equal in function (keep the versions in sync) You need to afford having the target code fairly modular and you need a system capable of running the tests(emulator/devel version of target). The tests aren't realy needed but quite convenient when hunting for bugs.

  5. A bad question... by Snamh+Da+Ean · · Score: 2, Funny

    Asking Slashdot "Should I post comments?" is a bit like asking turkey's "Should we cancel Christmas?".

    Let the commencement of the comment posting beginulate!

    1. Re:A bad question... by Snamh+Da+Ean · · Score: 0

      Before anyone feels the need to point it out, I apologise the the stray apostrophe in turkeys...

    2. Re:A bad question... by zippthorne · · Score: 1

      So you're correcting turkey's's extra "'"?

      --
      Can you be Even More Awesome?!
  6. cenqua! by i.r.id10t · · Score: 5, Funny

    Simple, and I've posted this link a few times before, but you really need to use cenqua. Takes all the pain out of comments, and still allows personality quirks to show thru.

    The Commentator

    Just be careful on your settings and you should be fine.

    --
    Don't blame me, I voted for Kodos
    1. Re:cenqua! by tacocat · · Score: 0

      Cute, but worthless. Just fills pages with arbitrarily obvious statements

      CODE is a language in itself. So is English (or your preference). The problem is finding a bridge between the two that makes sense. I can't write comments for my PHB, he shouldn't be looking at the code anyways because he's an idiot and it will only make him feel stupid, which causes me a lot of extra work.

      So who is the audience?

    2. Re:cenqua! by i.r.id10t · · Score: 1

      Well, seeing as how this site was posted here on /. back on 4/1/05 and there is a "today only on 4/1" offer at the bottom of the page....

      --
      Don't blame me, I voted for Kodos
    3. Re:cenqua! by tacocat · · Score: 1

      Oops! Good One!

      But I think there is still a valid question in identifying who the audience is when writing code comments.

    4. Re:cenqua! by Anonymous Coward · · Score: 4, Funny

      Slashdot really needs a "-1, joke went lightyears over his head" moderation option.

    5. Re:cenqua! by Anonymous Coward · · Score: 0
      My absolute favorite part:
      Plugins are available for every concievable IDE including Eclipse, IDEA, Emacs, Vi, BBEdit, VS.NET, sed, CodeWarrior, JBuilder, JDeveloper, Notepad, Wordpad...
      Plugins for Notepad! And sed, too! Sign me up!

      A seriously hilarious site. Highly recommended reading.
    6. Re:cenqua! by tacocat · · Score: 1

      I think we need to introduce an XML tag for and

    7. Re:cenqua! by yuri+benjamin · · Score: 1

      Why post it on the fourth of January? I would've waited 'til the beginning of April - it would've been funnier then.

      --
      You make the mistake of thinking you can educate the fundamental stupidity out of people. You can't.
  7. Check out Rob Pike's thoughts on code commenting by podz · · Score: 5, Informative

    Rob Pike, a former powergeek at ATT&T labs, and a present powergeek at Google, has the following to say about code commenting. In general, I agree with him.

  8. Good code is self documenting... by Private+Taco · · Score: 5, Insightful

    Just like good documents are self coding...

    --
    If I could, I'd destroy you all.
    1. Re: Good code is self documenting... by Rob+the+Bold · · Score: 1

      That is the trick, though. You put too many comments in your code, and you end up maintaining your comments as well. Or worse, you end up with code that obviously doesn't match the comment. Or even worse, you end up with code that doesn't match the comments, but not obviously -- sort of software counter-intelligence.

      --
      I am not a crackpot.
    2. Re: Good code is self documenting... by Malc · · Score: 1

      With well-commented code and a syntax-directed editor, I find it easier and quicker to read comments than reading the code. If I suspect there is a problem in the code, then I start to read it.

      The best way to code + comment is to write out the algorithm or steps of a function using comments, and then fill the code in. Good commenting is a bit of an art, and definitely takes a while to learn more through experience than instruction.

    3. Re: Good code is self documenting... by Anonymous Coward · · Score: 0

      Thats utter crap btw. When you need to implement a complex algorithm it doesnt matter
      how well its written, how well its formatted, how clean it is, the complex nature of what
      its doing needs to be commented. even if its just a small short few lines at the top
      describing what the algorithm is for and what its doing, even better if it says how it works.

      self commenting is nonesense. good code has good clear and well understood comments in it.

      dont over do it, dont comment every line, dont write a novel, keep it clear and concise and dont comment the obvious. (like if checkit == 0) doesnt need a comment normally so dont over do it.

      its an art like anything else, but good code is definatly not self documenting.

    4. Re: Good code is self documenting... by bunratty · · Score: 4, Interesting
      Yeah, right. I recently debugged some code that did matrix calculations. It turns out that the matrix involved was always positive definite, and therefore the calculation could be done by performing Cholesky decomposition rather than explicitly taking the inverse of the matrix. Needless to say, there were no comments explaining any of this, and it took me hours to reconstruct the thoughts and derivation behind the original code.

      Here's the original code:
      L = Cholesky(cov0);
      th1 = L.i() * th0;
      lrt = (th1.t() * th1).Trace();

      which is supposed to compute the same answer as the code:
      lrt = (th0.t() * cov0.i() * th0).as_scalar();

      I do agree that in general code should be self-documenting when possible, but sometimes you need a few lines of comments to explain a single line of code, or a few paragraphs of comments to explain a few lines of code. I added 17 lines of comments to that part of the program to explain 3 lines of code.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    5. Re: Good code is self documenting... by roman_mir · · Score: 2, Insightful

      First of all you are implying that people write good code. Secondly you are making a mistake thinking that all code is easy to read when it is good. This is a lie.

      Obviously if you are writing some sort of a 3 tier application, which has a presentation, business and data tiers, then it is in fact possible to write good self documenting code, but you must also provide a design document, which explains how to read this code from high level point of view. But when you get into any specific details of that code or if the code is not a simply a goto database/do some formatting/print/get input from user/do some validation/write to database code, but something like: switch the coordinate system, do some trigonometry, create a complex data structure, display 3D world, then there is no way that code can be fully self documenting. Sure, a math genius may not require additional comments, but for everyone else, for people who are not that familiar with the domain of the problem at hand, comments are very important. Of an extremely detailed and very much up to date design document.

    6. Re: Good code is self documenting... by Charmless1 · · Score: 1

      That is actually very good advice. It makes all of that pseudo-code in college a tad more relevant.

      --
      Cheney's Valentine's Day poem: "Roses are red, Violets are blue, Say something I don't like, And I'll shoot you, too."
    7. Re: Good code is self documenting... by Canthros · · Score: 2, Insightful

      Good comments ought use good English. Punctuation, like apostrophes, and proper capitalization increases readability. Even if your spelling is impeccable, other grammatical niceties should be observed as well.

      Even so, 'good code' is a combination of commenting and coding style. Probably, neither is sufficient alone. Even the most readable code will sometimes do things which are non-obvious or unintuitive, and comments, by themselves, cannot do near so much good as clearly, concisely, and well-styled code.

      --
      Canthros
    8. Re: Good code is self documenting... by Anonymous Coward · · Score: 0

      Secondly you are making a mistake thinking that all code is easy to read when it is good. This is a lie.

      So you're suggesting that code can be good but hard to read? That seems contradictory. You must have lower standards for code than me.

      But when you get into any specific details of that code or if the code is not a simply a goto database/do some formatting/print/get input from user/do some validation/write to database code, but something like: switch the coordinate system, do some trigonometry, create a complex data structure, display 3D world, then there is no way that code can be fully self documenting.

      Can you give a specific example of some code that can not be self-documenting? I've done coordinate systems, trigonometry, data structures, 3d graphics, etc., that were all pretty self-documented.

      For good examples of how to name things, see Cocoa Style for Objective-C.

      Sure, if you just use variable names like "r" and "t", then your trig code will look like ass. But if you call them "angle-from-horizontal" and "angle-after-rotation", it's clear as day to me.

    9. Re: Good code is self documenting... by Malc · · Score: 1

      Indeed. But as somebody else pointed out, good comments tend to reflect intention rather than the actual details. I do find this approach helps me think out the issues and help me avoid forgetting some important check.

    10. Re: Good code is self documenting... by Sebastian+Jansson · · Score: 2, Interesting

      Some people say that when you see the need of a comment, see if you can fix the code first. In your example that would mean putting the tricy calculations in a separate function, that also has the benefit that if you find a better way to write it, you only have to make the change at one place even if the function is used in many places. Maybe you'd still want to add comment in the function to clarify it though considering the coplexity of the code. But in many cases just the name and the docstring of a function is clear enough that you won't have to add extra comments.

    11. Re: Good code is self documenting... by Anonymous Coward · · Score: 0

      And the winning language is ...

      COBOL! Wheeee!

    12. Re: Good code is self documenting... by Coryoth · · Score: 1

      ...and comments, by themselves, cannot do near so much good as clearly, concisely, and well-styled code.

      I think this is a strong argument (in large projects that will require significant maintenance prorgamming) for langauges that enforce coding style, that constrain you to pretty much one way to do most things - very few ways to have cute hacks, or cunning implementations, or subtle ways to hint to the compiler for optimization; just one obvious way and let the compiler do the work. It doesn't need to be slow, Ada and Eiffel are designed with that sort of philosophy and they benchmark right up there with C (which has a million and one different ways to be cute or cunning with code). It does take a little of the fun out of things - it's always fun to find a some obscure but more compact or more efficient way of coding something... but then large projects that will require large amounts of maintenance aren't supposed to be "fun" to program.

      Of course that's not to say something like Perl with TMTOWTDI don't have their place. Having lots of ways to do something can make for a very expressive easy to write language, and there are definitely many times when that's the right choice, especially when you just need to get somethign working ASAP, or provide a little glue between things. And of course you can always program C or Perl with very very strict style guidelines and end up with perfectly maintainable code... it's just that when it matters, particularly on big projects with lots of people who all have slightly different idiomatic ways of thinking, actually having hard enforcement of style via the language to help produce clear, simple, readable code has real value.

      Jedidiah.

    13. Re: Good code is self documenting... by roman_mir · · Score: 1

      I don't think you have any idea what you are talking about AT ALL. My standards are high enough that none of the code I saw that is written in corporate environment falls into them.

      Good variable naming is part of the good practice but comments on the meaning of the data structures, subsections of algorythms cannot be replaced only with good variable names, good method names and correct design.

      I wrote code for telcos, banks, insurance companies, power distributors, printers and manufacturers, and I am telling you: there is nothing that substitutes good, up to date comments in code. When you are done with your 3d graphics software and you are gone, there better be some comments left that describe PURPOSE of what you are doing in the code. Comments describe BUSINESS KNOWLEDGE, they are not an indicator of whether you know how to program or not.

      You want an example of code that needed to be commented but wasn't? Here is a simple one: I worked for HydroOne - canadian power distributor. Some of the code was written by BEA people, supposedely they knew what they were doing. Unfortunately they had your attitude: code must be self-commenting. There was no comments in business functions summarizing the PURPOSE of these functions. The method names gave SOME idea of what those functions did but obviously this wasn't enough. Especially after the 4 years that this code was in production and was maintained by a variety of people who also did not really understand the entirety of the application.

      So comments are important for multiple reasons:
      1. Many people believe they write good, self commenting code. The reality is - the do not.
      2. Maintenance of applications is not usually done by the original authors of the code.
      3. Maintenance of applications is not usually done by people who understand the entire business functionality, and so they cannot make fully informed decisions, and eve the original authors do not necessarily posses the entire business knowledge to maintain the entire application without any documentation.
      4. Design documentation often gets out of synch with the code in question. Even more often it gets out of synch with the code in question before even the first release.
      5. I personally think that a developer who cannot write comments where needed, so a developer who cannot decide where it is necessary to write comments - a bad developer. No matter if he can write good code or not. Many people I know think the same way.

      I am sure I can think of more reasons, but this should be enough.

    14. Re: Good code is self documenting... by 2short · · Score: 4, Insightful


      Self-documenting code is a wonderful thing, and greatly reduces the need for comments. Whenever someone brings this up, others say no, and eventually present an example such as yours: Entirely non-self-documenting. What the hell kind of variable names are those? L? a method named i()? Spell out "inverse" for gods sake! Of course you can't follow it. Hell, I know what Cholesky decomposition is, and I've read your explanation and I still don't know WTF that code is doing. I'll bet you needed 17 lines of comments. If you had instead changed the var names to something sufficiently descriptive, the code would successfully document what it is doing, leaving you to write a comment describing why; I suspect the third sentence of your post would have sufficed.

    15. Re: Good code is self documenting... by booch · · Score: 1
      I suppose my (Slashdot) comment fits in here well.

      I write my comments first. I figure out what needs to be done and write it down in comments. Then I flesh out the code to do what the comments say. In this way, I tend to have a comment every few lines. Almost always 1 full sentence. The comments are never of the form "add a and b", unless I'm writing out a formula I derived or copied from somewhere. Occasionally, I'll end up with comments that mirror the code pretty closely, but less often than you might think.

      I find that my commenting method/style helps me in several ways:

      • I can write my "spec" before writing my code, to get the pseudo-code straight in my head.
         
      • I can not implement certain parts, and leave them to do later, without losing too much context, and with a clear indication of what I left out.
         
      • I find that my comments never get out of sync with my code.
         
      • I can come back to my code much later and quickly understand what it does.

        Here's a random example from some JavaScript slide-show code. Note that you can see what the code does by just reading the comments. I only leave the "how" part to the code.
        // Get a list of all slides (elements with class="slide").
          slides = getElementsByClass( "slide" );
         
        // See if the user specified a specific slide in the URL.
          var page = location.hash.substring(1);
         
        // Make sure the requested slide exists, or default to 1st page.
          if ( page != 'all' && isNaN( page ) || page < 1 || page >= slides.length )
          {
            page = 1;
          }
         
        // Get the drop-down element.
          var dropdown = document.controls.Goto;
         
        // Add an option to the drop-down for each slide.
          for ( var i = 1; i <= slides.length; i++ )
          {
            if ( IE )
            {
              slidetitle = i + ' - ' + slides[i-1].childNodes.item(0).innerText;
            }
            else
            {
              slidetitle = i + ' - ' + slides[i-1].childNodes.item(1).childNodes.item(0). data;
            }
            addOptionToSelection( dropdown, slidetitle, i );
          }
      --
      Software sucks. Open Source sucks less.
    16. Re: Good code is self documenting... by PeteABastard · · Score: 1

      The grand parent is correct. The code he shows _is_ self documenting in its problem domain. The problem with self documenting code is that most coders want to invent their own 'notation' to self document it. Unfortunately to actually understand the optimisation in his example, you need to know the mathematics behind it and therefore you are going to have to learn the universal mathematical notation anyway which will make the example code clear.

      As he says if there was a one line comment saying that due to the nature of the input the inverse may be found using Cholesky decomposition, at least you know what is going on. If you don't, you have a starting point for research you probably need to do anyway to understand your problem domain.

    17. Re: Good code is self documenting... by Sithgunner · · Score: 1

      If you need to read someone's code and understand, you will have to dig every file that is linked and referenced to go through the logic built in the code, but comment can make it navigate you through it like a flow, not leave you behind in a maze or why the programmer did a workaround or nasty hacking to get the thing done.

      Just code, never is a comment. It does make you go through it smooth, if written that way. But you don't know how someone you don't know writes the code.

  9. Nothing beats good comments by ccccc · · Score: 1

    I know a lot of people say comments are unnecessary if you have nice self-documenting code. But personally I find nothing beats a short comment at the top of chunks of code to give a quick idea what it's doing (or supposed to do).

    1. Re:Nothing beats good comments by Miros · · Score: 1

      Yeah, I'd have to agree with that. Writting large ammounts of code is easier if you dont have to comment, and if you're a decent programmer your code should be clear enough to get from reading it. But at the same time, if you're trying to debug or add a feature, it really helps to know what parts of a function do what without having to read the code to find out.

    2. Re:Nothing beats good comments by Threni · · Score: 1

      > I know a lot of people say comments are unnecessary if you have nice self-documenting code.

      It's a moronic argument. You should (sometimes) explain why you are doing something, not just what/how you are doing it. Yes, you should be following a design brief/spec, but documentation that's not in the source code *will* get lost and is pointless.

    3. Re:Nothing beats good comments by khendron · · Score: 1

      It is only some types of comments that are unnecessary. While it is true that you can figure out *what* is happening just by looking at the code, what you cannot see is *why* something is happening. And it is the *why* that is the most important.

      --
      Life is like a web application. Sometime you need cookies just to get by.
    4. Re:Nothing beats good comments by HunterZ · · Score: 1

      I know a lot of people say comments are unnecessary if you have nice self-documenting code. But personally I find nothing beats a short comment at the top of chunks of code to give a quick idea what it's doing (or supposed to do).

      My thoughts exactly. I can't recall how many times I've looked at sparsely-commented code and ran away in terror (or at least scratching my head). In my opinion it's essential to comment your code at some level. Finding that level is the hard part: you have to step back from what you're doing and think about the thought process of someone looking at your code who is unfamiliar with it. This usually means a comment of appropriate length at the beginning of most chunks of code, with a few more specific comments along the way if you feel you're doing something obscure.

      I feel fortunate to have a programming job in which a good portion of my code is peer-reviewed (and - perhaps more importantly - in which I also review others' code), as I feel that I've gained some valuable insight into how to better write and comment code.

      I find it likely that the majority of those who believe that well-written code is always self-documenting probably haven't worked on a large project in which people bend a code framework around to do all sorts of crazy things, nor have they had to do a significant amount of review of others' code in such an environment.

      --
      Arguing about vi versus Emacs is like arguing whether it's better to make fire by rubbing sticks or banging rocks.
    5. Re:Nothing beats good comments by Rob+the+Bold · · Score: 1
      But personally I find nothing beats a short comment at the top of chunks of code to give a quick idea what it's doing (or supposed to do).

      I absolutely agree that decent headers are vital, especially when working on a team of size greater than zero. And furthermore, your team should have an agreed-upon standard to facilitate reading and writing the headers for each "chunk". I'm guessing that the term "chunk" is used here to be sort of generic for procedure, function, method, aspect, or whatever in an agnostic sort of way.

      None of this excuses one from writng self-documenting code. I don't use that term to mean "doesn't need comments" but rather I mean your code should look like it does what it does.

      Just to be clear, I believe you still should explain anything that needs amplification in your comments. You should wholeheartedly follow your organization's internal documentation rules, and if you can't love them, at least tell yourself that they're "better than nothing". But on top of all of that, make your code as clear as possible for the language you are using. As I frequently told myself and others, "the guy that has to maintain this code could be YOU."

      --
      I am not a crackpot.
    6. Re:Nothing beats good comments by AuMatar · · Score: 1

      I prefer to think of it- comment *what* you're trying to do, not *how* you do it. If your code is supposed to calculate an average, you don't comment how you do it- every add, loop, divide, etc. You comment saying you're calculating the average of whatever, and let the code of the averaging speak for itself.

      --
      I still have more fans than freaks. WTF is wrong with you people?
  10. Comment every conditional branch or loop by Matt+Ownby · · Score: 4, Funny

    I once read that a good comment will appear on every conditional branch or loop, and a good comment will also state the INTENTION for doing something, rather than what is actually being done (because the programmer can usually figure out what is being done). For example: // i starts at 1 instead of 0 because we don't want to process the application's name (first argument)
    for (int i = 1; i argc; i++)
    {
        printf("ARgument is %s\n", argv[i]);
    } // AND with 0xFF1234 because that is the first set of bytes in the file header
    if (u & 0xFF1234)
    {
        printf("File is valid.\n");
    } // say file not found instead of invalid due to reason blah blah blah ...
    else
    {
        printf("File not found.\n");
    }

    1. Re:Comment every conditional branch or loop by KilobyteKnight · · Score: 4, Funny
      // say file not found instead of invalid due to reason blah blah blah ...
      "blah blah blah" is mostly what I use for comments also :)

      --
      When will Windows be ready for the desktop?
    2. Re:Comment every conditional branch or loop by MemeRot · · Score: 4, Insightful

      Comments can be good,
      Avoid 'magic numbers' too,
      You've heard of constants?

      Seriously, this is not good code: if (u & 0xFF1234) - what the hell is u? Is it the start of the file? What if your file structure changes, you want to grep for every instance of 0xFF1234 and see if it needs to be changed? What if you changed your definition of what a good file is?

      Why not: if isValid(fileStart) - or if all you're doing is printing, just put it in the print statment? You do have to comment to explain why you're doing something, but the clearer the code is the easier it is to read and maintain.

    3. Re: Comment every conditional branch or loop by Black+Parrot · · Score: 5, Funny

      > I once read that a good comment will appear on every conditional branch or loop

      But be sure to put them outside the loop, so people won't have to read them over and over.

      --
      Sheesh, evil *and* a jerk. -- Jade
    4. Re:Comment every conditional branch or loop by hackstraw · · Score: 2, Interesting

      Avoid 'magic numbers' too,
      You've heard of constants?

      Seriously, this is not good code: if (u & 0xFF1234) - what the hell is u?


      Exactly. I was thinking the same thing.

      Clearly labeled abstraction is self documenting and is just better.

      Instead of if (u & 0xFF1234), why not have a macro like #define VALID_HEADER(a) ((a) & 0xFF1234) and use if (VALID_HEADER(u)). u might be an OK variable, maybe not.

      One thing I do with perl code is instead of making a complex regexp that is expanded with inline comments and whatnot, I just throw a commented line or more of what is trying to be matched. Like if I was parsing a log file for something like:

      Nov 30 10:15:01 localhost anacron[5454]: Job `cron.daily' started

      I would throw that as a comment, and then throw a regexp on it that may look like hieroglyphics but say something like $mon $day $time $machine $command $pid $msg. If it works, nobody cares. If it doesn't (format changed or whatever) no comment in the world is going to make it easier to debug any differently than having a sample of the expected input.

      NEVER do dumb shit like:

      int i; /* loop counter */

      Its also good to document the basic ins and outs of functions, and the by products of it. If the function destroys the input. Let me know. If the function returns something special in the case of an error. Let me know. If the function takes arguments, let me know what those are. If the function returns malloc()ed data that I need to free, let me know. If I need to provide enough malloc()ed info going into the function, let me know.

      Feel free to substitute "me" with "you the programmer" in case you ever look back at your own code.

      Another thing to avoid. Don't make code reusable with copy and paste. That kills me, and I had to come behind some "senior" programmer's code before where that was done 3 or more times on huge modules where each one was subtly modified. I would fire someone on the spot for that if they were a "senior" programmer.

      Oh, and how about this. Reading the documentation first and/or knowing the language/API/specification before you start writing code. Another different "senior" programmer I worked with though he was clever to rewrite the CGI specification and do his own parsing of URL arguments instead of using & and = signs.

      Thank the FSM that I don't work for those companies anymore.

      I never thought that programming was that terribly difficult. Working with other programmers definitely is.

    5. Re:Comment every conditional branch or loop by 2short · · Score: 2, Insightful

      What a great example of lousty code and worse comments. How about the folowing... (Slashdot appears to offer a couple different ways to mis-format code; I've chosen incorrect indenting over comments can't start a line)

      // the only thing a comment here should explain is why you use & and not ==
      if (uFileHeader & VALID_FILE_HEADER)
      {
      printf("File shares at least one set bit with a valid file!\n");
      }
      else
      {
      // reason "blah, blah, blah", which I can not imagine existing,
      // certainly deserves a comment, but it applies to the decision
      // to say (falsely) "file not found", so it belongs here.
      printf("File not found.\n");
      }

    6. Re:Comment every conditional branch or loop by Lehk228 · · Score: 1

      so how would you propose reusing the bulk of the code with subtle differences? is SMC coming back into style?

      --
      Snowden and Manning are heroes.
    7. Re: Comment every conditional branch or loop by stinky+wizzleteats · · Score: 1

      This comment is why you should get karma for funny mods. Well done.

    8. Re:Comment every conditional branch or loop by AuMatar · · Score: 1

      I might go a step farther and create an inline function isValidHeader() that does the ANDing. It also seems like ANDing would be really wierd in this situation- the logical AND there would be TRUE if ANY of the bits of FileHeader matches any of the bits of VALID_HEADER. I'd expect he really wanted an equality test (in which case I might not break it into its own function, as the code is trivial and easy to understand).

      --
      I still have more fans than freaks. WTF is wrong with you people?
    9. Re:Comment every conditional branch or loop by dascandy · · Score: 1

      > I once read that a good comment will appear on every conditional branch or loop, and a good comment will also state the INTENTION for doing something,

      well...

      } // AND with 0xFF1234 because that is the first set of bytes in the file header
      if (u & 0xFF1234)

      that doesn't check whether the first four bytes are 0x00FF1234. It checks whether one of the 13 set bits is set, and if so, it's ok. Try a file starting with 0x0C 0x00 0x00 0x00, and it'll pass.

      Comments should detail the functional path and algorithm, code should do what the comments say.

    10. Re:Comment every conditional branch or loop by hackstraw · · Score: 1

      so how would you propose reusing the bulk of the code with subtle differences?

      Depends.

      The code I was talking about was actually something like 3 separate programs. So a library with a structure or class element to flag which program we are in is suffice. It could just be compiled into the main executable with #ifdef's to wrap around the subtle differences.

      The programmer I was talking about was just not that good.

      I was trying to debug his code that had a bug in it where he thought it was cool to change between ascii representation of an integer in hex or decimal representation and he interchanged those back and forth. It worked so long as we were dealing with numbers under 10. A sane programmer would store the data always as a native integer, and convert the integer as needed to ascii hex or decimal with member functions like asciiDecimal() and asciiHex() (I prefer underscores vs case, but this was Windows land and the opposite is preferred there).

      Actually, this was not a bug, it was an implementation error. I'm not even a good programmer, but I would have never done the stupid mistakes that he did. I guess I won't mention the name of the company by name, but they are a major software outfit that specializes in antivirus and security programs primarily for Windows. I've heard that their stuff isn't that good, but I don't know or care.

    11. Re:Comment every conditional branch or loop by Lehk228 · · Score: 1

      using #ifdef is worse than copying, maybe using a parameter passed to the block to select the different behaviors

      he rest sounds like the guy was an idiot, maybe being someone's nephew or brother in law got him his job?

      --
      Snowden and Manning are heroes.
    12. Re:Comment every conditional branch or loop by pommiekiwifruit · · Score: 1

      Well a senior colleague of mine did write extensively commented code that had explanations after each closing brace. I think he found it useful in finding his way around the code, since he was completely blind, making graphical editor highlighting less useful.

  11. commenting made easy... by nick-less · · Score: 1
    1. Re:commenting made easy... by Mr2cents · · Score: 1

      Isn't this error-prone? not to mention that it is a lot of tedious work!

      Therefore, I propose this simple well-documented awk-script that will automatically comment *every line* (yes, you heard that right!), thereby making the code much more understandable:

      # awk '{print $0 "\n//" $0}' undocumented_source_file.c > documented_source_file.c
      awk '{print $0 "\n//" $0}' undocumented_source_file.c > documented_source_file.c

      --
      "It's too bad that stupidity isn't painful." - Anton LaVey
  12. Ada Rocks by Anonymous Coward · · Score: 1, Insightful

    It's like C++ with some thought to design...

    1. Re:Ada Rocks by Anonymous Coward · · Score: 0

      How do you read a single keystroke in Ada without waiting for the return key to be pressed? Is there a simple function that will do this, like INKEY$ in BASIC?

    2. Re:Ada Rocks by Col+Bat+Guano · · Score: 1

      function Ada.Text_IO.Get_Immediate

  13. Denis who? by Anonymous Coward · · Score: 1, Insightful

    Who is Denis Krukovsky, and why should I (or anyone) care what he says?

    I did RTFA: it was poorly written and makes some statements that most people would STRONGLY disagree with. For instance:
    The point to start writing comments is... when the code is ready to be presented for others.

  14. Sure by Praetorian42 · · Score: 3, Funny

    Sure my code is readable, but more often than not I find my comments explaining the screwed up business logic behind the code.

    1. Re:Sure by cosinezero · · Score: 1

      Too true. Or insulting the developer responsible for writing the bloat... :)

    2. Re:Sure by urbanRealist · · Score: 1

      This is not funny. This is seriously the only need I have for comments. Many have built off of my code and none have complained. If it were not for insane requirements from management, I would definitely have no need for comments.

      --
      I've seen a lot of things, but I've never been a witness.
  15. The why not the how by Ckwop · · Score: 4, Insightful

    A comment should tell you why something is in place rather than what the code is doing:

    A trival example:

    Don't do this:

    public bool CheckSmsValue(Account smsAccount)
    {

    // Check tarriff is null
    if (Account.Tarrif == null)
              return;
    ...
    }

    Do do this:

    public bool CheckSmsValue(Account smsAccount)
    {

    // 30-11-2005 Fixes a null reference exception that occurs later on if no reference is available.
    if (Account.Tarrif == null)
              return;
    ...
    }

    Simon.

    1. Re:The why not the how by BarryNorton · · Score: 1

      // 30-11-2005 16:08 GMT Fixes a type checking error when no value is returned
      if (Account.Tarrif == null)
                          return false;

    2. Re:The why not the how by Youssef+Adnan · · Score: 1

      // 30-11-2005 16:08 GMT - (myemail@myco.com) Fixes a type checking error when no value is returned if (Account.Tarrif == null) return false;

    3. Re:The why not the how by Malc · · Score: 3, Insightful

      Person pet peeve here: dates and names/initials on comments. That's what source control is for, so don't litter the code with them.

      What I see here isn't preventing an exception, but rather checking the validity of a paremeter. I know it adds extra processing, but so many problems could be avoided if programmers put more effort in to input (e.g. parameter) validity checks. If it's an unusual situation, check for it in an assert as part of the pre-conditions at the beginning of the function (programming by contract). I'm assuming this is Java code in your example - does it not support assert now?

    4. Re:The why not the how by op12 · · Score: 5, Funny

      What about doing this?

      /* makes it public */ public /* boolean value */ bool /* function name */ CheckSmsValue( /* function parameters */Account smsAccount)
      /* start function */{
      /* Comment */
      // Check tarriff is null
      /* if statement */
      if ( /* variable */ Account.Tarrif /* equals */ == /* Null */ null)
      /* return */ return;
      /* dot, dot, dot */ ...
      /* end function */}

    5. Re:The why not the how by vadim_t · · Score: 1

      Both pretty bad, IMO.

      The first is obviously bad because it says nothing new. Now, the second one is more interesting.

      Are you returning because an error would happen if you didn't, or because with no tariff the rest of the code doesn't apply? IMO, it's the second thing that should be explained in the comment -- we aren't returning because it's a hack that prevents something from raising an exception, but because with this particular value set to null, the rest of the function doesn't apply.

      Perhaps there should be two comments: One explaining that this particular part of the code doesn't apply when no tariff is defined, and a second one that explains that the lack of this check previously produced a crash.

      This way, the programmer reading it can know two things: That this is done because the remaining code doesn't apply in this particular situation, and it also fixes a bug.

    6. Re:The why not the how by Anonymous Coward · · Score: 0
      In this case I would prefer to know Why can we skip the rest of the code in this case? Sure, it fixes a null reference exception; but are we still doing something sensible (once we provide a valid return value for your bool function)?

      // If we don't know the Tarrif, account is invalid so reject the SMS.

    7. Re:The why not the how by rjstanford · · Score: 5, Informative

      Sorry, but you happened to hit on one of my pet-peeves with non-self-descriptive code. I do agree with your suggestions, mind you, but I see it all the time: functions describing how they work, not what they do. Sorry to pick on you, but in this case why not take:

      public bool CheckSmsValue(Account smsAccount)
      {

      And instead say:

      public bool isSmsValueAccurate(Account smsAccount)
      {

      That way, anyone who glances at the call will know what the function does. In fact, the first one could be checking for existance, non-existance, accuracy, threshold, who knows? Heck, its exactly the kind of function that I could see being called in many different places by people expecting it to be checking different things. Or coder1 adds it in expecting it to check for "positive" as well as whatever else, months later coder2 realizes that it doesn't and adds the "extra check" into it - its a check function, after all, right? And then coder3's code in some far-away place suddenly starts failing because he didn't want that check in the function.

      A good name should be an implict contract. The function above should, by that definition, return "true" if it did at least "check" the SmsValue, and "false" if it didn't bother to... not quite what the original intent was. Probably.

      Phew. Sorry for the long-windedness.

      --
      You're special forces then? That's great! I just love your olympics!
    8. Re:The why not the how by QuadEddie · · Score: 1

      public bool CheckSmsValue(Account smsAccount)
      {

      // Check tarriff is null
      if (Account.Tarrif == null)
      return;
      ...
      }

      I can see why you shouldn't do that... Account is a class and not an object.

      It should read:

      public bool CheckSmsValue(Account smsAccount)
      {

      // Check tarriff is null
      if (smsAccount.Tarrif == null)
      return;
      ...
      }

    9. Re:The why not the how by nhl420 · · Score: 1

      /* Heh...you said "do do" */

    10. Re:The why not the how by Duhavid · · Score: 0

      Heh, you put "do do" in your comment.
      heh, heh.

      --
      emt 377 emt 4
    11. Re:The why not the how by drxenos · · Score: 1

      I completely agree. It's my pet peeve to. I hate seeing code littered with that crap! That is what your configuration management system is for!

      --


      Anonymous Cowards suck.
    12. Re:The why not the how by lahi · · Score: 1

      // 30-11-2005 Fixes a null reference exception that occurs later on if no reference is available.

      That comment does not belong in the code, it belongs in the comment field of the commit of the fix to the code repository. It is a typical comment that may go obsolete without being removed when someone else figures out that the null reference never occurs because the Account class invariant ensures its existence, and therefore deletes the if-statement.

      In general, historical stuff should not be in the code but in the CVS (or Subversion or whatever) repository. Same with dead code. It should be deleted, not commented out.

      -Lasse

    13. Re:The why not the how by Anonymous Coward · · Score: 0

      '(wow (better (code (readablility thorough) (obfuscation due to) comments) that ruin) the flow (of the function))

      I feel like I'm reading lisp

    14. Re:The why not the how by trailerparkcassanova · · Score: 1

      This is an example of something that doesn't need to be commented.

    15. Re:The why not the how by DavidTC · · Score: 1
      I hate 'fixes' in comments when in reality they're just 'the code later down is mess up, so we make sure we don't execute it in certain circumstances', because it implies some sort of God-like knowledge. How do you know someone didn't fix the same problem somewhere else later on, and thus your 'fix' is not needed?

      It's much better to say something like: // If the tarrif is nothing, this function does not apply (And does not work as of 30-11-2005)

      And no one gives a damn of what kind of bug it is that won't happen. That's just insanity.

      Also, I hate dating changes. What, do people have a time machine when working on the code? It wasn't fixed, now it is fixed, and it will remained fixed from now on.

      They really only make sense when you're using them as some sort of versioning system, and you really should be using, you know, actual versions, where you grab a copy of the code and call it 4.2.34 or whatever.

      Instead of having to ask 'Are you running the code from 30-11-2005 or 25-11-2005?' and then having to go and figure out what differences have been made.

      --
      If corporations are people, aren't stockholders guilty of slavery?
    16. Re:The why not the how by Coryoth · · Score: 1
      If it's an unusual situation, check for it in an assert as part of the pre-conditions at the beginning of the function (programming by contract). I'm assuming this is Java code in your example - does it not support assert now?

      Why not go one step better, get JML and actually have proper preconditions which will go into the JavaDoc documentation and can be used to generate JUnit unit tests automatically as well?
      //@ requires smsAccount.Tariff != null
      //@ ensures ...
      public bool CheckSmsValue(Account smsAccount) {
      ...
      }
      You then get the advantage that any subclasses will automatically inherit the pre- and post-conditions, and sensibly handles subtyping so that pre-conditions can only be strengthened and post-conditions weakened etc.

      It's also worth noting that perhaps the right way to go about this would have been to have
      public class Account {
      ...
      //@ public invariant Tariff != null
      ...
      }
      Presuming that an account should presumably always have a tariff (who knows exactly what the business logic is though), and thus when you have runtime checking of contracts enabled you'll get an error whenever the Tariff is null for an Account object (checked after every method executes), and you'll have the fact that Accounts should never have null Tariffs formally documented while you're at it.

      Jedidiah.
    17. Re:The why not the how by Phreakiture · · Score: 1

      Personal pet peeve here.... Dates and times should be in ISO-8631 format, so that the fields are easily recognised. In your example, it is clear that this is 30th November, but suppose you did this tomorrow? You would write 1-12-2005, where I would have written 12-1-2005. So, is it 12th January, or 1st Decemeber? ISO-8631 solves this problem by writing the date with the fields in descending order, e.g. 2005-11-30. It has the additional advantage (not relevent here, but still noteworty) of sorting correctly in a lexical sort.

      Whether or not dating your comments is a good idea will be left for others to bitch about.

      --
      www.wavefront-av.com
    18. Re:The why not the how by pthisis · · Score: 1

      Or you could use a completely unambiguous format: /* Changed on 30 Nov 2005 */

      I tend to use ISO-8631 for filenames or other things that might be sorted, but DD Mon YYYY for things that are human-readable non-sorting.

      --
      rage, rage against the dying of the light
    19. Re:The why not the how by pileated · · Score: 1

      Given the length of the newly named function I expect you to be longwinded............:-)
      I do tend to agree with you though and find it odd to find myself turning to these monstrously long names in the interest of clarity as I get older.

    20. Re:The why not the how by Anonymous Coward · · Score: 0

      Brian? Is that you?

    21. Re:The why not the how by phantomfive · · Score: 1

      You have a syntax error there on line 9, partner.

      --
      Qxe4
    22. Re:The why not the how by big+ben+bullet · · Score: 1

      How about:

      public bool SmsAccountIsValid(Account smsAccount)
      {

      That way the call is:
      if (SmsAccountIsValid(smsAccount))
      {

      and not

      if (isSmsAccountValid(smsAccount))
      {

      What call lays closer to the English grammar?

      Still... your suggestion sure beats CheckSmsAccount ;-)

    23. Re:The why not the how by rjstanford · · Score: 1

      A valid point - these days, most code (not including the GP) is written in some form of OO language, so you'd have if(smsAccount.isValid()) or something similar. And yes, you still (or at least I still) see a ton of if(smsAccount.checkStatus()) type calls. So in this case, with some language tweaking, you can have your grammar and, er, eat it too. Or something.

      --
      You're special forces then? That's great! I just love your olympics!
  16. Haiku by Anonymous Coward · · Score: 0

    this block for mailing
    checks addresses for error
    errors on failure

    *bow*

  17. Words to live by by 3CRanch · · Score: 5, Funny

    During college I always lived by:

    "It was hard to write; it should be hard to read"

    'course the profs didn't appreciate that much...

    1. Re:Words to live by by ucblockhead · · Score: 1

      It was hard to write because you didn't comment.

      --
      The cake is a pie
    2. Re:Words to live by by Weirdofreak · · Score: 1

      So get better at writing.

  18. No by trollable · · Score: 1

    You should use Java instead (or another easily readable and understandable programming language). Ok there may be some cases where a comment is needed but it is quite rare. Give the source, that should be enough. Of course, if your design is complex, you should write design/technical documentation (but it is out of the scope of comments anyway). Don't hide important information into comments, give it its own status. Don't clutter your code with comments. IMHO.

    1. Re:No by BodhiCat · · Score: 0

      You should use Java instead (or another easily readable and understandable programming language).

      Na, use Perl and never use comments. "A True Klingon never comments his code."

      What could be more readable than:
      if($mainarray[$i][$n] =~ /[A-Za-z ]+, / && $mainarray[$i][$n] =~ /^[^\d]/ && $mainarray[$i][$n] =~ /\d\d\d\d\s*$/){ @cstzip_array = split(/,\s+/,$mainarray[$i][$n]);}

    2. Re:No by ProlificSage · · Score: 1

      You should use Java instead (or another easily readable and understandable programming language).
      It doesn't matter what the language is if the programmer doesn't know how to write/comment properly. I just finished a contract at a Java shop where they had uncommented/un-javadoc'd methods with parameters like s, s1, s2. Unless you can track down who wrote the code, it's a nightmare. This place also believed in commenting, but they did it stupidly. There were no descriptions of what code was supposed to do, or why. But, there were idiotic running comments like if(x == null)//see if X is null. It was a nightmare. Needless to say, I am glad that contract is over. If the commenting/variable naming is good, then I don't necessarily have to be an expert in the language to figure out what's going on. For instance, I am no Perl expert, but I can get an idea of what a properly commented Perl script is supposed to do. This is important because maybe someday code will be maintained by a junior programmer who is unfamiliar with the code, and possibly the language. I was in this situation myself once, so I try to make my comments clear. I also try to make my variable names clear as well. A variable named x is quick to type, but accountBalance is a lot clearer. If it was hard to write, then the programmer should make it easy (easier) to read by using proper variable names and comments.

      --
      Real software engineers regret the existence of COBOL, FORTRAN and BASIC.
    3. Re:No by trollable · · Score: 1

      I supposed the code is well written. Comments won't help for bad code.

      It doesn't matter what the language is if the programmer doesn't know how to write/comment properly.

      Some languages are easier to understand than others. The semantic of Java is very simple, the semantic of Perl or others is not. These languages are more powerfull but also more difficult to understand. Code that was hard to write should be commented. However, there is no such code in Java ;)
      I agree with your sig.

    4. Re:No by AuMatar · · Score: 1

      You fail. A true Perl programmer does not use variables. He lets @_ and $_ hold all his data.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    5. Re:No by ProlificSage · · Score: 1

      Code that was hard to write should be commented. However, there is no such code in Java

      I disagree. While Java itself is well-done and useful, there is still code that is "hard to write", or more accurately, maybe took the author lots of research to find the proper algorithm, etc. In this case, when you add in bad variable naming and little or no commenting it is a maintenance nightmare. At the very least, the author should state the general purpose of the class itself. Without that at least, you end up being more of an archaeologist than a programmer, trying to dig through the code to see what's supposed to be going on, and making assumptions. I'd much rather have well-documented classes/methods. If I know what it's supposed to do, then it makes things easier when trying to track down bugs. While well-written code in and of itself is somewhat self-documenting, it's nice to be able to run Javadoc on a file and have a quick reference of what's going on. Otherwise, time is wasted in the long run.

      Of course, part of my problem with my last contract is that it was quite easy to tell that the Java code was written by people used to writing COBOL or C. The COBOL programmers wrote thousand line methods. The C programmers had cryptic variable names and you could tell they learned using punch cards. That can be forgiven to an extent.

      What shouldn't be forgiven, however, is the utter lack of typing skill found amongst most programmers. I type 50 words a minute, so it is not at all painful for me to write good Javadoc. Ask a programmer who types with two fingers, slowly, to do that and it really becomes a big hurdle for them to do it well. I think anyone who uses a keyboard for a living should know how to use it correctly. Especially if they are being paid by the hour

      --
      Real software engineers regret the existence of COBOL, FORTRAN and BASIC.
  19. The classic by $RANDOMLUSER · · Score: 1
    --
    No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    1. Re:The classic by egarland · · Score: 1

      An actuall comment I put in my code may years ago before I understood that consisely and clearly describing things was important and valuable:

      #Talk about your complicated data structures. It would take a book
      #to describe this one. If you can figure it out, good. If not, tough.

      --
      set softtabstop=4 shiftwidth=4 expandtab nocp worlddomination
  20. You should not comment on your code by raingrove · · Score: 1

    Try your best to make your code unreadable by anyone else other than you. That will keep you employed :P

    1. Re:You should not comment on your code by TheRon6 · · Score: 1

      Here's an article that was posted on /. a while ago about that if you're really looking for some job security. http://thc.org/root/phun/unmaintain.html

      --
      Does this rag smell like chloroform to you?
  21. Comments tell reason. by Daniel_Staal · · Score: 4, Insightful

    The code can tell me what it is doing, but it can't tell me what it is supposed to be doing. The comment should tell me why the code is doing what it is doing. Then I can look at the comment and code together and tell whether the code is right. (And the comment won't have to change as I modify the code: It either stays because the why still exists, or it is removed because it doesn't.)

    --
    'Sensible' is a curse word.
  22. You are not expected to understand this by b1t+r0t · · Score: 1

    I once managed to put an "All Your Base" reference in a series of comments, and have them actually be meaningful to the code.

    --

    --
    "Open source is good." - Steve Jobs
    "Open source is evil." - Microsoft
    1. Re:You are not expected to understand this by tlhIngan · · Score: 1

      Skillful commentors are able to insert their phrase-du-jour into the code at the right place.

      Unfortunately, I'm not a skillful commentor - so I often fail to work in quotes that I have in my head, or thoughts, or characters into my comments. Would be nice since the code can then serve as a journal...

      ("I can't believe I liked the book then! Sheesh!")

    2. Re:You are not expected to understand this by prgrmr · · Score: 1

      I only commented in Latin and Klingon for that employer

      I'm still looking for an appropriate occasion to use mysterium iniquitatis in a comment. But my primary job duties aren't programming anymore. C'est la vie, I suppose.

    3. Re:You are not expected to understand this by BodhiCat · · Score: 0

      After that incident, I only commented in Latin and Klingon for that employer.

      I took over my current job at a Southern University from a former part-time programmer who was working on a Ph.D. in Buddhist Philosopy. These are some of the actual comments that he used:

      $catarray[$m][$j][6]=0; # Don't know mind = 0

      if(not $catansarray[$m][$t]) #check to see if entry exist conventionaly

      if($quaarray[$i][$j]) #check to see if the ultimate question has been aswered

      Thanks, bud, that was really helpful.

    4. Re:You are not expected to understand this by Anonymous Coward · · Score: 0

      I once managed to put an "All Your Base" reference in a series of comments, and have them actually be meaningful to the code.

      It would be better if used within the code: make every variable named "YourBase" a member of a structure named "Us" which, in turn, controls the standard output.

      "Main screen turn on."
      "All YourBase are belong to Us."

      Otherwise, it's just name-dropping.

  23. MOD PARENT UP. by 3-State+Bit · · Score: 1

    ha, I thought you were making a subtle point!

    1. Re:MOD PARENT UP. by Southpaw018 · · Score: 1

      Oh snap. I should have just kept my mouth shut. O_o

      --
      ACs are modded -6. I don't read you, I don't mod you, I don't see you. Don't like it? Don't be a coward.
    2. Re:MOD PARENT UP. by $RANDOMLUSER · · Score: 1, Interesting
      > No one at Microsoft has ever had anyone murdered.

      Tell that to Gary Kildall

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    3. Re:MOD PARENT UP. by the_humeister · · Score: 0

      i don't see any mention of murder. so he got drunk and fell off a bar stool. big deal. he also sold is company for hundreds of millions. if he was poor and homeless, then it'd make more sense.

    4. Re:MOD PARENT UP. by Syberghost · · Score: 1

      Who at Microsoft overserved him alcohol until he hurt himself?

    5. Re:MOD PARENT UP. by Anonymous Coward · · Score: 0

      I remember the newspaper articles about Kildall's death. They indicated he had been attacked and beaten and left for dead. The police never tracked down his attackers.

    6. Re:MOD PARENT UP. by cp.tar · · Score: 1
      so he got drunk and fell off a bar stool. big deal.

      Yes, it is a big deal. You just don't know the whole story.

      Apparently, Steve Ballmer grabbed his stool and beat him with it repeatedly, shouting "I'll fucking kill him!"
      (He added the "I've done it before..." later.)

      Of course, it was all hushed up...

      --
      Ignore this signature. By order.
    7. Re:MOD PARENT UP. by Syberghost · · Score: 1

      I remember the newspaper articles about Kildall's death. They indicated he had been attacked and beaten and left for dead. The police never tracked down his attackers.

      Random news articles all around the world indicated all kinds of ridiculous bullshit. The San Jose Mercury, however, his local paper, indicated that he'd suffered a massive heart attack and fallen down; the latter possibly caused by the former. I don't feel like spending $5 to get the autopsy report, but feel free to do so yourself.

      Certainly the people inside the restaurant with him who called the ambulance didn't feel like he'd been "left for dead" somewhere.

  24. Haiku? by Twitch42 · · Score: 1

    golden urn soiled
    grandfather desecrated
    by a confused cat

    My coding comments are about as useful as my message board ones.

  25. Forget the comments by Lxy · · Score: 1

    Learn to write Submissions first.

    --

    There is no reasonable defense against an idiot with an agenda
    :wq
  26. Why Comment in Haiku... by lax-goalie · · Score: 1

    ...when you can code that way?

    "How to decrypt a DVD: in haiku form". It's quite elegant, really.

  27. News? Matters? by BarryNorton · · Score: 1

    // Redundant.comment while(story = slashdot.getStory()) { story.read(); eyes.roll(); }

  28. Three Books to Read by CortoMaltese · · Score: 3, Informative
    Three pretty good books that have insightful views on how to write readable code and comment it appropriately:

    In short, they all suggest writing readable code is more important than commenting spaghetti, but there are also good points on commenting. (Can't be bothered to copy-paste them here, though, see for yourself.)

    1. Re:Three Books to Read by tehshen · · Score: 2, Informative

      In contrast, WardsWiki has a list of how to make it so your code doesn't need comments so often: SelfDocumentingCode

      --
      Guy asked me for a quarter for a cup of coffee. So I bit him.
    2. Re:Three Books to Read by ZorroXXX · · Score: 1
      In my opinion there are three ways to write code:

      1. write unreadable code
      2. write unreadable code, but try to comment it readable
      3. write readable code

      Example:

      1. if (uFileHeader & 0xFF1234)

      2. if (uFileHeader & 0xFF1234) // check if the file header is valid

      3. #define VALID_FILE_HEADER 0xFF1234
        ...
        if (uFileHeader & VALID_FILE_HEADER)

      This second way is the same as Martin Fowler in his book Refactoring refers to as writing comments as using deodorant to cover up that the code stinks. This is a great book, highly recommended. The Pragmatic Programmer is also very good (I have not read the two other books mentioned in the parent post).

      As a rule of thumb (in my personal experience), the majority of all one-line comment are deodorant.

      Note that even though the comment by itself might be enlightening and add (even great) value to the code (like "// check ..." above), the code is "always" better of if what the comment expresses is incorporated directly into the code instead.

      One way to increase the quality of comments is to literally put a price tag on them. If you were to pay a consultant to insert the comment, how much would you be willing to pay him/her? Use a 10-based scale, say $100, $10, $1, 10cent (and also consider the negative side of scale, i.e. if a given comment exists, how much would you pay him/her to remove the comment?). Then remove all comments below a given value, say $1.

      How many of you could have argued that spending say $1 to add the comment below would be a good investment?

      while (! feof(stream)) {
      do();
      what();
      ever();
      with();
      the();
      file();
      } // end while

      On the other hand, you might sometime stumble over great comments that you could defend spending $100 to get written if they did not exist (these are multi-line comments/stories perhaps on the form "We tried earlier to do things in such and such way but that did not work out very well because of whatever. An besides blah blah..." or something similar. ).

      I often complain about comments written by my colleagues so I have a reputation of being opposed to writing comments. But I am not against writing comments; I am against writing valueless comments.

      --
      When comments lie about the code, both are probably wrong.

      --
      When you are sure of something, you probably are wrong (search for "Unskilled and Unaware of It").
  29. Comments First by Doc+Ruby · · Score: 4, Insightful

    Good comments are written first, before the code, describing what the following code does. It is gramatically correct, punctuated, easy for a stranger to read. It says what the following code does in terms of the real world, not just in terms of other code, unless the sole purpose of the code is to connect other code without relation to anything expressible in real world terms. I prefer my comments to be in the present tense, as if they could be directly compiled themselves. I put comments inside practically every block, like function definitions, loops, conditionals. I often put comment labels after block closers, especially complex conditional sets, embedded loops and functions. That labeling makes it easier to keep track of context within which variables, their scope and the "current task" are in operation. I'd rather spend a few more seconds typing up front, and save a lot of scrolling and delimiter-matching later (not to mention reducing confusion and mistakes).

    Code gets shuffled around in different order, read by strangers, and reread much later by yourself, often after you've changed by experience (either in programming or in the task being programmed). Writing the code first is a good way to outline the program, and to detect flaws in your approach. It also gets a little bit of the program done, on screen where you can see it. Often coding to support the comments is more like a cleanup task than starting from scratch.

    --

    --
    make install -not war

    1. Re: Comments First by Black+Parrot · · Score: 4, Insightful

      > Good comments are written first, before the code

      When implementing a big program or non-trivial algorithm, I start the file with comments that end up serving as an outline for the code I insert afterward. It helps clarify my thoughts about how I'm going to go about it, and of course keeps me from forgetting anything.

      --
      Sheesh, evil *and* a jerk. -- Jade
    2. Re:Comments First by the0ther · · Score: 1

      This is great advice. Agree with you 100%.

    3. Re: Comments First by Doc+Ruby · · Score: 1

      I start a file with a description of what the contained "object" does. I don't put a lot of details in the beginning anymore, because I got tired of updating the comments whenever I changed the API or significant varibles/algorithms. I really wish my programming editor stored every line in its own record in a relational database, with separate tables for blocks, variables, class/function names and comments. I'd like to query for callgraphs, and more easily factor code. And I'd like to query for uncommented blocks. The side benefit of arbitrary indent/CR and other whitespace formatting also seems valuable, if out of the scope of this discussion. Someday.

      --

      --
      make install -not war

    4. Re:Comments First by khb · · Score: 1
      While I agree absolutely that comments should be written first; I am not so doctrinare as to do so for every block. As others have sagely noted, the comments should not repeat what the code says; it should focus on:
      • What I intend (especially if it's subtle, involves global state, etc.)
      • What I assume (about input, the processor, or more generally, the context)
      • Pointers to suitable external design documents (e.g. paper which introduced the algorithm employed), especially when they are uncommon.

      Some of the code I wrote 25 years ago is still in use. While I can't say that I can pick it up after all these years, people who have taken the project over claim that such signposts proved helpful over the years, and the many hands it's passed through since.

      Write like your code will live forever. If you do it will, it just might ;>

    5. Re:Comments First by customiser · · Score: 1

      I'm sure this works for a lot of people, and I would definitely be grateful if I did find such well commented code. But on the other hand it adds a lot of overhead, especially when changing the code structure significantly (e.g. refactoring). Which means that unless everybody in your team is very disciplined, after a while comments don't get written or don't match the code anymore.

      The other approach is to write clean code, use good naming conventions, write unit tests, and comment only when things are not clear (and after trying to rewrite it in a better way). Of course, this can also go wrong as it depends a lot on the judgement of the individual developers.

    6. Re:Comments First by orbitalia · · Score: 1

      Good comments are written first, before the code
      Yeah it's called a design..

      Code gets shuffled around in different order, read by strangers, and reread much later by yourself, often after you've changed by experience (either in programming or in the task being programmed). Writing the code first is a good way to outline the program, and to detect flaws in your approach. It also gets a little bit of the program done, on screen where you can see it. Often coding to support the comments is more like a cleanup task than starting from scratch.

      Designs should be maintained in parallel with code.

    7. Re:Comments First by Doc+Ruby · · Score: 1

      Well, of course if subsequent editing doesn't respect the comments, they'll become useless. But that is true of any comment style. My style binds comments to their scope, largely independent of outside context, which makes it much easier to edit the comments along with the code. And their "redundancy" helps enforce the focus of the code. All those other approaches you mentioned are coding conventions - which I also follow, except that I comment everything. I make sure to leave linebreaks between sequences of related code lines, and comment just the "paragraphs", although I rarely follow an esoteric line with a comment clarifying it.

      I produced my style after years of working with others. Starting programs, finishing them, jumping in to help - all collaborating with others, and getting their feedback (sometimes unintentional) on what works to keep the same ideas of the code in all our minds. And considering "me, later" as distinct as any other coder. Coders without the discipline to follow a comment style generally don't have discipline to write code that other programmers can maintain. And starting with good comments gives everyone a momentum kickstart in keeping the comments readable. They're not expendable - it's often much easier to rewrite code from scratch, just so it's understandable, than to create comments from scratch to describe the code.

      --

      --
      make install -not war

    8. Re:Comments First by Doc+Ruby · · Score: 2, Insightful

      The design is usually in different terms than the code. When intelligible, the design that accompanies the code would make good comments. But often the design is at a different level of abstraction, or in terms of entities not directly represented in the code, or omits important artifacts of the code or the machine itself. A good project has design documentation, code comments, and code, all referencing each other, each understandable in its own terms (the code by both humans and machines). And of course all maintained in sync with the other, which they all reference.

      The need for each of those work products by different people/machines at different parts of the project cycle is one reason I've been waiting for flowchart programming for many years. When we can flip between lexical and graphical representations of the same executable, with attached multimedia documentation, we'll have much more efficient team understanding of the code. Object techniques have brought us a lot closer, but we still have a lot of skills (topological sense, geometrical arrangement) that we can use to work better to make the machines do what we want, not just what we asked for.

      --

      --
      make install -not war

    9. Re:Comments First by Anonymous Coward · · Score: 0

      Actually if you have to scroll down to match delimiter, then your blocks might be too long already.
      try breaking code in smaller chunks.

    10. Re:Comments First by Doc+Ruby · · Score: 1

      While modern compilers optimize away most CPU jumps to factored code calls, there are still good reasons to have blocks (especially functions) longer than 24 or 80 lines or so. Most readers find it easier to scroll than to jump to other scopes factored out of a sequence. And some sequences of operations are best read in a fairly long run, rather than "hypertexted" into nested subroutines. It's not common, but when it's appropriate, that's when I label the delimiters. I always label function closes with the name of the function (or its entire signature, where ambiguous). What I'd really like would be an editor that would un/roll subroutine definitions inline on request, so I could look at the called code along with the calling code without switching contexts. Or another pair of eyes for multiple monitors...

      --

      --
      make install -not war

    11. Re:Comments First by bprime · · Score: 2

      I prefer my comments to be in the present tense.

      Do you also prefer non-gendered pronouns and clothing products made out of human skin?

      (It puts the comment in the code. It does this whenever its told.)

    12. Re:Comments First by Doc+Ruby · · Score: 1

      I do prefer nongendered pronouns when I don't know the gender. And I like leather clothing - are you volunteering?

      --

      --
      make install -not war

    13. Re:Comments First by customiser · · Score: 1

      I don't really disagree with what you are saying. My point is basically that the easier a commenting convention is to follow and the least overhead it places to development, the greater the likelihood of it being observed. And it's better to have adequate commenting that everyone follows than great commenting that is only there half the time.

    14. Re:Comments First by andyross · · Score: 1
      Good comments are written first [...] gramatically correct, punctuated [...] I put comments inside practically every block [...] after block closers. [...] I'd rather spend a few more seconds typing up front, and save a lot of scrolling and delimiter-matching later (not to mention reducing confusion and mistakes).
      Maybe if you didn't have so many comments in the way, your functions would be shorter and more readable and you wouldn't need to do so much scrolling and delimeter matching. Writing short, meaningful functions is IMHO far more important than having clear comments. It sounds to me like you are using comments as a crutch to make up for your use of spaghetti code.
      Code gets shuffled around in different order, read by strangers, and reread much later by yourself, often after you've changed by experience
      And if you think said modifications will preserve the comments in their original positions and meanings, I have a bridge to sell you. Elaborate and extensive commenting adds a failure mode to code modifications -- even correct comments can rapidly become lies.

      There's a great quote to this effect, something like: "Don't read the comments, they lie viciously. Debug only the code." Does anyone have the attribution?

      Actually, your position is so extreme that I'm honestly not sure if this was sarcasm or not. If so, my apologies and thanks -- I was definitely amused.

    15. Re:Comments First by Henrik+S.+Hansen · · Score: 5, Insightful
      Good comments are written first, before the code, describing what the following code does.

      That's some of the worst advice I have seen wrt. code commenting. Comments should never describe what the code does. If it is not obvious from the code, it should be refactored.

      The strategy of verbose and essentially redundant comments are bound to end up in outdated and/or useless comments. If such a practice is employed in industry, forcing people to comment every loop, etc. as you describe, I'm certain there would be a lot of useless comments.

      People will simply not do something, which they cannot see how they would later benefit from. Classic CSCW problem.

    16. Re:Comments First by legirons · · Score: 1

      Good comments are written first, before the code, describing what the following code does.

      That's because the design tools are crap, and you're left to use comments as a replacement for them.

      I know what you mean, and I use comments that way all the time. But only because my company doesn't own a single decent UML, flowcharting, or outlining tool.

    17. Re:Comments First by booch · · Score: 2, Insightful
      Comments should never describe what the code does.

      It seems that most folks here believe that -- that you should only comment on why you're doing things, not what you're doing. But I think that's a bad idea. For example, let's say you've got some "code" that says:
      Combine an egg, some flour, some milk, some sugar, ...
      I would contend that the comment should be "make a cake". I suppose you could contend that tells why we're combining the ingredients, but I think it's more clear to say that that is what we're doing. My point is that what we're doing is not at all obvious from just looking at how we did it.
      --
      Software sucks. Open Source sucks less.
    18. Re:Comments First by Doc+Ruby · · Score: 1

      Who caress whether you're amused? In 30 years of programming, I've learned how to comment code so it's maintainable by me, a team, or anyone else. You don't even know what "spaghetti code" means - it's when you have too many jumps around too many scopes. If you're not competent to update comments to reflect code changes, that's your major malfunction. I pity anyone who has to work with you. Because your position is the extreme one - why not just eliminate all bugs by leaving out all comments and all code, avoid computers altogether? From the coding insights you've revealed, it sounds like we'd all be much better off if you did.

      BTW, the "H" in "IMHO" means "humble" - another programmer buzzword you obviously know nothing about except that quoting it makes you look like you know what you're talking about. Poser.

      --

      --
      make install -not war

    19. Re:Comments First by Doc+Ruby · · Score: 1

      Who said comments have to be "verbose" or "redundant"? Comments are there to describe the code. Your remark that they should "never describe what the code does" is the most ridiculous possible. What, then, should comments do? Talk about "useless comments"...

      --

      --
      make install -not war

    20. Re: Comments First by halleluja · · Score: 1
      It helps clarify my thoughts about how I'm going to go about it, and of course keeps me from forgetting anything.
      /* main.c
      code will exit correctly
      next time, get sober first
      more beer in left drawer
      */
      int main(int aargh, char **aaaaargh)
      {
      return 42;
      }
    21. Re:Comments First by TLLOTS · · Score: 1

      You've completely misunderstood what was meant. I'll show you, for your example psuedo code, if I were to comment it saying what the code does, it would look like this.

      //Combine an egg, some flour, some milk, some sugar, etc.
      Combine an egg, some flour, some milk, some sugar, ...

      If I were to describe why the code does what it does, it would look like this

      //Combine various ingredients to make a cake
      Combine an egg, some flour, some milk, some sugar, ...

      You're wrong to say that what the code does is hard to tell from the code alone, because I can clearly see that what it is doing is combining a series of ingredients. Why it is doing that is a job for the comments if the code itself doesn't make it immediately obvious.

    22. Re:Comments First by booch · · Score: 1

      Let's say you are baking a cake. Someone asks you "what are you doing?". Would you really answer "I'm combining ingredients"?

      --
      Software sucks. Open Source sucks less.
    23. Re:Comments First by TLLOTS · · Score: 1

      No, I'd most definitely give an answer reflecting why I'm doing what I'm doing, as I can easily make the assumption that the person asking me is well aware what it is I'm doing, and infact wishes to know why I'm doing it.

      You might of course explain what it is you're doing if the task were of sufficient complexity that it was reasonable to assume the asker would have trouble understanding it. However, when applying that to coding it means either of two things. 1. Your coding style needs work and you should attempt to refactor it to improve readability, or 2. Your task is extremely complicated and impossible to break down into a more readable fashion.

      Realistically 2. should be a very very rare occurence, one you should minimise wherever possible. Certainly I will agree it is sometimes necessary to comment on what it is your code is doing, but commenting should never be used as a crutch for a poor coding style, which more than anything is something I believe the original poster was arguing against. Certianly you should never comment what even the simplest things are doing, e.g.
      //Defines an int named 'integer_one'
      int integer_one
      is completely useless.

      Commenting sparingly where appropriate is crucial. Commenting excessively can be as harmful or even more harmful than not commenting at all

  30. There are loads of comments in Haiku... by McCall · · Score: 1

    There are a ton of comments in Haiku. Just take a look at their SVN.

  31. How to write stories by Prince+Vegeta+SSJ4 · · Score: 1

    what they seem to need is a class on how to write stories, have you not seen the first sentence of THIS monstrosity?

  32. Re:Here you go... by Xaositecte · · Score: 1

    dear casualsax,
    you have a stick up your ass.
    Kindly remove it

  33. OMG First Post by minginqunt · · Score: 0, Offtopic

    KDE SUXX0rs. All the kewl kidz use teh Macs now!

    ---

    Now that's a *great* comment. Lame, inaccurate, ignorable, irritating, worthless.

    If I keep this up in my code, it'll be so unmaintainable by any other, I'll be secure in my job for life.

    Martin

    1. Re:OMG First Post by minginqunt · · Score: 1

      Tsk. It's almost as if some moderators never get past the subject before they moderate.

      It was supposed to be a joke.

      Martin

  34. You are not expected to understand this by Rob+the+Bold · · Score: 1
    I've used some of the corallaries to this comment, e.g.

    /*Be afraid. Be very afraid.*/

    Once I actually did use the "/* you are not expected . . ." comment and got a severe talkin'-to by my boss about being a "team player". After that incident, I only commented in Latin and Klingon for that employer.

    --
    I am not a crackpot.
  35. slashdot sucks by Anonymous Coward · · Score: 0

    start an account, start a blog, and post your articles to mods to have posted as "stories"

  36. Comments Not Needed... by SparafucileMan · · Score: 0

    ...if you wrote your code clearly enough. Any well written code is as easy to read as comments and is more informative. By doubling up and reading the comments as well, you're just wasting your time.

    Of course, alot of code isn't well written so comments ("pseudo code") is necessary just to understand it. The sign of either a bad programmer or a system or language that is too complex.

    The name of the game is find the right language, and you won't have to juggle two or five poorly written languages.

    1. Re:Comments Not Needed... by bmalia · · Score: 2, Insightful

      "Good code" will be easy to read AND have good comments. For example, my company has some old SQL Reports that need to be maintained on rare occasion. I can kind-of-sort-a make out what the code is doing, but I am not used to that syntax and I havn't been able to find any tutorials for the stuff on the web anywhere. It sure is nice to have comments along with the code that I can read in english what the code is doing. "This will print the subtotals","This pulls the exchange rate", etc. Does that make it a bad programming language? Probably, but it still has to be maintained. Life sure would be alot more difficult for me if the original programmer of those old reports had thought that comments were a waste of his time.

      --
      There's no place like ~/
    2. Re:Comments Not Needed... by SparafucileMan · · Score: 1

      Yes you're right.

  37. Haiku? by Daedala · · Score: 3, Funny

    Remember the seasonal reference!

    Begin declaring
    Global integers, constant
    As the winter rain

    Check for null values
    That will cause problems later
    Cherry blossoms fall

    --
    What I say does not represent the views of my employers, my friends, my cats, or myself.
  38. Re:Check out Rob Pike's thoughts on code commentin by squiggleslash · · Score: 5, Insightful
    I'm not sure I do.

    He's used two stupid examples of commenting, examples that are popular jokes, rarely appearing in real life and usually the result of sarcastic nudge-nudging from experienced programmers, and pretended that's what we're talking about when we talk about commenting. When he finally admits they may have a use, the description is so vague it's hard to see what he means - which, if he comments the same way, is probably as true of his code as it is his prose.

    It doesn't take much, or add any clutter to code, to put a brief, one or two line, comment before each paragraph of code, that describes the intended functionality of the code block. It makes a massive difference when you revisit your code three years, or even three months, later, or worse have a collegue look at it.

    Nor is it a massive imposition to have more obscure decisions you've made be explained in a comment block before the code itself.

    Code is not self-documenting. It becomes intensely verbose when you try to make it self-documenting, and it's rare that anyone, no matter how well skilled, can produce something that transmits the intended functionality of the written code in the implemented functionality. This is especially true if you're using an optimal algorithm. Reasonable, non-excessive, use of comments, describing functionality rather than function, are extremely important.

    --
    You are not alone. This is not normal. None of this is normal.
  39. One good reason by Billosaur · · Score: 2, Informative

    You should write comments because some day you're not going to be doing your job anymore, perhaps because you started your own rock band, or won the lottery, or the company decided they could get someone cheaper to do your work. In any case, some unfortunate soul (and I've been this person more than once) has to come in and maintain and expand your code. And in most cases we're bright and we know our languages pretty well, but we can be a little slow on the uptake. In the end, we stare at your code and ask, simply: What the freak is going on here?!?!? Because we are not mind readers, and if we were, we probably wouldn't want to touch your mind because... ewwwwwwwww!

    Does this mean you have to do this?:

    my $i = 0; # initialize variable $i

    No! We're not retarded... we think. But if it's not trivially obvious what you're doing somewhere in your code, please feel free to let us in on it. We would appreciate it.

    --
    GetOuttaMySpace - The Anti-Social Network
    1. Re:One good reason by f0rtytw0 · · Score: 2, Funny

      As my professor once told us "Write code so that your pyschotic successor does not hunt you down and kill you."

      --
      this is the most important sig ever! In your face 446154!
  40. Commenting has its uses. by Malpheus · · Score: 1

    As an engineering student in college, failing to comment in my code is equivalent to failing at life. Our profs say it's common courtesy to comment code, especially in industry. As one who has had to read the code of others, I can say it does help at times. So keep commenting, if only for the stupid people.

    --
    Free you mind. May the Force be with you.
    1. Re:Commenting has its uses. by pyser · · Score: 1

      C A comment per line
      C means you're doing just fine

  41. Javadoc and XDoclet as models by coyote-san · · Score: 1

    I've written a lot of comments, and most of it was useless. It helps when you're looking at the code itself, but you missed the larger context unless every comment was mindnumbingly detailed. That type of comment is a pain to write and essentially unmaintainable.

    Javadoc (and similar well-supported systems) is godsend. You still want to have some comments within your code, but the real power is in the generated documents that give you the larger picture. It's not complete -- you still want to know the overall architecture and design -- but many days I would rather have empty Javadoc (with nothing but links to the classes used as parameters and results) than well-written but isolated comments within the code, especially if reasonably sane class and method names are used.

    XDoclet takes this one step further. The comments don't just produce useful documentation, they produce useful configuration files and even related source code.

    --
    For every complex problem there is an answer that is clear, simple, and wrong. -- H L Mencken
  42. Explain Things That Need To Be Explained by Py+to+the+Wiz · · Score: 1

    Ive been in enough classes this year (well below my level.. dammit, I need the "letters") that Ive come to the conclusion that introductory programming courses are taught all wrong.

    Write 5 lines. Write 20 lines. Write 100 lines. Of useless and pointless code.

    What should be done is: Take this 1000 line programme. Add on 5 lines. Add on 20 lines. Add on 100 lines. Beacuse that would require being able to read code, too. Being able to understand what is already there is frequently more then half the battle. Saying "What the fuck does this mean?" a few dozen times is the only way to get to write comments. Being a sysadmin, rather then a full time programmer, this took me litteraly years to learn. And it was usualy "What the fuck were you doing here, brain? Dammit, one of these days were going to have to start commenting our code."

    About 6 months ago, I read through a project request on one of these ebay-for-coders sites. Language optional; 1 comment per 5 LOC, but if using Perl, 1 comment per 2 LOC.. With requrements like that you are only asking to get BS comments like "Print X to the console".

    --
    Fight the fall of slashdot by supporting PlayfullyClever in your sig.
  43. Re:Check out Rob Pike's thoughts on code commentin by prgrmr · · Score: 2, Insightful

    "Procedure names should reflect what they do; function names should reflect what they return"

    This is one of the most effective methods of producing self-commenting code and I wish everyone writing programs would do this.

  44. good code is not self-documenting by petes_PoV · · Score: 0, Insightful
    this is a common mistake that some beginners and most managers make. It usually only survives in their minds until they have actually read someone else's (supposedly) self-commented) code.

    As the OP says, code will only ever tell you the "how" not the "why". As in this snippet:
    i++ ; increment counter
    while trivial, it tells you nothing about why you wish to increment the counter. Ada,C(++) or any other high-level language is always limited to this.

    The best comments are a summary at the start of a block of code that describes the autors intent. It should have correct spelling and grammar. if the coder can't even get the coment right - the code is probably wrong, too.

    --
    politicians are like babies' nappies: they should both be changed regularly and for the same reasons
  45. Definitely Haiku by Rorschach1 · · Score: 1
    comments in haiku
    not for any good reason
    I was very bored

    (And yes, I have done this. The bit above and several others are, as far as I know, still in some shipping management system for a certain multinational mining corporation.)

  46. /* Drunk -- fix later */ by Cobalt+Jacket · · Score: 2, Funny

    © Leo Plotkin

  47. Even Worse by PlayfullyClever · · Score: 1

    I used to grade student's code as a TA at my university, and I'll tell you what is more annoying than NO comments, this:

    printf("Encrypt message...");/* print "Encrypt message..." to the console */

    and then followed by about 150 lines of uncommented spaghetti code

    --
    Check out my website: Playfully Clever
    1. Re:Even Worse by CynicalGuy · · Score: 1

      Although it does make it easy to tell when the student copied the assignment from someone else.. :)

  48. It should be hard. by www.sorehands.com · · Score: 1

    It was hard enough to write, so it should be hard to read.

    Anyways, code is obvious to a REAL PROGRAMMERS.

  49. Obligatory... by Saeger · · Score: 1

    ...I don't comment code for job security. Besides, comments are for the weak; good code should be self-documenting (but my code isn't good either, because I have to obfuscate it... again for the mythical job security).

    --
    Power to the Peaceful
  50. Intelligent response //add to this by 0110011001110101 · · Score: 1
    Hello slashdotters //make this wittier

    //put more believable words in here, sometimes larger words
    //convince the /. crowd that Im actually intelligent
    I would like to say that commenting code has helped me many times to more completely understand the crap my co-workers produce.

    //TODO: make the following post an actual haiku, to amuse
    //the more advanced crowd
    Haiku comments would be disastrous

    //TODO: add funnier sig, this one sucks

    --
    Don't anthropomorphize computers: they hate that.
  51. !- -pretty words go here- - by kevin.fowler · · Score: 0

    working in XML in content development, I really can't add personal flair to code; many cooks are working on one pot. I am however a firm believer in commenting so that everyone in your project knows what the hell is going on. much more useful than having one comment per 3 lines of code like I had to have in college projects. (3 points off my final because one of the comments read "my sister was once bitten by a moose")

    --
    Bury me in mashed potatoes.
  52. Comments by Live_in_Dayton · · Score: 1

    I saw the RSS title and I thought it was about writing comments on /. Am I spending too much time on this web site?

  53. how to write comments by BushCheney08 · · Score: 1

    1) Press 'Reply' button or click 'Reply to This' link.
    2) Type witty reply/comment/troll in box. Don't forget to include a subject.
    3) Click 'Submit' button. Note: Under no circumstances should you click the 'Preview' button!

    --
    Be a real patriot: Question authority. Think for yourself. Formulate your own conclusions.
  54. The code was hard to write.... by mcsporran · · Score: 1

    Therefore it should be hard to read.....

    --
    This is NOT a signature.
  55. Docs more important... by cosinezero · · Score: 1

    I think documentation goes a lot further than comments. Chances are, with good docs and proper unit testing, I never have to read the source on your object.

    1. Re:Docs more important... by weg · · Score: 1

      Unless "your object" is a class library of course. In that case, not commenting classes and functions breaks encapsulation (because users have to dig around in the internals).

      --
      Georg
    2. Re:Docs more important... by cosinezero · · Score: 1

      Document individual objects & methods.

  56. Re:Check out Rob Pike's thoughts on code commentin by eronysis · · Score: 1

    What a great read! Thank you!

  57. Comments need to include rationale by Anonymous Coward · · Score: 0

    Hi - I have heard this "proper code does not need comments" idea for years. What this ignores is that many times there are multiple ways of implementing something. In such a case IMO it is very helpful for the original developer(s) to explain why they chose a certain method / algorithm over another. As times goes on, things often change (price of storage, memory, etc) and the original factors may no longer be as important in years to come. A related area is when there is a bug in the software (compiler or interpreter etc) that is being coded around since future versions may fix the bug or provide an entirely different method.

    TWR

  58. Various commenting style... by Anonymous Coward · · Score: 0

    Well, comments are sometimes needed, but sometimes...
    // Beginning
    // Middle
    // Endpart
    //  IMPORTANT HERE

    or something in one of the books. A page explaining workings of a program. Then a page of listing of the program, about 60 lines of comments on how it's supposed to work. Repeated from the previous page. Then 5 lines of actual code total, quite self-explainatory too.

    Or:
    y = x - x - x; /* Just you dare changing this!!! */

    or:
    <!-- A79BD69D8DD324F9DF -->

    or:
    for(i=0;i<maxT;i++){  /* This is a very tricky   *
    unit[i]=another[i]%c;  * part so pay             *
    if(!unit[i]) break;    * close attention         */
    }

    There are quite a few more ways to comment the code in a creative way that will drive whoever reads your code nuts.

  59. Self documenting by Dun+Malg · · Score: 1
    Real programmers write self documenting code, so even if your boss makes you put in comments, all you really have to do is repeat what the code says:

    int x, y, z;
    snizlr mfSnizzlr; //create variables
    x = 10; //set x equal to 10
    mfSnizzlr(y,z); //call snizlr to get y and z
    for(int z1=0;z1 < z;z1++) //start at 0 and loop until z1 reaches z
    {
    y = (z>x) ? z : x; //set y to appropriate value
    mfSnizzlr(y); //y back to snizlr
    }

    return(y); //return y

    see? easy!

    --
    If a job's not worth doing, it's not worth doing right.
  60. Writing Comments by Nom+du+Keyboard · · Score: 1
    Writing comments helps you understand that you know what you're doing.

    And useful later on when you need to fix your own code after plenty of time has passed allowing you to forget how clever you were in the first place.

    --
    "It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
  61. If you don't comment it will come back to haunt u by gasmonso · · Score: 2, Interesting

    Commenting code is good on several fronts. Firstly, even the programmer can't remember what the hell he did just a few weeks ago, let alone several months or years. You will thank yourself. Secondly, anyone else who has to modify that code will track you down to explain something if it's not commented. If you use source control, they will find you. And thirdly, it's easy to do while you're coding and not after. It's almost a freebee.

    gasmonso http://religiousfreaks.com/
  62. General comments guidelines by Foofoobar · · Score: 1

    I like my comments to have brief description and show example of usage to cover the 'hit by a train' scenario. Also with good comments, you don't require as much documentation... which is a shame because WE ALL LOVE to write documentation! /* getFunction(array,int);
          desc: Function is described here
          usage: this->getFunction(names,number); */

    --
    This is my sig. There are many like it but this one is mine.
  63. Re:Here you go... by Anonymous Coward · · Score: 0

    > dear casualsax,
    > you have a stick up your ass.
    > Kindly remove it

    dear Xaositecte,
    you have a grudge on your shoulder.
    be nice, and casualsax might let you remove that stick for him...

  64. but good data structures often arent by egarland · · Score: 1

    I dislike comments mostly but one thing I do like commenting is complex data structures.

    --
    set softtabstop=4 shiftwidth=4 expandtab nocp worlddomination
  65. Self-Documenting by sconeu · · Score: 1
    Everybody knows that good code is self documenting- which is why my prof in college demanded we write in Ada.

    You don't know how right you are. I once got some some Ada code from a third party. Each procedure had a block comment describing the its function. The block comment? Literally the procedure code, commented. When we asked, we were told the code was self documenting.

    i.e. it looked like this:
    -- procedure FOO is
    -- begin
    -- TEXT_IO.PUT_LINE('Hello World');
    -- end FOO;
    procedure FOO is
    begin
      TEXT_IO.PUT_LINE('Hello World');
    end FOO;
    --
    General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
  66. comment to lament by digitaldc · · Score: 1

    /*
    * If you have to read this
    * then you are not smart enough to figure it out for yourself
    * why should I even try to explain it to you?
    * pick up a book and figure the damn thing out on your own, that's what i did
    * if you change any lines of code hereafter, you will be sued and defamed
    * i say good day
    */

    --
    He who knows best knows how little he knows. - Thomas Jefferson
  67. Why you must (sometimes) comment code. by swagr · · Score: 1

    Code always documents exactly what the code does.
    Documents document what the code is supposed to do.

    --

    -... --- .-. . -.. ..--..
  68. How to write comments? by Chaffar · · Score: 1

    I encrypt all my comments in double ROT-13, it helps me keep my job :)

  69. Commenting code...more than just best practice. by ashtophoenix · · Score: 1

    Commenting code in a good way is as important as writing good code. Think from the perspective of the poor maintenance programmer. How much time would be saved if code was properly commented? Isn't it after all about not wasting energy, ours and the other person's too? It's so much easier to comment code while one is writing it, or has recently written it since its fresh in the memory. The further you comment it from the point of writing, the more the chances of the comments not being accurate. And I would rather have no comments than wrong comments :) Commenting code in a useful way, thinking about a maintenance programmer who knows nothing about this code, is not just a 'best practice', it is the duty of any programmer who takes pride in his/her work.

    --
    Life is about being a Phoenix!
  70. mod parent up by Anonymous Coward · · Score: 0

    1. Pick up a topic where everyone has something to say
    2. Write a basic article on the topic with no new insights
    3. Post it to /.
    4. Popularity!!!

  71. Good comments, or mediocre comments? by cperciva · · Score: 1

    The discussion so far seems to have centered around comments which are not good, but rather mediocre -- comments which are likely to give a hint as to what the code does, but not to provide a convincing explanation as to why the code works.

    In my opinion, a good comment is one which starts with \begin{theorem}, ends with \end{proof}, and provides a formal statement of what the code in question is supposed to accomplish, along with a proof that it works.

  72. How about... by Anonymous Coward · · Score: 0

    /** Teri in Accounting unbuttons her blouse ... **/
    /** Increment to avoid null pointer reference **/

    Seriously, though I'd like to see a chunk of useful comments preceding a block of code. Take out the code, and you'd have virtually a 'black box' describing what went in, what transpired, and what goes out. For the benefit of the poor individual your code got outsourced to, many many years later.

  73. How about for the pramming-skill challenged? by ||Plazm|| · · Score: 1

    Good code *is* easy to read....for many. But what about someone who is new to a project or new to an implementation?

    I don't agree with the practice, but we often had engineers coming in and spending 2-3 days or even a week before they would head back to work on whatever it was that they were working on. Mostly this occurred when people went on vacation or if they needed help, but good coding practices as well as good commenting practices were very helpful. Essential? Probably not, but it does take out any interpretation errors that might occur.

    Most of us are still human, aren't we? ;)

  74. Humour in the Linux kernel by Mr_Silver · · Score: 4, Funny
    This made me smile (in a rather sad way)...
    static void happy_meal_tcvr_write(struct happy_meal *hp, unsigned long tregs, int reg, unsigned short value)
    {
    int tries = TCVR_WRITE_TRIES;

    ASD(("happy_meal_tcvr_write: reg=0x%02x value=%04xn", reg, value));

    /* Welcome to Sun Microsystems, can I take your order please? */
    if (!hp->happy_flags & HFLAG_FENABLE)
    return happy_meal_bb_write(hp, tregs, reg, value);

    /* Would you like fries with that? */
    hme_write32(hp, tregs + TCVR_FRAME, (FRAME_WRITE | (hp->paddr
    Mind you, it's not a comment but this one was good for printer status:
    static char *usblp_messages[] = { "ok", "out of paper", "off-line", "on fire" };
    --
    Avantslash - View Slashdot cleanly on your mobile phone.
    1. Re:Humour in the Linux kernel by Anonymous Coward · · Score: 0

      if (!hp->happy_flags & HFLAG_FENABLE)

      Too bad that line of code has a rather serious bug in it - "!" has higher priority than "&", and !anything will be either 0 or 1.
      Fixing it would be as simple as either putting in an extra set of parentheses or changing the "!" to a "~".

    2. Re:Humour in the Linux kernel by Exaton · · Score: 1

      Saw the fortune on /. yesterday :

      $ fortune -m "trinity lp0"
      (knghtbrd)
      %
      Feb  5 13:27:01 trinity lp0 on fire
          -- the Linux kernel, alerting me that there was some unknown
             problem with my printer (ie, it was out of ink)
      %

  75. Highkoo by Quiet_Desperation · · Score: 1

    /*This code does some things.
    I should have commented it.
    Mysteries abound.*/

  76. Commenting getters-setters by ashtophoenix · · Score: 1

    How do people deal with pure getters-setters in terms of commenting them. I mostly just leave them out, if they exist simply for the purpose of accessing/mutating (without any error checking or validation). I mean the dumbest form of a getter or setter. Some purists may want to comment every method of a class, but I don't see the point of it. Maybe it makes them more amenable to being commented in the future?

    --
    Life is about being a Phoenix!
    1. Re:Commenting getters-setters by hey! · · Score: 1

      I'd also be interested in what is considered good practice.

      There is one place C# is pretty nice, IMO, because while getters and setters are in principle a good thing, they are syntactic clutter that leads to this kind of purposeless conundrum.

      What clearly needs to be documented is the attribute (which may be in a sense purely an API rather than a thing). I find it convenient to do this in the setter, because I can also describe any constraints I want to put on the attribute:


      public class Foo {
              private int bar;
              public int getBar() {
                      return bar;
              } /**
                  * The <code>bar</code> of a Foo is the priority we assign to the Foo.<p>
                  * @param newBar -- the new priority; 0 is low; must be >= 0.<p>
                  */
              public void setBar(int newBar) {
                      bar=newBar;
              }
      }

      --
      Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
    2. Re:Commenting getters-setters by borkus · · Score: 1
      I get a laugh from comments that just parrot the internal variable name for a getter/setter. For example -
      setItemIDCode(String itemIDCode)
      /** sets the itemIDCode **/
      Usually, you see this kind of stuff in IDE generated code. It's stupid but often not worth the effort to go back and delete.

      If you name your member variables so that they're easily understood, the getters and setters should be self-evident. However, if you have a class with members that could be confused, use the comments to explain the specific fields. For example, if you have a class with fields like
      getQuotedPrice
      getAdjustedPrice
      new developers might not know the business differences between the fields and end up misusing them.
  77. Make them few, make them count by hey! · · Score: 1
    Too often comments are misleading, or out of date, or try to explain mechanism. Here is an example of all these problems:


    foo--; // increment foo


    Here the original comment was totally useless. All it does was clutter and distract from potentially useful information. Now it is worse than useless, as most mechanics oriented comments are.

    Code must carry two burdens: to make the intent of the programmer clear, and to implement the programmers intent. If the mechanics of the code are clear, they need no comment. If it isn't clear, it needs reorganization. But what may not be clear is the intent is. This is particularly true in elaborate or complex loops. Here is an example:

    // dataStructure must be checked out valid ABOVE here.
    // anlyze dataStructure and set up derivative products A and B.

    while sometest(dataStructure) {
            blah1;
            blah2; ...
            blahn;
    }
    // A and B have been computed at this point. Maintainers should not
    // modify A or B below this point.



    This shows some common patterns in my code. I like to place a signposts saying what needs to be accomplished before a piece of code executes, and what kinds of assumptions it's safe to make after it executes. Often though if you are working in a system which allows you to create procedures without polluting the encompassing name spaces, refactoring the code achieves the same purpose:


    final ImmutableThing A,B;
    if (validDS(dataStructure))
          (A,B) = analyze(dataStructure); // comment no longer necessary.


    So sometimes the need to do an elaborate comment tells you that you need to reorganize your code. I like to shoot for procedures/methods that are less than thirty lines long; ten or less being ideal. This in part comes from having been trained early on in functional programming.

    The advice in the article about documenting class relationships is very sound. Comments need to be maintainable just like code, and as such they need to obey the same design rules as code, the chief rules they have in common are:

    1. Assumptions need to be put in one and only one place.
    2. Important stuff needs to be easy to find.
    3. Be neat.
    4. Be consistent.
    5. Focus on preconditions and outcomes.
    6. Accomplish the maximum effect with the minimum stuff, without trying to do two things at once.


    --
    Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
    1. Re:Make them few, make them count by ashitaka · · Score: 1

      foo++; // increment foo

      Fixed that for ya.

      --
      If you don't want to repeat the past, stop living in it.
    2. Re:Make them few, make them count by rjstanford · · Score: 1
      foo++; // increment foo

      Fixed that for ya.


      Aha - but how do you know it shouldn't have been:
      --foo; // decrement foo
      Rule of thumb: if the comments and the code don't match, don't trust either one of 'em.
      --
      You're special forces then? That's great! I just love your olympics!
  78. If you think... by zullnero · · Score: 1

    ...your code has a chance of sticking around for awhile, as in there may be a chance someone might have to update some of it in several years down the line. If you don't comment that, then someone, somewhere (if it's not you yourself) will curse you onto infinity.

    Well-written code is truely in the eye of the beholder, and is subjective to current trends, personal preferences, etc.

  79. Closely linked with good code by AlvySinger · · Score: 2, Informative

    It's pointless writing "good" comments on bad code. Write clear obvious code that doesn't rely on needless tricks or language side-effects.

    Layout is important but don't get obessive. You'd write prose using paragraphs, use whitespace in code.

    Good comments are hard because, like code, bad comments are very easy. Don't describe what's obvious from the code. Why is better than how. Don't spend ten lines describing a pattern when you can refer it by name.

    Don't add redundant comments (and this is from someone who writes more than my peers). Twenty lines of boiler-plate for each method is pointless. If there's a need for a detailed change history then your source-control should provide this. If the code requires heavy detail try refactoring it to make the code clearer.

    Simple metrics are difficult but look at your code without comments and imagine what'd be useful if your coming at it blind. What would you want to see? (Try this with a random sample of colleagues code. Typically - from experience - you won't have to spend too long removing comments because there won't be any.)

    And the difficult bit: make sure you're in a culture that values comments and documentation. It's pointless crafting detail now if some future developer will ignore them or not maintain them.

    Finally, none of this is exact. Everything about can be argued. Get some literature (McConnell, Brooks, etc.) and learn from this too. Use what the situation demands, don't apply things where they're not warranted.

    1. Re:Closely linked with good code by try_anything · · Score: 1
      It's not pointless at all. Somebody is going to have to fix the code, and it helps to see code out of sync with comments - it means something is fishy and needs to be examined closely. If I see

      // get a random prime number
      p = 2 * random_int() + 1;

      then I immediately see a bug: the guy who wrote his code thought all odd numbers were prime. He's an idiot, but he helped me debug his code. If he carried on thinking p was prime but never documented that mistaken assumption, figuring out the bug would have been ten times harder.

  80. Remember assembly? by Anonymous Coward · · Score: 0

    Anyone here programming assembly language? Nice way to learn commenting. Almost every line is being commented. Since you can't take much freedom at naming variables, functions etc, and calling things by physical register/mnemonic names (R1, ACC, RL, DPTR) instead of variables/commands (i, refCount, *=2;, (char*) username;) forces you to comment EVERY SINGLE LINE of code (with rare exceptions like one operation takes two mnemonics) or you'll get hopelessly lost in what your program is doing. Comments are usually 70% of an assembly listing (considering how brief the mnemonics are), and you comment everything, a function: How the input is passed, what means what, what registers are used (so they have to be pushed on stack in case of some other function called from inside), how the return value is given, then you comment what which register does, because there's no way to distinguish loop counter from higher byte of a floating point value without analysing the code, and finally you comment practically every operation, because practically nothing is self-explainatory.

  81. A comment is written communication. First rule: keep your audience in mind. What will the maintenance programmmer want to know? /*
      * This odd-looking construct works around a Windows bug using the workaround MS recommends. See their article KB######
      */ /*
      * If you change this, you'll also need to make a parallel change in sssss.c, function XxxYyyy()
      */ /*
      * Initializing libAlesandria with this set of parameters was an arbitrary choice. You should be safe
      * if you make changes
      */

    sleep(100); // Problem report NNNN from integration test: wait for signal to stop bouncing on rev D2x boards

  82. 'Why', not 'How' by lawpoop · · Score: 5, Insightful

    The code is the 'How'. What the reader needs to know is 'Why' you are taking these steps. What larger goal are you accomplishing? What is the purpose of this code? What is its justification for existance?

    Fill in this blank: "If were weren't running this code right here right now, we wouldn't be able to do _____. We could have done it this other way, but we chose this method because of X, Y, and Z.

    In a real world example, code is like "Turn left, Go to High Street, turn right, continue on to 1122 High St, pull into the driveway, and park the vehicle." Those are the steps taken, but the goal you are acommplishing is "We want to return the library books, so we are going to drive the books to the library using the car."

    OK, so why are we taking the books to the library? Ultimately all comments will filter up to the goals of the application. They are all nested subgoals of the design specs.

    --
    Computers are useless. They can only give you answers.
    -- Pablo Picasso
    1. Re:'Why', not 'How' by Speare · · Score: 1
      One, I have a rule I teach to any programmer under my supervision: strategy in comments, tactics in code. Tactics are what you do to get something done. Strategy explains what you want done. In warfare, an officer focuses on strategy: "secure that hill!" "pick the best two devices!" "find the local minimum!" Don't mention the tools you use to get that job done, soldier, unless there's a good reason for being fiendishly clever. Comments should be in natural human language, while the code should just accomplish those tasks.

      Two, I have a technique I teach to any new programmer, whether they're under my supervision or not: write the comments first. Programming courses always talk about writing pseudocode: why write it on scratch paper, just to throw it away?

      sub process_ring_packet
      {
      # if we have a prior server registered,
      .# if this packet was received from the prior,
      ..# if this server created this packet originally,
      ...# kill the packet, it's completed the trip.
      # scan the packet for all object references.
      # dispatch packet to object mentioned which we control.
      # if any object references remain unhandled,
      .# if we have a next server registered,
      ..# send the packet to the next server.
      }
      (Here's another concrete example of why the compression-as-lameness-indicator is not helpful. Think of the dots as indentation.) Once the pseudocode is written in human terms, then fill in your actual code in whatever computer language is being employed. Note that I didn't say HOW to do each of the tasks in the comments. I just wrote what needed to get done.

      Lastly, as others have indicated, the actual code should not be too clever for your teammates to understand at a glance. Use clear concise words for variable names, without abbreviating them unnecessarily. Use the idioms they're familiar with. Use the language they're familiar with. You shouldn't need any # swap $x and $y comments to explain basic tasks or idioms. If you really find a clever but unusual trick, or you need to hack out something that's not obvious, then you can mention it.

      I have taught my editors to highlight tags like #REVIEW: #TODO: #BUGBUG: #HACK: so I can see areas that need more attention. Review things which may or may not be right or done in the best way. List things that are definitely undone but needed. Mark areas where known bugs are located, even if the fix isn't in there yet; give bug tracking numbers if appropriate. Mark code which is overly clever to get around dumb library limitations or which save a lot of processing in obscure ways.

      --
      [ .sig file not found ]
    2. Re:'Why', not 'How' by Anonymous Coward · · Score: 0

      Books? They're like offline websites, right?

    3. Re:'Why', not 'How' by booch · · Score: 1

      I think everyone here, and everyone past first-semester programming classes would agree with that. The big argument here seems to be whether to comment on what the code does. I seem to be in the minority who believe that comments should tell what. But even your example better answers what you're doing than why. Note that the what people seem to want to comment a bit more than the why people, and in fact there's a large portion (like me) who write the what comments before the code.

      --
      Software sucks. Open Source sucks less.
  83. Are you certain this is what you want? by palad1 · · Score: 2, Funny

    public void GNAAT()
            {
                System.IO.Stream stream = System.Net.HttpWebRequest.Create("http://www.goats e.cx/receiver.jpg").GetResponse().GetResponseStrea m();
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(stream, false);
                stream.Close();
                System.Windows.Forms.Form form = new System.Windows.Forms.Form();
                form.BackgroundImage = bmp;
                form.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                form.Disposed += delegate(object src, EventArgs args)
                {
                    GNAAT();
                };
                form.Show();
            }

    // A moose once bit my sister. You see, she was carving her initials in the moose with a toothbrush when...

    1. Re:Are you certain this is what you want? by beacher · · Score: 1
      form.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch

      Kind of redundant, don't you think?

    2. Re:Are you certain this is what you want? by petermgreen · · Score: 1

      at first sight that looked like java code written without using import statements but those class names don't look like java.

      is it C#?

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    3. Re:Are you certain this is what you want? by adolfojp · · Score: 1

      I am quite surprised to see that no one has attacked you for making the joke in C# and Winforms... this being slashdot and all ;-)

      Then again, this being slashdot... I am quite certain that most of the people here can't read code. /ducks

      Cheers,
      Adolfo

  84. Re:Ditch the signatures by Anonymous Coward · · Score: 0

    > Sigs are useless and annoying. Usually, it's a one-liner obscure geek reference that nobody cares about.

    I care.

    -----------

    struct beer *miller_lite; if (oldskool == YEAH_BOYEEEE); *miller_lite->taste = great; exit (BEYOTCH);/* \\//_ */

  85. Comment Judiciously by awol · · Score: 1

    Comments suck. In the vast majority of circumstances, the only effect that a comment can have is detrimental. That is, it is wrong, saying one thing when the code does another. That situation is V Bad.

    The only time one should comment is when you do something in the code that is obtuse, and by that I don't mean complicated I mean counter intuitive. If you have to do something weird (usually for performance, in my experience) then tell the reader that it was deliberate otherwise they will "fix" your optimisation out of the way.

    People are that are talking about "code that should be self documenting" are essentially right. I have seen some pretty hoopy code in my time but every time I have cursed a lack of comments I have come to retract the curse when I thought about how disgusting the english (my native language) would need to be to describe what was going on.

    And there my friend is the real reason why generic comments suck; human languages have a much wider scope for interpretation than code. Comments that are crystal to one person are opaque to another but the code _never_ lies. So let the code tell its story and only augment it when it looks like the code is being dumb/wrong and yet it is not.

    --
    "The first thing to do when you find yourself in a hole is stop digging."
    1. Re:Comment Judiciously by rjstanford · · Score: 1

      In the vast majority of circumstances, the only effect that a comment can have is detrimental. That is, it is wrong, saying one thing when the code does another. That situation is V Bad.

      And 87% of the time, if the code doesn't match the comment, they're both wrong.

      --
      You're special forces then? That's great! I just love your olympics!
  86. Code is not self-documenting by fredrated · · Score: 0

    Code could only be self-documenting if it was bug free.
    There is esentially no bug-free code, so there is no self-documenting code.

    Stupidity: it's a renewable resource!

  87. comments as visual cues by ignavusinfo · · Score: 1
    as an xemacs user with font-lock permanently turned on i find that jumping around in code, particularly older code, is made much easier with comments are in a bright colored text (yellow or orange) and the remainder of the code is neutral (white or black, depending on the background color). each stanza gets a comment and the comments tend to read one to the next. it allows for scanning the comments in order to zero in on the chunk of code i'm looking for without parsing the code (which gets dense at times).

    letting the editor mark certain text as interesting also obviates the need to put vertical-space consuming boxes of ;;;, ***, ###, and so on. this way comments become less "expensive" in terms of how they affect overall readabity.

    what it comes down to is that although i've been at this programming game for a good long while now i'm still better at reading english than a symbolic language.

  88. Steve McConnell says it all by rraton · · Score: 1

    Steve McConnell tells us all about comments in Code Complete. Code Complete 2 (released last year) tells all about them in Part VII - Software Craftmanship (Chapter 31 - Layout and style, Chapter 32 - Self-documenting code).

    All programmers should read this. Twice.

  89. On code commenting by david.emery · · Score: 1, Interesting
    Comments should concentrate on the "why", the code itself should be clear about the "what" and "how".

    Specifying the "what" in a human-readable form is a strength of some languages including COBOL and Ada. No one (hopefully) would argue that C-based syntax is particularly intuitive, and that common practices that emphasize brevity also are focused on reader comprehension. Where the language doesn't aid comprehension of the "how" or "what", comments should help.

    In 25+ years in this business, I've seen everything from

    i++; /* increment i */
    to code preambles that resembled War and Peace.

    dave

  90. Comments... by Anonymous Coward · · Score: 0

    Comments are only helpful if they are acurate. I have seen too many cases where a program was changed in some fundimental way, but the comments were left unchanged and thus wrong. Update your comments when you update code. PLEASE!!!

    1. Re:Comments... by Anonymous Coward · · Score: 0

      watch this -- some awful coder is going to mod you a Troll because this is slashdot and people are asshats around here

  91. ADA by Anonymous Coward · · Score: 0

    Yeah Taco, I remember the big green book too. Thanks for giving me flashbacks!

    Go Hope!

    1. Re: ADA by Black+Parrot · · Score: 2

      > Yeah Taco, I remember the big green book too. Thanks for giving me flashbacks!

      What is this 'ADA' you speak of? American Dental Association? Americans with Disabilities Act?

      The programming language is called 'Ada', as in Ada, Lady Lovelace, Charles Babbage's sidekick.

      --
      Sheesh, evil *and* a jerk. -- Jade
  92. Re:Check out Rob Pike's thoughts on code commentin by truedfx · · Score: 1

    "Procedure names should reflect what they do; function names should reflect what they return"

    What about functions that simply return a success/failure indicator? Should we rename, for example, waddstr to waddstr_error?

  93. Sheesh... by DaPoulpe · · Score: 1

    Real Men don't use comments...

  94. mod parent funny! by goonies · · Score: 1

    Most of them script kiddies didn't get that one, i guess.

    --
    .sigh
  95. You can't appreciate good comments... by Rick+Genter · · Score: 1

    ...until you've read them in the original Klingon.

    --
    Don't underestimate the power of The Source
  96. Use the preview button when posting code by Tired_Blood · · Score: 1

    If you can't bother with previewing the comment, at least post as "code" instead of "plain old text".

    Code comments are fundamentally about presentation and your example is really messy. The less-than (<) character got lost too.

    --
    This is not my sig.
  97. code in ruby and your code will be like a song by Anonymous Coward · · Score: 0

    it is real pleasure to read ruby code. Ruby is not computer language, it is simply language.

    5.times { print "Ruby rocks! " }

  98. Primarily comment your data by iabervon · · Score: 1

    Good code is self-documenting, unless it relies on some non-obvious property (like code which doesn't need a failure case because the four-color conjecture turns out to be true, or code that computes the min cut of a graph by actually computing the max flow). But data is not at all self-documenting: the meaning of variables, particularly globals or function arguments, and the meaning of particular values they can have, is clear only by studying a potentially large amount of code that's somewhere else. Therefore, it needs a comment that explains how it works and any rules that it follows.

    Similarly, function declarations need comments, because the detailed documentation in code is not in the same file, and often too long to use as reference.

    1. Re:Primarily comment your data by ratboy666 · · Score: 1

      Please think about the following cases (extracted from my current project): /* Semaphores and condition variables are not interchangable on Solaris. The condition variable is EVENT driven, and not based on a COUNTER. This means that the sequence:
                signal condition variable
                wait on condition variable
      will not wake up. With semaphores, this DOES work. We could "roll our own" semaphore out of condition variables, but since Solaris offers both, we just use the semaphore.
      */
      ksema_t ellided_sema;

      And consider: /* There isn't a mutex for creating and removing card handles, because the OS will do this "single-threaded". Also, we don't need one for the IOCTL entry, because any changes will be reflected in the change count, which is not updated until after the data structure has been modified.

        If you are truly paranoid about this, do:
                ACA_Get_ACA_Handles -> change_count_1
                ACA_Get_ACA_Handles -> change_count_2
                if (change_count_1 == change_count_2) then
                        if (change_count_1 != original_change_count)
                                interpret handle list
      */
      static bool remove_card_handle(dev_state *asp)
      { // elided
      }

      In both of these cases, what is being documented by the comment is something that isn't there. And, really, isn't likely to be there in other documentation either.

      And, yet, I consider both of of these comments vital (as mis-understanding WILL break, or degrade the program).

      They do not comment the MEANING of the data (you still don't know what ellided_sema is for, but you DO know why it is a semaphore), and certainly not the parameter of the function (although, I think it would be /hopefully/ obvious that remove_card_handle() will remove the card handle associated with, or represented by, a dev_state *. But, you know that the operation is not controlled by a mutex, or other locking device, and, hopefully, you understand why.

      Good code is self-documenting? Generally, I don't think so. Code represents one possible solution, but why was that chosen? What are the tradeoffs resulting in the decisions that resulted in THIS code? The code is (in a Zen way); but the deeper question as to WHY it is generally remains unanswered.

      Then again, I get well paid for asking these questions -- this is what results in optimization. Possibly my comments are more reflective of a personal thought process.

      But I am very curious about this.

      Ratboy.

      --
      Just another "Cubible(sic) Joe" 2 17 3061
    2. Re:Primarily comment your data by iabervon · · Score: 1

      Neither of those cases are documenting code, either. They're documenting why the code works, but letting what the code does speak for itself. They both document why code that doesn't exist doesn't exist, and code that doesn't exist is certainly not self-documenting.

      Actually, I don't think either of these should need to be comments here; if Solaris were properly documented, it would be clear that condition variables have to be protected with a mutex, so a semaphore is the intuitive primative for this situation (and the comment does imply that we expect this condition to be signalled in advance of when it will be waited on; something about the data). And the documentation of the set of hooks that remove_card_handle is for ought to tell you that it's called in a single thread and not overlapped with ioctls. Both of these comments are generally good information, and not really particular to the locations you give for them. That's not to say that they should be omitted if you can't change the better place, but in an ideal world...

  99. Don't bother writing comments... by Anonymous Coward · · Score: 0

    ... just offshore it to India because your boss won't care about maintenance anyway.

  100. Re:Check out Rob Pike's thoughts on code commentin by p2sam · · Score: 1

    In a perfect world, filled with great programmers like Pike, yes, I agree with him, comments become unnecessary. However in the real world, software is typically developed, and maintained by a team of programmers with varying skill levels, where I routinely see methods that spans 300 lines, and for-loops nesting 4 or 5 times, comments become necessary.

  101. XML comment by Shad_the_protector · · Score: 1

    When reading code, most of the code is actually, if well coded, clear to me. But a useful things to do, if using visual studio .NET is to use the XML comment to comment a class, function, etc. Especially when the other that will use the class, will only have a Dll, or have nothing to care about the code. XML comment give useful information in the popup and the object browser that can help the user to understand what exactly do the following class or function.

    sure a class like class says a lot, but if when you check it it says Implemented the = and &= opperator to the stringbuilder class then you know what new.

    In a function you can comment each parameter to know exactly what they do and what to send there.

    Comment is no more just for those modifying your code later when you are gone, but also for the Dll user. to help them use your class.

    Check there for more info

  102. Comments are Critical to larger scale projects by localman · · Score: 3, Insightful

    Sure, well written code should read clearly and be clear about what is happening at every step. But in any larger scale project, no matter how well you make your data structures or how cleanly you encapsulate, eventually you'll code things where the motivation isn't clear.

    Good comments don't talk about the code itself, they talk about why the code is doing what it's doing. What the code is doing should be obvious if it's well written, but I've never written a code file that couldn't benefit from a little english exposition.

    Cheers.

    1. Re:Comments are Critical to larger scale projects by Anonymous Coward · · Score: 0

      In my mind, comments should tell the reader what a block of code *should* be doing. That way, correct behaviour can be determined in the event that the code is behaving contrary to expectation. This, of course, works well with unit tests to enforce that expectation.

  103. Re:Check out Rob Pike's thoughts on code commentin by BrackishWater · · Score: 0

    you obviously don't write code. first of all code is almost never self-documenting. whoever made that crap up should be shot. and even if the code is clear to the programmer, the comments aren't only for the programmer. all code should include comments so that ANYONE can peer through looking ONLY at the comments and be able to figure out what the code does.

  104. Bingo! That's it exactly by Weaselmancer · · Score: 1

    Why is far more important than how. You can get the how from reading the code. What the author was thinking, that's the part that's hard to figure out if the comments are missing.

    Another thing I like to do is start with a function body, and do nothing but list the WHY items as a simple flow chart, like this.

    function do_something()
    {
    /*check to see if the port is open*/
    /*if the port is open, open the database*/
    /*get the customer record*/
    /*close the database*/
    }

    And then, fill in the code under each comment that does that bit. And when I'm done, leave the flowchart-ish comments in.

    --
    Weaselmancer
    rediculous.
  105. CmdrTaco's education by tverbeek · · Score: 1
    Everybody knows that good code is self documenting- which is why my prof in college demanded we write in Ada.

    Which prof was that? I can't imagine Herb Dershem saying that good code doesn't require comments.

    --
    http://alternatives.rzero.com/
    1. Re:CmdrTaco's education by thelenm · · Score: 1

      I'm pretty sure he must have been referring to Dr. Dershem, though I wouldn't have said Dershem loved Ada because code should be self-documenting. I always assumed he loved Ada so much because he had spent years working with it in the Air Force.

      --
      Use Ctrl-C instead of ESC in Vim!
  106. Comment first. Code later. Then comment again. by Mr.+Slippery · · Score: 1

    // the idea here is to write a post about "Comment first.
    // Code later. Then comment again."

    // first cover "Comment first."
    You should be writing your code from some sort of
    design/psudocode, right? Use that as a skeleton of comments.

    // handle "Code later."
    Then put your code into that skeleton. Change the
    skeleton if needed. The process is recursive, BTW;
    apply it to the module as a whole, to each function,
    and to blocks therein. Also comment any section that
    when you go back and look at, you have to think about
    for a moment to decypher. // this means comment as you go

    // finally, "Then comment again."
    Now make your function headers, formal comments, etcetera;
    all the things that fall under
    "Always code as if whoever maintains your code     // shouldn't happen,
    is a violent psychopath who knows where you live." // but account for
                                                       // this case anyway

    // witty ending
    A fomer colleague of mine comapared documentation (under
    which comments should be considered) to foreplay; doing it
    right raises your desire to code and make the whole thing
    much more enjoyable. I suppose that makes the
    necessary after-documentation a little cuddle time.
    // FIXME - or changing the sheets the next morning? check this.

    --
    Tom Swiss | the infamous tms | my blog
    You cannot wash away blood with blood
  107. Colleges ruin commenting by east+coast · · Score: 1

    I had taken a Java course (my first real coding course) in college that shows why commenting has gone so wrong... We were told to comment EFVERY line reguardless of what it was. For the n00b coder this was their first experience in the world of practicle coding and it left a mighty bad impression. While commenting certainly is important the professor made it seem not only tedious but stupid as well.

    Maybe it was just limited to the faculty at my college but I wonder if this "comment every line" mentality carries to other schools. GOOD commenting is what needs to be taught to make the commenting make more sense to the student. You have to give consideration to the level of the programmer likely to examine your code and having to code lines like "i++;" is just purely nonsense unless there is a need to explain why the increment should happen at that point in time. Otherwise you're just asing to clutter up the code with a lot of things that the programmer should have had a solid grasp on in their freshman year.

    Asking for too much commenting makes the work tedious and leads to the programmer putting less effort into what really matters; the actual code.

    --
    Dedicated Cthulhu Cultist since 4523 BC.
    1. Re:Colleges ruin commenting by tomstdenis · · Score: 1

      I agree.  We had to do that as well.  I started writing programs (in C) without the if statement, then I got bored of while and for loops.

        x = 0; top: ++x < 5 && printf("x == %d\n", x); switch (x) { case 5: break; default: goto top; }

      for instance :-)

      Of course I'd have my comment

        // for i from 0 to 4 inclusive, print i

      before it so they'd figure it out.

      When asked why I wrote like that I asked why we had to put comments before trivial lines instead of blocks of code [which represent ideas more faithfully than individual lines].  After that point I was free to comment as I wanted and I passed [been out for a year now...]

      Tom

      --
      Someday, I'll have a real sig.
    2. Re:Colleges ruin commenting by epee1221 · · Score: 1

      Engineering students here have to do stuff with VisualBasic in the engineering fundamentals class, and they're required to comment excessively. The CS department, on the other hand, only wants comments to explain the purpose of code (and is in most cases satisfied with just the javadoc stuff).

      --
      "The use-mention distinction" is not "enforced here."
  108. umm...no by JustNiz · · Score: 1

    >> ..Everybody knows that good code is self documenting...

    This is a really bad myth that only stays alive as an attempt to justify either a sloppy development approach, or a purposeful attempt at job security through obscurity.

    Good comments let you know what the developer was thinking, i.e. what design philosophy/mental model/pattern he was working to. Even the best uncommented code is only an abstraction of the thought process.

    Uncommented code only tells you what it is actually doing ('correct' or not). It doesn't provide any information that allows you to determine original design intent.

    1. Re:umm...no by gnasher719 · · Score: 1

      >> >> ..Everybody knows that good code is self documenting...

      This is a really bad myth that only stays alive as an attempt to justify either a sloppy development approach, or a purposeful attempt at job security through obscurity.

      There are several things that you need to know: What the code does, what it is supposed to do, and how it is supposed to be used.

      Good code is not self-documenting. However, when code is well-written (and doesn't do things that are too complicated), I can read it and I will know what it does, and I will be quite confident that it does what it is supposed to do. So well written code will indeed achieve some of the things that comments are there for.

  109. "should I write comments?" by tomstdenis · · Score: 2, Insightful

    Boom, you're fired.  If you have to ask that you're clearly incompetent.

    As to what a good comment is, it's something that gives context to a section of code.  Comments aren't supposed to "explain" every step of an algorithm but rather explain why they're there...

    e.g.

    // for loop from 1 to 5
    for (i = 0; i < 5; i++)
       // strcmp for "key"
       if (!strcmp(strings[i], "key")) dowork();

    Could be written better as

    // we are going to look for the string "key" in the array
    for (i = 0; i < 5; i++)
       if (!strcmp(strings[i], "keys")) dowork();

    (better yet is to replace '5' with some constant or other label).

    In cryptographic tasks I assume the reader has the RFC [or other spec] handy and I just explain what parts of the standard I'm fulfilling, e.g.

    // step 3c, xor key with 0x5e
    for (i = 0; i < keylen; i++) key[i] ^= 0x5e

    That way the reader can follow my code against the spec quicker.

    If you're not capable of these sorts of comments it's because you don't think like a developer.  You're slinging one line of code against another instead of properly breaking your task down into many smaller more modular tasks which can then be easily expressed on their own.

    Tom

    --
    Someday, I'll have a real sig.
    1. Re:"should I write comments?" by will_die · · Score: 1

      Do most of the same things.

      However with and RFC, design pattern, spec whatever when you make references you should also inform the person, I put it header, where(URL if available), what version, author(if that applies), ISBN, title, etc that you are using.
      /*
      Following referneces used:
      [1] RFC blablabla , version bla, URL:bla
      */
      Then be sure to say which of thoses references you are refering to. I usally just number then and then when used do
      //[1] step 3c, xor key with 0x5e

    2. Re:"should I write comments?" by tomstdenis · · Score: 1

      That works too.

      Though I normally put one [exportable] function per .C file so standard references don't usually have to be numbered because there is only one standard being used [e.g. PKCS #5 or ANSI X9.63 EC-DH or whatever].

      Tom

      --
      Someday, I'll have a real sig.
    3. Re:"should I write comments?" by rpg25 · · Score: 1

      I'd like to second this comment --- if you get your algorithm out of a book, RFC, or whatever, PLEASE GIVE A CITATION!

      I recall trying to read a blob of code that was supposed to solve linear inequalities (simplex). But there are about a zillion ways to formulate this problem, how slack variables are used, etc. In the end, it was easier to rewrite it than reconstruct how it should be called.

      Actually, this is not a perfect example. The author of that code had cited the book from which the algorithm had been taken. But it was published in the 1950s, was long out of print, and I couldn't even get it through inter library loan.

      So keep that in mind if you think a citation is enough of a comment! If you got the algorithm from a freely-available (not copyrighted) source, consider committing the RFC or what-have-you into the source code repository (you do use one, right?) with the code.

  110. Re:If you don't comment it will come back to haunt by east+coast · · Score: 1

    Damn you and your logic. We don't need that kind of crazy talk here!

    --
    Dedicated Cthulhu Cultist since 4523 BC.
  111. Code Quality? by Anonymous Coward · · Score: 0

    While I think self-documenting code is a nice goal and is sometimes sufficient, this is a bit naive to try to jump to other conclusions within the same breath. While the code may allow you to understand the mechanics of 'how' it does nothing to address questions of 'why'. Often times it is very important to understand why something is coded the way it is; I have seen too many large projects have inappropriately coded solutions because of a violation of the meta view of the project. In the real world, many programmers are making coding decisions based on an incomplete (sometimes incorrect) view of the system. Some of this cannot be avoided and when someone can offer specifics of why something is the way it is, it makes it easier for others to follow in another's footsteps in their absence.

  112. I need a blog... by jferris · · Score: 1
    ...just so I can spew off and have people think that it is an actual article of some sorts.

    The best "point" in the article is the mention of CRC Cards, although I think having a solid series of class diagrams as part of the design document is better. Trust me, have you ever tried to email an index card? ;-)

    Seriously, though... I am sure a lot of people will disagree with me, but this is what works for me, and has worked for the places that I have been employed over my career. When I have a class diagram, I use it. When I don't have one, I make one. My reasoning is as follows. I use the class diagrams to prototype the objects as void methods and properties, commented before a single line of functional code is ever written. The idea of commenting after coding is just completely absurd and is akin of trying to justify an action after giving it no prior thought.

    By commenting not only the method and property blocks and class level comments, I actually pseudo-code the entire class before I write a single line of code. Often, it helps refine things that were missed in the design and/or class diagrams. It also is nice to help identify "helper" or utility code that gets wrapped up in either a class or within an existing one (depending on scope of the utility). This can be reintroduced to the design and make it into any post development documentation, as needed (SDKs, etc.).

    Many people think that this adds time to the development process, and I would think that it is just untrue. Following this methodology for more than ten years now, a lot of problems are identified up front and can be introduced into a modfied design without breaking extant code. Also, hitting key points in commenting in this style provides a cross reference to the design document. Done right, it makes it a lot faster to know where you are and what you are doing. Without it, there is the possibliity of burning cycles constantly looking for things. Even worse, the high and mighty developers out there who read a design document once and never look at it again.

    People just don't seem to understand that a design document is not a friendly recommendation on how you might go about doing something, it is what the customers/employer/analysts expect. Development should not be a fluid process in the respect that you change direction whenever and to wherever the wind blows.

    Sorry. Rant mode off. ;-)

    --
    You are in a maze of little twisting passages, all different.
    1. Re:I need a blog... by Anonymous Coward · · Score: 0

      Amen to the blog comment. Is this paid placement? I wonder if paid placement of blogs pays off solely in AdSense...

      To bolster your main point, and present my own way of looking at this issue: code is documentation. Documentation, like almost any aspect of software process, is an investment that lowers risk. Put in this light, this question isn't even interesting. "How much process (documentation, testing, etc.)" always should be answered with "What is the company's and individual's risk profile for this project?"

      To your point on writing comments before code: in your methodology, comments are a form of documentation that lowers the risk of coding itself, just as design does. Again, it's a risk assessment exercise.

      But keep in mind how blind most of us are to most risks... Given our unwavering and ridiculous faith in ourselves that we can do it right the first time, developers almost always under-represent the risks, and therefore, at their worst, believe that code is 'self-commenting'.

      Don't deny the risks. Own up to them, or they'll surface one way or another. THEN decide what level of process to use.

    2. Re:I need a blog... by jferris · · Score: 1
      Exactly. That is another issue that I should have brought up. I am in a .Net shop, so we use XML comments. The available tools to create documentation from them (help files, etc.) is not only another example of the emphasis that people are finally putting into commenting, but it is an incredible timesaver, as well.

      Looking at some coworker and ex-coworkers, I am thankful that I don't share the perfection complex that some of them seem to exhibit. There was a time that I did a lot of analysis work and could see just how badly the best requirements and designs could be bastardized by a hotshot fresh out of school and green as the fairway. SAs and PMs have a truly thankless job, if you think about it. They are usually the first ones to get blamed when something goes wrong and the last ones to be recognized when it goes right. And in today's market, it isn't uncommon for them to make less than a developer. (One of the reasons that I have resisted a move to project management, at least with the current market state).

      I used to dread commenting. It was always an afterthought. For smaller projects, most often non-critical applications, I didn't realize the impact. My surprise came walking into the shop of a Fortune 500 Company and feeling lost in a sea of commentless code. To make matters worse, it was for a client who was overseas, so the language barrier slowed down the reciprication of answers to even the most basic questions.

      Granted, I have been stuck with other people's code with comments as sparse as days without duplicate Slashdot articles, but I will be damned if I will leave someone in that boat. ;-)

      --
      You are in a maze of little twisting passages, all different.
  113. lazy programmers by MatD · · Score: 5, Insightful
    People use the 'code should be self documenting' excuse because they are lazy and don't want to take the time to actually write documentation.

    If you are programming anything non-trivial, you are going to have sections of code that are obscure, and when you have to go back and fix a bug, or add functionality, you won't have any idea what the hell you were doing.

    For example, I've written code that had to run on displays with 256 color palettes in windows. It involved saving the current palette when the window gained focus, and then restoring it when the window lost focus. But I couldn't even tell you how I did that now. If I had to go back and look at that code today, I'd have no idea what I was thinking. I do recall that is wasn't actually very many lines of code.

    Back before UML was a common thing, I used to 'write' my code in comments and stubs, as a design. After I could read through the code as a narrative of what my app/service/dll did, I would actually fill in the stubs to make it work. This ended up saving me a lot of time in the long run, as I didn't really have much refactoring work to do while coding.

    --
    Since when did operating systems become a religion?
    1. Re:lazy programmers by Anonymous Coward · · Score: 0

      Comments == extra information. Too much information can make the reader's head explode sooner.

      If you have a 100-line file which is just plain well-structured code and you add another 200 lines of silly comments there is a higher possibility that the reader's mind will explode before reaching the interesting function. And be careful. Most good programmers suffer from Attention Deficit Disordering and Introversion. They dont even RTFA.

      Comments should lead hackers to the right direction, by clearing out things they would probably misunderstand by a first glance.

      Your employer.

    2. Re:lazy programmers by javaxman · · Score: 1
      People use the 'code should be self documenting' excuse because they are lazy and don't want to take the time to actually write documentation.

      Amen, brother, though that could be "lazy or don't have time"

      too often I feel like I don't have time, or tell myself "I'm just prototyping here and will comment it later, I'm not showing this to anyone else yet" which is a mistake, because later I have a mass of code with no comments that need them, and you just won't write useful comments that way.

      I've found there are two types of comments which are important. First there's the comment you should write before starting a block of code- the one that talks about what it needs to do. The second type of comment is the one you write somewhere in-line, which talks about how and possibly why something non-obvious is being done.

      Mostly I've found that if you're thinking you don't have enough time to write comments for your code, it's an indication that you're spending too much time writing comments for slashdot.

    3. Re:lazy programmers by Anonymous+Cowhead · · Score: 1
      People use the 'code should be self documenting' excuse because they are lazy and don't want to take the time to actually write documentation.

      People use the 'you should comment your code' excuse because they are lazy and don't want to take the time to actually write understandible code.

    4. Re:lazy programmers by reclusivemonkey · · Score: 2, Informative

      Back before UML was a common thing, I used to 'write' my code in comments and stubs, as a design. After I could read through the code as a narrative of what my app/service/dll did, I would actually fill in the stubs to make it work. This ended up saving me a lot of time in the long run, as I didn't really have much refactoring work to do while coding.

      For a non-programmer writing VBA at work, this has been by far the most useful comment to me. Thanks :-)

    5. Re:lazy programmers by MikeBabcock · · Score: 1

      Too much information is not a bad thing.

      Its called 'grep'.

      Or, if you use a nice editor, tell it to hide comments if you don't want to see them.

      --
      - Michael T. Babcock (Yes, I blog)
    6. Re:lazy programmers by Flwyd · · Score: 1

      The goal is therefore to break your program up into appropriate parts so that almost everything is trivial. You can therefore comment the parts that are non-trivial and not worry about the rest.

      The ideal method is a few lines long and has a descriptive name and parameters. The test for this quality is to try to write a comment for it -- if you find you're just repeating the code, you've done a good job.

      public Collection getUnripeFruits() {
              Collection result = new LinkedList();
              for (Iterator iter = fruits.iterator(); iter.hasNext();) {
                      Fruit fruit = (Fruit) iter.next();
                      if (!fruit.isRipe() && !fruit.isRotten()) {
                              result.add(fruit);
                      }
              }
              return result;
      }

      No comment.

      --
      Ceci n'est pas une signature.
    7. Re:lazy programmers by epee1221 · · Score: 1

      Some processes/algorithms are simply too complicated for their code to be immediately understandable.

      --
      "The use-mention distinction" is not "enforced here."
    8. Re:lazy programmers by big+ben+bullet · · Score: 1

      the verb you are looking for is

      refactoring

      thus the phrase becomes:

      People use the 'you should comment your code' excuse because they are lazy and don't want to take the time to refactor their code.

  114. Comments should be like skirts... by Mgdm · · Score: 1

    ...short enough to maintain interest but long enough to cover all the important bits.

    (Maybe more relevant to documentation in general, but whatever)

  115. Unified theory of commenting by awtbfb · · Score: 5, Funny
    // If you can't follow this, go ask CowboyNeal
    1. Re:Unified theory of commenting by texaport · · Score: 1
      Given the current global realities, shouldn't the debate be whether to comment
      in Urdu with Perso-Arabic script, versus Sanskrit with the Devanagiri script ?

  116. I tend to get the problem solved in fits by SlashSquatch · · Score: 1
    When I have to code,
    or in reading my old code,
    I'm suprised at voids.

    When things get to deep
    for my small brain to handle
    useful comments cease

    "so in the end Salter and Greeney finally succumbed to the ways of Harold, and in doing so each gave just a little bit of his soul away. What a couple of dumbshits."

    --
    Autonomous Retard -- Is your camp safe? UnsafeCamp.com
  117. Bad Code + Block commenting = Good Commenting by djdole · · Score: 1

    Recipee for good commenting:
    Write bad code then use block comments to comment out the code.
    Da na! Good (use of) block commenting.

    (JOKING. If you take the above seriously [and respond with some anal-retentive reply], then you're an ass-hat who needs a head examination.)


    /ComentingComentingComentingComentingComentingCome ntingComenting
    //Now it's not a word. It's just a sound that sounds funny.

    public void asshat(){

  118. Ah, the age old programming question by TheSkepticalOptimist · · Score: 1, Insightful

    Pretty much my philosophy is to comment any section of code that IS NOT OBVIOUS what it's intent is.

    I mean, any reasonably skilled programmer should be able to look at a block of code and understand what is going on without an excessive description of what the original programmer intended to do. But there are always those cases, especially if the original programmer got crafty and found ways to streamline or optimize the code for performance, where anybody not involved in the original development would just scratch their head and wonder what the heck is going on.

    Comments can be very detrimental in many cases. If I get some code that is heavily commented, to the point where the actual code is separated by long blocks of commented code, I just nuke the comments and condense the file. I have actually found files that are thousands of lines long be reduced to only a few hundred lines be removing superfluous comments, and the actual code is easier to understand without the unecessary comments.

    NOBODY should ever write a comment like //Loading X with the value 5
    int x = 5;
    I mean, this is a very obvious and exagerated case, but often this happens. It is very obvious what the code is doing, anyone with at least 1 day of programming lessons can understand it easily.

    Usually, its more like //Initialize Y to be false
    bool y = false;

    Why should y be initialized to false. I many cases, false is just an arbritrary initial value, but in some cases, the initial condition is important, this importance should be commented and highlighted.

    For the most part, comments end up being inaccurate. //Initialize Z to 10.2 because it is important
    double Z = 6.1;

    So what do you do here? If your reviewing the code, is 10.2 still the important value, or has a bug been fixed by changing the inital value to 6.1. Is a bug occuring because Z is not 10.2?

    As a programmer, one should never blindly read the comments and not review the code. Learning to understand the code makes more sense then deciphering the comments. In most cases, the comments are either superfluous, meaningless, or just wrong. The best skill a programmer can learn is to ignore comments and read the code.

    Ultimatly, I comment a block of code to give a general sense of what I am trying to do. I don't go into particulars within a section such as why I am deleting a pointer or loading a value (it should be obvioius what your doing), its the end result that is important, not all the minutia involved in getting there.

    Also, I CAN'T stand notation that lists the history of file changes. I mean, the CURRENT code is what your interested in, not what someone did 6 years ago. Knowing that person X modified Line Y in 1992 is of no benefit to my ability to read, understand, fix, or update code in 2005. Often, these modifications refer to code changes that no longer exist in the file. Someone made a fix to code in 2001, but someone in 2003 rewrote the whole code, the 2001 fix is irrelavent. Serious programmers invest in a source control product, like Visual Source Safe, CVS, or SubVersion. These programs STORE the history of a file, there is no need to write a header that can be hundreds of lines long telling you about all the bug fixes and file changes. If you need to review old code, simply go into your source control and compare the file between 2005 and 1992 to find out what is different and changed. Often, most of the people involved in the file's history no longer work at the company.

    Lastely, one of the MOST important commenting tricks is to insert nothing at all! A blank line can speak volumes. It can separate functional sections in code, allowing you to understand the flow of the code and realize when certain results are accomplished. I am an object oriented programmer, so seeing blocks of functional units where a blank line separates some operation or result just makes sense (even more if you turn the code section into a class

    --
    I haven't thought of anything clever to put here, but then again most of you haven't either.
  119. This rubbish again by Anonymous Coward · · Score: 1, Insightful

    Everybody knows that good code is self documenting

    Sigh. This rubbish again. That a lecturer is promoting this nonesense is even worse.

    The "self documentation" you refer to means that you cannot check the documents against the code in order to detect errors. It also means you cannot check the tests against the documents to detect errors - you can only check the tests against the code, which is self defeating.

    Good code is commented. The best code in the world that has no comments is
    a maintenance nightmare - how can you tell why a particular part of the code
    is written this way rather than that way and why is that special case there?

    Those that don't believe this either haven't been writing software long enough or have yet to work on a sufficiently large and complex product to
    realise the error of their ways.

    I'm currently working on a project that is 11,000,000 lines of C++ and assembly including comments. About 7,000,000 without comments and without whitespace. It would be a nightmare without the comments (i.e. "self documenting" - pah).

  120. Re:Check out Rob Pike's thoughts on code commentin by Anonymous Coward · · Score: 0

    In a perfect world, filled with great programmers like Pike, yes, I agree with him, comments become unnecessary. However in the real world, software is typically developed, and maintained by a team of programmers with varying skill levels, where I routinely see methods that spans 300 lines, and for-loops nesting 4 or 5 times, comments become necessary.
    No *refactoring* becomes necessary.

    My experience is that comments by programmers that do stupid stuff like that aren't useful anyway. The first refactoring step is to delete the comments so they don't distract. If its for a current project, step two is to go get the programmer and show them how to organize the code properly, get them started, and let them finish it up on their own.

    If its for an older project and the programmer isn't available, I just fix the issue, and then hunt for the real bug. Sometimes, I discover I fixed it accidently.

  121. No he's a good commenter, by Anonymous Coward · · Score: 0

    I think the guy is saying that, in addition to the WHY comments, he goes down to the level of explaing why FOR and IF statements are there. Because you have to use ugly code.

    So he's a good guy.

    Better than the people who assume everyone knows about the _WIN32GetBillGatesHandleAndPull() function.

  122. Are you reading the same thing I am? by Some+Random+Username · · Score: 1

    I see comments EXACTLY like this:
    i=i+1; /* Add one to i */
    ALL THE TIME. It is incredibly annoying, and trains your eye to ignore all comments, so you miss the occasional useful one. If you don't see comments like that in real life, then you are without a doubt the luckiest programmer alive.

    "It doesn't take much, or add any clutter to code, to put a brief, one or two line, comment before each paragraph of code, that describes the intended functionality of the code block. It makes a massive difference when you revisit your code three years, or even three months, later, or worse have a collegue look at it. "

    Oh, you mean kinda like he said he does do, and is what comments should be used for? Did you skip over this part: "But I do comment sometimes. Almost exclusively, I use them as an introduction to what follows. Examples: explaining the use of global variables and types (the one thing I always comment in large programs); as an introduction to an unusual or critical procedure; or to mark off sections of a large computation."?

    And yes, code should be mostly self documenting. The exceptions should be few and far between, and should be commented as appropriate. Its amazing that you read his statement which could be summed up as "Reasonable, non-excessive, use of comments, describing functionality rather than function", and somehow managed to disagree, and summarize your opposition as "Reasonable, non-excessive, use of comments, describing functionality rather than function".

    1. Re:Are you reading the same thing I am? by squiggleslash · · Score: 1
      I see comments EXACTLY like this (...) ALL THE TIME
      I don't. I see them occasionally. You're either surrounded by complete idiots, or elite programmers making jokes that are flying above your head.
      Oh, you mean kinda like he said he does do, and is what comments should be used for? Did you skip over this part: "But I do comment sometimes.{...}"
      No, I didn't skip over it. It doesn't mean what I said. He "sometimes" comments. Sorry to snip at that part, but I think it's the bit you missed and why I disagreed with him. Now, sure, if what he meant was:
      I always comment in what follows. Examples: explaining the use of global variables and types (the one thing I always comment in large programs); as an introduction to an unusual or critical procedure; or to mark off sections of a large computation
      ...then yeah, he'd have been saying something vaguely similar to what I was writing, in some areas, and I'd have not posted a major disagreement. But he didn't. He said he sometimes comments. The general gist of what he writes is you should avoid commenting altogether, and if you comment, you should limit it to a small set of circumstances.
      The exceptions should be few and far between, and should be commented as appropriate. Its amazing that you read his statement which could be summed up as "Reasonable, non-excessive, use of comments, describing functionality rather than function", and somehow managed to disagree, and summarize your opposition as "Reasonable, non-excessive, use of comments, describing functionality rather than function".
      It's amazing you read his statement, which can be summed up as, "You shouldn't comment, if you do, limit it to explaining certain globals, documenting one or two procedures, or sectioning off complicated code" as being the same as "Reasonable, non-excessive, use of comments, describing functionality rather than function".

      Code that's "mostly" self documenting is not self documenting. Regular, non-excessive, commenting, that describes functionality, is important.

      --
      You are not alone. This is not normal. None of this is normal.
    2. Re:Are you reading the same thing I am? by Some+Random+Username · · Score: 0, Flamebait

      "I don't. I see them occasionally. You're either surrounded by complete idiots, or elite programmers making jokes that are flying above your head."

      Or perhaps you are making stupid assumptions. Yes, I deal with alot of shitty code, most of it open source and written by people I have never even met. The people I am surrounded by are not making the comments, the mass of assorted dumbasses all over the world are. But of course, it must be just me and that wacky nut Rob Pike, we're both such shitty programmers that our experiences would be irrelivant.

      As for the rest of your post, you just like to argue it seems. You are reading into his words and mine the intent you would like to see, simply so you can disagree with it. Since you don't actually need anyone else for this, why not just go make up both sides to an argument on your own?

    3. Re:Are you reading the same thing I am? by ednopantz · · Score: 1

      i=i+1; /* Add one to i */

      I only see that from interns. I don't know what they teach kids these days, but it seems to be
      "use lots of comments that explain the trivial bits, but never comment anything that could actually help someone."

      Someone really should gin up a piece of baffling code only commenting that trivial crap for use as an anti-pattern.

      "Rarely comment what. Often comment why." is the approach that works best for us.

    4. Re:Are you reading the same thing I am? by squiggleslash · · Score: 1
      Or perhaps you are making stupid assumptions. Yes, I deal with alot of shitty code, most of it open source and written by people I have never even met. The people I am surrounded by are not making the comments, the mass of assorted dumbasses all over the world are. But of course, it must be just me and that wacky nut Rob Pike, we're both such shitty programmers that our experiences would be irrelivant.
      Sorry, let me repeat myself. I don't come across this kind of thing very often. I work in a company with about fifty programmers (in our area of the business), of varying skills, and it just doesn't happen that often. We come across dumbass comments once every few years, and when they occur, they're emailed around the company much to the amusement of most of us and embarassment of the programmer concerned, assuming they still work here.

      I assume all these people are now working with you and Rob Pike. I shall take great comfort in the fact that, apparently, I work for in the greatest company in the world, with the most skilled, intelligent, programmers, and shall wonder why we're not paid a hell of a lot more, and why we're working on database tools for obscure branches of the marketing departments of automotive manufacturers rather than cures for cancer.

      As for the rest of your post, you just like to argue it seems. You are reading into his words and mine the intent you would like to see, simply so you can disagree with it. Since you don't actually need anyone else for this, why not just go make up both sides to an argument on your own?
      Uh-huh. I read a comment that discourages commenting. I replied to it. You claimed, despite the fact Pike was arguing against commenting and I was arguing for it, that we must be in agreement. Now you're saying "I just like to argue" because I explained it to you.

      If you think Pike is for comments, perhaps you can point out what paragraph actually encourages commenting in his article, rather than claiming that we're saying the same thing because we happen to agree that "i++; // increment i" is an inappropriate use of comments.

      --
      You are not alone. This is not normal. None of this is normal.
    5. Re:Are you reading the same thing I am? by Anonymous Coward · · Score: 0

      I'm looking at 'The Practice of Programming', by Brian Kernighan and Rob Pike (2nd printing, Addison Wesley), pages 23-27, where comments are discussed. The discussion about eliminating 'obvious' comments takes up much of the first page of this section. This appears to be the section causing all of the controversy here, where the authors discuss removing trivial comments of the '//here we increment i' sort. The section does use a sort of a strawman example, but I've seen this kind of overcommenting enough that it is worth pointing out as a style error.

      The second section is headed 'Comment functions and global data'. It begins:

      "Comments can be useful of course. We comment functions, global variables, constant definitions, fields in structures and classes, and anything else where a brief summary can aid understanding."

      Later on this page, the authors recommend adding comments where 'the algorithm is complicated or the data strucures are intricate." In these cases, the authors suggest adding references for algorithms or reasons for implementation decisions.

      Here Pike is clearly not discouraging comments.

    6. Re:Are you reading the same thing I am? by Arandir · · Score: 1

      You're either surrounded by complete idiots, or elite programmers making jokes that are flying above your head.

      Since he's seeing them all the time, my assumption is that he's teaching first semester Java programming at a junior college.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
    7. Re:Are you reading the same thing I am? by Anonymous Coward · · Score: 0

      That's positive, if a little schitzo. Why Pike feels the need to discourage them in the article under the discussion is anyone's guess.

    8. Re:Are you reading the same thing I am? by Some+Random+Username · · Score: 0, Flamebait

      Quoting a dumbass who refuses to read what he replies to:
      "I assume all these people are now working with you and Rob Pike."

      Quoting the post you replied to, and even quoted:
      "The people I am surrounded by are not making the comments, the mass of assorted dumbasses all over the world are."

      "If you think Pike is for comments, perhaps you can point out what paragraph actually encourages commenting in his article,"

      I already did, remember:
      "Almost exclusively, I use them as an introduction to what follows. Examples: explaining the use of global variables and types (the one thing I always comment in large programs); as an introduction to an unusual or critical procedure; or to mark off sections of a large computation."

      But obviously reading what you reply to takes WAY too much effort.

    9. Re:Are you reading the same thing I am? by jgrahn · · Score: 1
      I see comments EXACTLY like this:
      i=i+1; /* Add one to i */
      ALL THE TIME.

      I see comments SIMILAR to that one frequently. It doesn't have to be that obvious to be annoying; sometimes there's a bunch of text which, when you mentally decode it, boils down to exactly what the class name/function name/code snippet/whatever says.

      The only sane thing to do is to remove them and move on.

    10. Re:Are you reading the same thing I am? by jesup · · Score: 1
      I see comments EXACTLY like this:
      i=i+1; /* Add one to i */
      Then find some better programmers to work with, or teach them how the write more useful comments.

      That style makes sense in one, and only one usage: ASM code. Even there, it should be used with care. (Ok, and in APL).

      The gp poster wasn't suggesting those. That is a comment on "function" not "functionality". See a previous article here.

      Here's something I wrote there that's relevant:

      comments can lie
      I worked with a programmer who disliked comments so much he'd remove them before looking at a function. Ok. So I wrote some code and he came to me and said "why do you have an empty else case?" I was puzzled, then realized that I'd written something like this:
      else
      {
      /* we don't have to do anything in the else case because of x y and z */
      }
      where x y and z would be non-obvious to anyone who wasn't fully immersed in this code. He's run it through a filter that removed all comments. He was a genius programmer - but wrote code that almost no one else could ever maintain. Tons of reliances on edge conditions without comment, reuse of generically-named variables (1 and 2 character names), tricky (but efficient) algorithms. So far as I know, I was the only one there ever to manage to really grok his code, and that required days of immersing myself.
      x = x++; // add one to x
      is obviously not useful.
      // Test FU_E (End bit) after FU_A/FU_B test! If there's a gap, do not consider
      // hitting the End bit a marker to stop - continue until we see another
      // packet/timestamp (in which case we return TRUE), or until we are
      // at the end of the buffer (in which case we return FALSE and keep
      // hoping to assemble it).
      if (((*curr)->GetPayload()[1] & FU_E_BIT) && !gap)
      break; // no error in fragment
      // if there's a gap we still won't return true unless
      // we find a non-fragment packet (or one from another fragment!)
      This is an example of a useful comment - and yes, it has to be maintained if the line of source were to change. I chose that at random; there are better examples - such as explaining what the edge cases are (especially if not handled), and under what circumstances they would become relevant, and how they could be dealt with then.

      Please excuse the incorrent indenting above; "" doesn't work exactly like 'pre'

    11. Re:Are you reading the same thing I am? by Trillan · · Score: 1

      And yes, code should be mostly self documenting.

      No, code is never self-documenting. Anyone who says this is deluding themselves and will eventually realize otherwise.

      An assignment with a calculation, for instance, perfectly explains a formula in a way anyone familiar with the language can understand. But no matter how descriptive the variable names are, it doesn't explain why the calculation is taking place, or why it's taking place NOW, what if any assumptions are made about the inputs, and what the ultimate goal for the calculation is./p

    12. Re:Are you reading the same thing I am? by The+boojum · · Score: 1

      x = x++; // add one to x

      Not only is it not useful but it's wrong too! The code modifies x twice between sequence points. It'll only add one to x if you're lucky, but it's behaviour is actually undefined in C/C++. "Nasal demons" and all that jazz.

    13. Re:Are you reading the same thing I am? by ipfwadm · · Score: 1

      I'm not sure why I'm jumping into this conversation, given the ad hominem attacks, but here goes...

      "Almost exclusively, I use them as an introduction to what follows. Examples: explaining the use of global variables and types (the one thing I always comment in large programs); as an introduction to an unusual or critical procedure; or to mark off sections of a large computation."

      You left out the immediately preceding sentence: "But I do comment sometimes." The "Almost exclusively" means that WHEN he comments, which is "sometimes", he uses those comments "as an introduction to what follows", examples of which are listed. It does NOT mean that he always comments the examples he gives. Perhaps he MEANT to say he always comments the given examples, but that is NOT what he DID say.

    14. Re:Are you reading the same thing I am? by petermgreen · · Score: 2, Insightful

      basic programming classes seem to push overcommenting.

      good comments should imo cover
      1: the why (why am i doing it this way)
      2: the why not (why am i not doing this the obvious way)
      3: the high level what (though to some extent this can be pointed out through method signatures etc)
      4: the low level what in cases where it wouldn't be obvious to someone reasonablly skilled in the language.

      However you don't get many of those in trivial programming excercises but the teachers are still supposed to encourage people to use comments. So naturally comments that point out trivialites are the result.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    15. Re:Are you reading the same thing I am? by Some+Random+Username · · Score: 1

      But saying that he doesn't always comment is not saying "never comment, commenting is bad", which is what the other poster somehow takes away from it. I do comment sometimes, and then giving examples of when he thinks commenting is helpful is most certainly encouraging commenting. Its simply discouraging USELESS commenting, which is WAY too common.

      And FYI, an ad hominem attack is attacking someone, instead of attacking their argument. I clearly pointed out the flaws in his argument, and only called him a dumbass who refuses to read after he ignored everything I said and repeated the same nonsense. That's not ad hominem at all.

    16. Re:Are you reading the same thing I am? by try_anything · · Score: 1
      I see comments EXACTLY like this:
      i=i+1; /* Add one to i */
      ALL THE TIME. It is incredibly annoying, and trains your eye to ignore all comments, so you miss the occasional useful one. If you don't see comments like that in real life, then you are without a doubt the luckiest programmer alive.

      Wow.... I've never seen anything that clearly idiotic, and I've read the code of perhaps a dozen coworkers in my career, as well as a certain amount of open-source code. Perhaps what you see is the result of refactoring unclear code to be more clear, making the comments superfluous?

      You know, you inherit code with repeated use of an expression like this:

      date1 = nextWorkday(date2.nextWeek().nextWeek().nextWeek() .nextWeek().setDay(Date::monday()));

      You create a function named firstPossibleCheckupDate and use a wildcard search-and-replace to replace those expressions. You confirm that each replacement is valid, you recompile, the unit tests pass, but you accidentally leave a few comments in the code that look like this:

      // first possible checkup date
      date1 = firstPossibleCheckupDate(date2);

      I don't think that's so bad in the big scheme of things.

    17. Re:Are you reading the same thing I am? by ipfwadm · · Score: 1

      But saying that he doesn't always comment is not saying "never comment, commenting is bad", which is what the other poster somehow takes away from it.

      I wasn't commenting on the other poster's interpretation of the article. I was commenting on your post, which claimed that the paragraph I quoted ("I sometimes comment. Almost exclusively, I use them ...") was somehow equal to an encouragement to comment. It is not.

      then giving examples of when he thinks commenting is helpful is most certainly encouraging commenting

      The quoted paragraph never explicitly says that he thinks those are cases where commenting is helpful. He just says that's all he does when he comments. And forgive me for thinking that saying "I only sometimes comment, but when I do these are the only things I comment" isn't exactly an encouragement to comment.

      If the original article (other than what was quoted) actually explicitly says that he thinks those are helpful cases, then ignore that. But I'm too lazy to go back and read it again now.

  123. Is that news? by 4D6963 · · Score: 0, Flamebait

    You call that news? Plus I never thought that writing comments in code was such a big issue. i mean, we all know that it's important to have code commented so we easily understand what the code is for, but I don't think that it's necessary to make a page explaining how to write good comments, everybody instinctively knows how to write short and pertinent comments, i think..

    --
    You just got troll'd!
  124. Close Tag! by theonetruekeebler · · Score: 1
    Wait! You forgot the close comment tag! You have to put */ in there or I won't be able to...

    I won't be able to read...

    I'll have to read...

    All the rest of the comments.

    Hmmm.

    /*

    --
    This is not my sandwich.
  125. Parent Comment Has an Error by Anonymous Coward · · Score: 0

    Your comment misses an ending */ perhaps your comment is not yet finished?! I suppose the idea is so that your code may not be able to do any buffer overflows since it too would be considered part of the comment -- that's an excellent way of making sure your code can not break things!

    // Note to self: do not use multi-line comments if you do not end them correctly.

  126. You mean by hackwrench · · Score: 1

    /* Oh snap. I should have just kept my mouth shut. O_o. */

    By the way, I also have Anonymous Cowards auto-moderated down to -6. and I don't reparent replies to Anonymous Cowards. My limits aren't hard limits, so if an Anonymous Coward replies to someone, I see that there is a post underneath my threshold.

    There- I have commented my Anonymous Coward procedure. Feel free to use this as a template for documenting your code. Also see the Lord's Prayer, which has been confused for an actual prayer, but is clearly a template for generating prayers. It was in response to the question "Teach us how to pray" not "Give us the one true prayer".

    1. Re:You mean by DavidTC · · Score: 0, Offtopic
      That 'praying the Lord's Prayer' thing has always confused me.

      Especially when people say it in King James English!

      Here's the template as I understand it:

      You are great, God. Do your will on earth. Please continue to keep us fed and whatnot. Please help us forgive other people.

      Amen.

      Basically, it's: Jesus's First Law (Love the Lord with all your heart), remembering that God has a plan that you don't know and it comes before any requests you make, then any random requests you might have anyway, and then a request for Him to help you with Jesus's Second Law. (Love other people as if they were yourself)

      It's a very nice prayer, with all the priorities, and someone could probably preach a whole sermon on it.

      Instead, people treat it like it's some sort of poem, and don't even listen to what it says.

      --
      If corporations are people, aren't stockholders guilty of slavery?
    2. Re:You mean by Aadomm · · Score: 1

      I thought Jesus's first law was:

      Thou shalt not harm another person nor through inaction shalt thou allow another person to come to harm.

      --
      Mention the Lord of the Rings one more time and I'll more than likely kill you.
    3. Re:You mean by DavidTC · · Score: 1

      Any sufficiently advanced prayer is indistinguishable from magic.

      --
      If corporations are people, aren't stockholders guilty of slavery?
  127. Re:Bingo! That's it exactly by orim · · Score: 1

    This is exactly what I do. Then if you take out all the code, you're left with the pure intention of the entire function/method/block of code.

    That way, you get the big picture... for the details, just look at the code.

    --
    "If you could only see what I've seen with your eyes..." - Roy Batty
  128. Re:Check out Rob Pike's thoughts on code commentin by ENOENT · · Score: 1

    Good idea. Now I'm off to finish writing foo_returns_the_system_configuration_as_a_big_tree ().

    --
    That's "Mr. Soulless Automaton" to you, Bub.
  129. Yeah! by DemonWeeping · · Score: 0

    ME TOO!

  130. Comment Why and What, not How by Bob9113 · · Score: 1

    Good comments can be very helpful. It is a great pleasure at the beginning of a complex section of code to see a comment that says, "This section computes the operating cost based on our first-in-first-out financial policy. It was written in haste, and perhaps could be more simple, as long as it does FIFO." That makes it clear to me what the business needs the software to do, and I am free to refactor to match the intended outcome. Without a comment like that, it is hard to tell what portions of the code are bizarre because they have to be, and which sections are bizarre because there was a time constraint.

    In short, commenting why you did something, and what it is supposed to do are very valuable. Commenting how it does it is generally redundant and often grows inaccurate over time.

  131. like such? by Anonymous Coward · · Score: 0

    while(true); //Loop until the universe collapses

  132. dont read this... by mmmiiikkkeee · · Score: 1

    damn it i said dont read this... oh well u asked for it... i think there is not really a good "rule" for how one should comment code. good commenting is like painting(or any other art). if u work to hard at it u can get an overdone piece of crap and look like a fool(//commenting every little obvious thing(//like me commenting this...//jk//no really jk//or was i???)). now on the other hand if u put too little comments you can really confuse others who have to read your code(and when u are one of the others reading ur code that just leaves u questioning ur self like... was i really that stupid.... wait no... that was a good idea look here see... wait no... fuck that was the problem i have been looking for all-along...//repeat endlessly till you brain get tired and just rewrites all the code over...)... in both cases the code gets written..... but they both end up takeing more time then they should have taken u(just think of how that time could have been well spent reading /. ... now cry... yes cry and promis not to do it again)....ok so i have said nothing new really: so whats my point???.... um i dont know(let me reread my previous _comment_ to figure out where i was..)... i think it was some thing about how there is really no best "rule" of how to comment code......
    so it seems that making a good system of rules to comment code's goal would be to avoid the above problems...
    WRONG.... well kinda the real truth is it depends what are the common goals of the group coding(present and future)... and that will always determine wheither the comments are good.(and yes there are time when no comments are aproperate//not normally though) just think of all the differtn commenting styles and there advantagesand disadvantages ::> there is the i just want this shit to work comments... jsut enough that it makes sence that nihgt ur working on it... the i know some one else will be reading this comments... the i know some idiot will be reading this i better comment every thign for them... the i dont givea shit comments. the i catn splle connemts. the look how fucking pretty they are comments... the inconsistant commenter(says what going on here but not there).. the comments liek to be on one line damnit commenter. the //no comment .... commenter... my favorite. the offtopic commenter. the code works but but dont read the comments cause they dont really describe what the hell its doing comments... the the code dont work but if u read the comments it tells u how it should of been written commenter... um...... then there are commenters like me that start out with good ideas but in the end whe u read it ur left thinking WTF is that fool tryign to say........they all have there place some time or another(some are jsut there to show us what codeing would be like if we all that lazy)

    i like my comments how i like my tea; //green

  133. sweet smelling comments by Anonymous Coward · · Score: 0

    I liked this commentary, and we've adopted this article as a guideline in our Java shop: http://www.stickyminds.com/sitewide.asp?ObjectId=9 041&Function=DETAILBROWSE&ObjectType=ART

  134. My haiku by timbck2 · · Score: 4, Funny

    So many good posts --
    Damn! I wish I had mod points!
    Better luck next time.

    --
    Absurdity: A statement or belief manifestly inconsistent with one's own opinion. -- Ambrose Bierce
  135. When to comment/document by Qbertino · · Score: 1

    When I programm ERP Modules (in Python) I start with a large comment on what the module is supposed to do. I actually started doing this quite from the beginning. I write a litte summary of what the module does and comment heavily throughout the source. I even have debugging sessions were I only work on comments - often detailing them further.
    I also do a lot of other programming (ActionScript rich media and stuff). I don't do opening or other comments there that much.
    Why that?
    If a multimedia app doesn't work I get an e-mail or a call asking to check into it within the next 24 hrs. The customer is anoyed or says that this comes bad with the end-user. We talk a little, I get to work and fix it within the next 10 hrs.
    If a ERP module doesn't do what it's supposed to, I get a call on my mobile, with the CEO at the other end telling me that he's losing 200 Euro an hour because order processing has gone haywire.

    This is a good point to end all discussion wether commenting is good or bad. When you are debugging a piece of code that keeps 3 people breathing you shure as well want it to be well commented.

    --
    We suffer more in our imagination than in reality. - Seneca
    1. Re:When to comment/document by rjstanford · · Score: 1

      If a ERP module doesn't do what it's supposed to, I get a call on my mobile, with the CEO at the other end telling me that he's losing 200 Euro an hour because order processing has gone haywire.

      Only losing 200 Euro an hour? That's almost not worth fixing.

      Well, you did say that you were writing an ERP in Python...

      *ducks*

      --
      You're special forces then? That's great! I just love your olympics!
  136. pseudo code by eheldreth · · Score: 1

    I always thought of comments as pseudo code. In addition to the usual suspects (loops, etc...) I comment all variable declarations. I also place a comment on any overly complicated or uncommon code I use. I care for several large programs written around 1999 in C, C++, VB, Perl, FPL, and a little Assembler. None of the original staff are still here and I have been bitten more than once by odd techniques they used that leave me scratching my head and grabbing my books.

    --
    The perversity of the Universe tends towards a maximum. - O'Toole's Corollary
  137. And I thought... by billyjoeray · · Score: 0, Offtopic

    This was going to be a story on how to write slashdot comments..

    --
    This sig will make it clear that ANYONE can use this post for ANY purpose WITHOUT the written consent of the NFL.
  138. Forget commenting! by WedgeTalon · · Score: 0

    Real programmers don't document: if it was hard to write it should be hard to understand!

  139. Date & intials in comment by Merdalors · · Score: 1
    Person pet peeve here: dates and names/initials on comments

    I vehemently disagree!

    Have you ever worked on a large, legacy project when something suddenly starts going wrong? Don't you love spotting a line of code in the offending module with last week's date? Don't you appreciate having a chat with the perpetrator?

    Seriously, I can't tell you how many times we have been able to fix an obscure bug by correlating the version and date when it started appearing, with the source history.

    We use a Visual Studio macro that inserts date & intials with one keystroke.

    --
    Slashdot entertains. Windows pays the mortgage.
    1. Re:Date & intials in comment by drxenos · · Score: 1

      If that is your problem, yours is a problem with source control and configuration management. You should not be relying on comments for change history information.

      --


      Anonymous Cowards suck.
    2. Re:Date & intials in comment by Malc · · Score: 1

      Most decent source control systems will let you look at a history of the changes.

      In VSS (not a decent one), you can do a recursive history of a project. The results come up in a window with file names and labels that are chronologically sorted. This is far faster and efficient than scanning source files for dated comments.

      I use Perforce at my current place. It too can do changelist searches based on selected parts of the source tree.

      I stand by my statement: source history is provided by source control, not comments scattered throughout the code. It does it far more efficiently. Yes I have worked on a large project. When something goes wrong, the last thing I want to do is start going through hundreds of files. What I can do is get a list of files from source control that have changed, and then start looking at diffs (visual diffing tools like WinDiff make this very easy and more acurrate than comments in the code).

      BTW, I'm not sure how a "legacy" product has any bearing on this. And from my experience, the bigger the project, the more one has to lean on other tools than the source, such as source control and bug tracking systems.

    3. Re:Date & intials in comment by rjstanford · · Score: 1

      Have you ever worked on a large, legacy project when something suddenly starts going wrong? Don't you love spotting a line of code in the offending module with last week's date? Don't you appreciate having a chat with the perpetrator?

      Oh, gosh yes. Its wonderful in isolation. However, for many years I was the tech lead for a good sized enterprise package - 3+ million LOC, and I'd guess 500+ man-years of development over 15 calendar-years. There were people who extoled that format of comment there, as well, except that who the fuck cares that JGQ (whoever that was, he left a decade ago) modified a line of code seven years ago?

      Now think about the number of times important files would have been changed (hint: thousands over a decade and a half) and add 2-3 "# JTW 02/21/87 Start cd mod 582J7" (and the matching end line - most of the time) type lines to it. Its a cute idea, but its totally non-scalable.

      The one place where it does make sense, IMO, is if you plan on taking a complex software package and making a very few customizations to it. Even then you're not saving a whole lot of time vs. digging into your source-code-control-system, but I can see the utility especially if you have relatively unskilled developers working on the project. But that's about it.

      --
      You're special forces then? That's great! I just love your olympics!
    4. Re:Date & intials in comment by rjstanford · · Score: 1

      There were people who extoled that format of comment there, as well, except that who the fuck cares that JGQ (whoever that was, he left a decade ago) modified a line of code seven years ago?

      Preventative note to smart-alecks: Yes, I see that it would indeed be quite interesting to see that someone who quit 10 years ago still had checkin privs 3 years after the fact. Its an example. You know what I mean.

      --
      You're special forces then? That's great! I just love your olympics!
    5. Re:Date & intials in comment by TimboJones · · Score: 1

      In fact, the most recent versions of Perforce have "Time-lapse view" in the GUI which will mark lines in a file with the revision, changelist, or date they were last modified, and the user that modified them. It also color-codes by age. Better integration with the IDE would be ideal, but it's not particularly difficult to use two tools.

      I completely agree that littering the code with timestamp & modifier is too distracting in the vast majority of cases. On the other hand, embedding the bug id in a comment describing a bug fix can be useful. It's concise enough that I don't find it distracting.

      Of course most of these arguments are moot, since this kind of thing really depends on the coding standard of the team you're working on.

    6. Re:Date & intials in comment by pommiekiwifruit · · Score: 1

      Well, the sysadmin couldn't be bothered to create a new account so the new guy just used the olds guys password :-)

  140. Comments LIE. Code never lies. by Kazoo+the+Clown · · Score: 1

    I don't read comments. It's been my experience they're often wrong, or left over from some previous incarnation of the code where they might have been accurate but are now irrelevant.


    If you can't read code, perhaps you should consider some other line of work.

  141. IDE support for out of line comments by Anonymous Coward · · Score: 0

    Sometimes you need detailed comments but putting them inline destroys the visible structure of the program. You need the ability to put in hyperlinks to more detailed explanations be it footnotes or pop ups. We're in the multimedia enhanced browser age and code is still in the flat text file age. Kind of like using lynx to browse the web.

  142. Re:Humour in the Linux kernel - on fire by moskrin · · Score: 2, Informative

    As I understand it, the "on fire" entry in the printer status indicates when a line printer has a paper jam and is still online, thus potentially generating enough heat to *actually* catch fire... or so I've been told.

  143. a little bit different. by 3-State+Bit · · Score: 1
    I got so frustrated with the lameness filter, I scrapped my entire earlier post. Let's do something different.

    Instead of code, let's comment an obscure poem. (I work from here.)

    Step one. The Code. The bare code. This is the code without comments:
    1. Like as the waves make towards the pebbled shore,
    2. So do our minutes hasten to their end;
    3. Each changing place with that which goes before,
    4. In sequent toil all forwards do contend.
    5. Nativity, once in the main of light,
    6. Crawls to maturity, wherewith being crown'd,
    7. Crooked eclipses 'gainst his glory fight,
    8. And Time that gave doth now his gift confound.
    9. Time doth transfix the flourish set on youth
    10. And delves the parallels in beauty's brow,
    11. Feeds on the rarities of nature's truth,
    12. And nothing stands but for his scythe to mow:
    13. And yet to times in hope, my verse shall stand
    14. Praising thy worth, despite his cruel hand.

    If you've just run over it as quickly as I have, you won't understand it either on a textual level (what each sentence means) or the poem as a whole.

    Now let's add comments (from that web page).

    Step Two. Code with comments.
    /* The code below meditates on mortality.
    At the end the meditation is about beloved, and this becomes the return value.

    (so you can use this whole function as a get method [get beloved] from the data in mortality, but please note that the code's more important function is its side effect, the meditation.

    The thoughts the side effect brings focus on destruction, you can consider it as taking reference counts, etc, whatever meditation on mortality consists of. [Note: this function does no garbage collection, no destruction methods are invoked from objects in mortality! You're not actually killing anything here, just preparing for the death...]*/

    /* like as==in like manner to the way in which: */
    1. Like as the waves make towards the pebbled shore,

    /* imagery of the destruction of each wave as it beats on the shore to make a simile with human life (continues forever, but each life/minute ends):*/
    2. So do our minutes hasten to their end;

    /* Waves appear to change place with each other. As one rolls away, another takes its place: */
    3. Each changing place with that which goes before,

    /* in sequent toil == in consecutive laborious procession: */
    4. In sequent toil all forwards do contend.

    /* TO DO comment: */
    5. Nativity, once in the main of light,
    6. Crawls to maturity, wherewith being crown'd,
    7. Crooked eclipses 'gainst his glory fight,
    8. And Time that gave doth now his gift confound.
    9. Time doth transfix the flourish set on youth
    10. And delves the parallels in beauty's brow,
    11. Feeds on the rarities of nature's truth,
    12. And nothing stands but for his scythe to mow:
    13. And yet to times in hope, my verse shall stand
    14. Praising thy worth, despite his cruel hand.

  144. A comment for all occassions by wintermute740 · · Score: 1

    The best comment I've ever seen has to be:

    /* Magic happens here */

    I've seen it a couple of times now....

  145. I have to tell this story... by RetiredMidn · · Score: 4, Funny
    ...if I haven't already.

    Back in the 70's, I worked the Help Desk at my college's computer center. I was approached by a student taking the entry-level programming class, which taught FORTRAN; programs for the class were written on punched cards (!) and submitted to our RCA Spectra for batch processing.

    Anyway, this guy came to me with a question about a cryptic compiler error message (maybe that's redundant). I asked to look at his listing, and found the problem easily enough, but I was intrigued to see that his code was double spaced! (See it coming, yet?) I wanted to figure out how he did it, because I thought it would be useful in my own work to leave room for writing notes on my listings when I looked at them back in my dorm room.

    I couldn't find any special options on his command card (the first card in the deck that specified how the deck was to be processed; I finally realized that every other line was a blank comment line. (A "C" in column one, and nothing else on the line/card, for you young'uns).

    I couldn't imaging taking the time at the card punch to type just "C", then feed a new card (which took a couple of seconds) between every line of code, so I asked him why he had bothered.

    His answer...

    [...wait for it...]

    "The professor said the program would be easier to debug if we included a lot of comments."

    P.S. The program, about 15-20 lines long, was devoid of actual comment text.

    1. Re:I have to tell this story... by MtlDty · · Score: 1

      "The professor said the program would be easier to debug if we included a lot of comments."

      Is that what we call a punchline?

  146. Re:Check out Rob Pike's thoughts on code commentin by arkanes · · Score: 1
    waddstr is a procedure, not a function (conceptually - yes, I know that C doesn't make a distinction). In a more verbose language it would be named something like addStringToWindow. It's not about Hungarian style funcion & procedure names, it's a literate style of naming. If you have a function that checks if a window is raised and returns a boolean, don't call it raise, or wraised - call it isWindowRaised() or (OO) window.isRaised() or window.raised(). Using verbose names for both your variables and your functions can do amazing things for the readability of your code, even in the absence of comments.

    Comments are still extremely valuable for explaining why you do something, especially if it's because theres a non-obvious corner case, or there is an obvious change or optimization you can't make for non-obvious reasons.

  147. Identify purpose, interaction, particulars by masinick · · Score: 1

    Regardless of how well written a piece of code is, there always need to be at least a few comments. First of all, I believe that every program should have the name of the program at the top. I believe in code reuse. Therefore, when you grab some code, identify the current name of the file. Identify who wrote the original code. Identify who has changed the code. Identify the purpose of the code - what it does, what, if anything, it expects as input, the environment needed to run it, the tasks it performs, and the outputs it produces. These minimal things ought to be in every piece of code, no matter how small, even if it takes up more room than the code itself!

    Any code that either you or someone else might have to think about ought to be documented as well. Document each block of code. IF there are any lines of code that use some kind of optimization or shorthand, explain what you are doing and why.

    Any good code really ought to be used, even if it was developed originally as a one time hack. Most of my good stuff can be copied and reused many times over. I like to remember what *I* did, but I also want to make my code usable for others. I sure appreciate it when someone else does the same for me.

    Some code is more easily read than other code, but I maintain that no code stands completely on its own. Documentation provides a useful and important context and should never be minimized or ignored. However, that also puts the onus on the documentation to be useful, accurate, and relevant, otherwise it wastes more time and causes more problems instead of being a useful resource.

    --
    Brian Masinick, masinick at yahoo dot com Linux
  148. haikus? by nazsco · · Score: 1

    what is that
    with geeks and haikus? ..ok, i don't have a third line, neither i'm willing to count anything...

    1. Re:haikus? by antispam_ben · · Score: 1

      I wrote assembly
      and I counted cycles. Can't
      one count syllables?

      --
      Tag lost or not installed.
  149. Re:Check out Rob Pike's thoughts on code commentin by Freexe · · Score: 1

    What about using,

    if(!waddstr())
    { //error
    }

    but it's a bad example as its a function you can look up.

    i would use:
    if(!write_to_window())
    {// Returned false, failed to write to window ... debug code ...
    }

    as it's clear what is does and allows you to debug easier

    --
    "In a time of universal deceit - telling the truth is a revolutionary act." - George Orwell
  150. Re:Check out Rob Pike's thoughts on code commentin by arkanes · · Score: 1
    The correct fix here is not to document the bad code, but to remove and correct the bad code. Accepting poor coding and thinking that a band-aid in the form of a comment (and people who write bad code also write bad comments, although the reverse is not true) is acceptible is where you are failing. Sometimes you work with bad programmers, or unskilled ones. If you can't do anything about that and they aren't willing to learn, then theres nothing you can do but suck it up. If you can do something about it, or they are willing to learn, then teach them to write good code first, not to comment half-assed code.

    All that said, the amount you comment can be affected by your target audience. I wrote some C++ code that will be supported and maintained by people with little or no C++ experience, so I went to some lengths to comment common C++ idioms and constructs that I wouldn't normally do - as if I were commenting sample code for a C++ book, rather than commenting C++ code for someone with the same level of experience I have.

  151. When? by cowboy76Spain · · Score: 1

    I, for once, have read TFA and I must disagree -that is why I do not read the articles often-. Comments must be written with the code, if you wait until the code is finished, then your boss will tell you something like "go ahead with the next chunk of code, we will add comments later (that means never)". And if the logic of the program is complex enough, it is probable that after finishing it (and more if there have been holidays in the middle) you have just begun to forget the scary details...

    --
    Why can't /. have a rich-text editor? Editing your own HTML is so XXth century.
  152. Overcomment everything by Animats · · Score: 4, Interesting
    Of course you write comments. Usually more comments than code. Don't look for excuses not to comment.

    Some comments I've written:

    • From a physics engine:
      // The contact force component is aligned with the vector between
      // the two closest points. The frictional force is in a plane
      // perpendicular to that vector and through the midpoint of pnt0-pnt1,
      // The frictional force vector is opposite the velocity vector
      // component in the friction plane.

      // Witness point checks.
      // All witness points must be on their polyhedron's side of the
      // separating plane.

      Here the purpose of the comments is to explain the math.

    • From the control code for a DARPA Grand Challenge vehicle. Here's some code I wasn't happy with, so that's clearly noted.
      // constructPath2 -- reactive obstacle avoidance and path planning
      // - the hard cases
      //
      // Called when we have to do some obstacle avoidance
      //
      // Path is an output only.
      //
      // First pass tries to find some path that will work within the turning limits.
      // If that fails, we try "brake then steer" mode - look for the longest path
      // in any direction, regardless of dynamics limits, and slam on the brakes
      // while turning. The actual steering command will be limited later.
      // ***MAKE SURE THAT CHECK IS MADE***
      //
      // ***NEEDS WORK***
      // ***SEARCHING OUTSIDE LIMITS WILL ALWAYS FAIL***
      //
    • Finally, here's some Perl code, part of the code that runs Downside.
      #
      # extractsecurityclass -- extract class of a NASDAQ security
      #
      # Foreign and bank securities aren't filed with the SEC, so
      # we need to note this. There are also test and statistics items that
      # aren't real securities.
      #
      # Note that the test for "bank" is rather poor. NASDAQ used to
      # identify banks using a column in the table, but they no longer do so.
      #
      sub extractsecurityclass($)
      { my $vals = shift;
      ## Check for symbols that don't file with the SEC
      if (${$vals}{'test_issue'} ne 'N') { return('test'); } ## is test
      (We have to stop there; Slashdot's "lameness filter" rejects Perl code.)

    All code should have well-written comments. As Wirth pointed out years ago, people who can't express themselves well in their native language are generally poor programmers.

  153. /* You are not \n expected to understand this by billstewart · · Score: 1
    /* You are not
    expected to understand
    this */ haiku

    (The classic comment was from the 6th Edition Unix kernel source, in a section that was doing context switches.) (Remember to pronounce "*" as "star".)

    --

    Bill Stewart
    New Fast-Compression-only CPR http://preview.tinyurl.com/dy575ks
  154. Whoosh! by A+nonymous+Coward · · Score: 1

    Could you comment that comment please? I am matrix math challenged.

  155. Self agrandizement by belg4mit · · Score: 1

    Fvck you Denis Krukovsky, and Fvck the editors for posting "articles" submitted by the authors of the linked content.

    --
    Were that I say, pancakes?
  156. Re:Check out Rob Pike's thoughts on code commentin by truedfx · · Score: 1

    waddstr is a procedure, not a function

    As far as I know, the difference is that procedures don't return values, and functions do. waddstr returns a value. What's the difference according to you?

    And the compact waddstr name doesn't matter; if it were named window_add_string, I would make the same point by saying that its name would need changing to window_add_string_returned_error.

  157. Re:Date & intials in comment - Legacy by Merdalors · · Score: 1

    What I meant by "legacy" is one of those big ole' projects that lays dormant for years with lots of forgotten modules, no one actively involved with the code at their mental fingertips, when suddenly something stops working, leaving you scratching your head.

    --
    Slashdot entertains. Windows pays the mortgage.
  158. The only comment you need by Anonymous Coward · · Score: 0

    /* FP! */

  159. At least in C the rule is by washley · · Score: 2, Funny

    "If it was hard to write it should be hard to read."

  160. Two things by Tom7 · · Score: 1

    First, comments are useful even if you are hiding your code forever. I can't tell you how often I've come back to an old piece of code, intended only for my own use, and been confounded by its obscurity or pleased to see an explanation in a comment. It makes a difference. It's also a good way to force you to think about what you're doing before you do it. (Even better are languages that allow you to express some of these things in the language itself, so that they are additionally checked by the compiler!)

    Two: I'm surprised the article didn't explicitly mention pre- and post-conditions, since this has been known for years. When documenting a function, it's critical to state precisely the conditions under which it will work, what it does, and what state of the world it guarantees after being executed. Being specific here helps for the person who wants to call your function, but is even more important for blame assignment: when the program goes wrong, it's important to be able to figure out WHY. Is it the caller or callee? Being able to see that a function is called without its preconditions, for instance, would blame the caller. Seeing that the function doesn't meet its stated specification in a corner case would blame the function itself.

  161. I will write comments... by umbrellasd · · Score: 1

    when the computer learns how to execute them.

  162. I don't have to comment my code by Bahamuto · · Score: 1

    So I use this fancy program that does it for you.

    The Commentator

  163. Article Author on Crack by dmatos · · Score: 4, Insightful

    As per the subject line, the author of this article is on crack. I'm not going to argue the why's and wherefores of his text, but I have a major objection to his "when". He states that the best time to comment code is once it's all done, and you're just about to submit it. WRONG!

    Has he ever worked on a major project? One that cannot be held in one brain in its entirety at one point in time? START with the comments. Start with the program architecture. Decide what each part will do. Write out how each part will accomplish its goals. Then, copy/paste that into your editor, and write the code to match the comments.

    Believe me, if you can plan out how everything will work in the first place, and then just follow your plan, the whole project will be much easier. An added bonus is that the code comments just come straight from your design document. Of course, from the tone of the article, I'd guess that this guy's response would be "What design document?"

    --

    It may look like I'm doing nothing, but I'm actively waiting for my problems to go away.
    --Scott Adams
    1. Re:Article Author on Crack by duckyd · · Score: 1

      write the code to match the comments

      This is a horrible way to go about things, IMHO. The code should be written to match the planned design, but you should *not* need a comment to describe every bit of code. When the code changes, the comments are often left unchanged, and you're left with comments that are worse than useless, they are downright misleading.

    2. Re:Article Author on Crack by dmatos · · Score: 1

      When the code changes - change the comments. Change the design document so that it still reflects the code. In fact, don't change code by changing code. Change code by changing the design document, propogate that through to the code comments, then rewrite the affected code.

      Please note that these comments I'm talking about are not "add one to i". They are more likely to be "find the largest integer in this set". It should be a high-level description of the steps in the algorithm. If your code is changing enough that the algorithm it performs is now completely different, I think you need to re-evaluate your design document before any further steps are taken.

      --

      It may look like I'm doing nothing, but I'm actively waiting for my problems to go away.
      --Scott Adams
  164. Why comment only code? by pe1chl · · Score: 1

    What I often find annoying is that only program sourcecode is always allowed to contain comments, but many systems that store data do not allow comments with that.
    Sure, the programmers that coded those systems must have been familiar with the concept of comments. And so, probably, are the designers.

    Then, why can't I put a comment near a Windows registry entry, that explains why I changed it?
    Or why can't I put a comment in an ACL or Group membership record that explains why a certain access is required?

    There are many similar situations where you would want to annotate some piece of data stored in a file or database, but very often there is no such possibility.

    1. Re:Why comment only code? by hobbit126 · · Score: 0

      That is a very interesting point. What a useful thing that would be. Especially if you could annotate *everything* on a system. Files, network shares, users, groups, applications, event log entries (windows.) And of course, as you stated the entire object hierchy of a database if you like. Not that you should comment every instance of those things, but sometimes... I could see this being extremely useful.

  165. I like mr. Spock's comments by Stormwatch · · Score: 1

    He just says: "Fascinating."

  166. Re:Check out Rob Pike's thoughts on code commentin by arkanes · · Score: 1
    As far as I know, the difference is that procedures don't return values, and functions do. waddstr returns a value. What's the difference according to you?

    In C, it's a conceptual difference. The return value of waddstr isn't important and in fact exists only because C doesn't have any other convenient way of indicating an error condition. waddstr is a procedure because it has side effects.

    And the compact waddstr name doesn't matter; if it were named window_add_string, I would make the same point by saying that its name would need changing to window_add_string_returned_error.

    The compat name does matter because it's exactly the point. Compact names make for hard to read code. And claiming that it should be window_add_string_returned_error just means that you are totally missing the point and don't understand the issue.

  167. Re:Check out Rob Pike's thoughts on code commentin by Chandon+Seldon · · Score: 1

    A function in C that can return an error condition is still a procedure. Consider it as being exactly equivilent to a procedure that throws an exception. Specifically, it's not returning a function result - it's using the value return mechanism to pass an error flag.

    --
    -- The act of censorship is always worse than whatever is being censored. Always.
  168. Like the POS I'm reviewing today by kt0157 · · Score: 1

    Reviewing a piece of software today:

    t->overflow_flag = 1; /* set the overflow flag to 1 */

    Stupid moron! I can bloody well read that you're setting it to 1. WHY are you setting it to 1. What does 1 mean anyway? Jesus. And this code is supposed to go into anti-lock brakes.

    My old prof for assembly programming used to get so sick of reading stupid comments he wrote a stupid comment generator. It would parse the .asm file and then add comments automatically. Like:

    INC X ; add 1 to X register

    Of course, none of the dumb students doing this got the joke. I guess to these people irony is what you add carbony to when you make steely.

    K.

  169. Self-documenting code by Arandir · · Score: 1

    Everybody knows that good code is self documenting

    But self-documenting code is not sufficient. It is very important but it's not an excuse to ignore comments.

    --
    A Government Is a Body of People, Usually Notably Ungoverned
  170. Who Comments What by oldCoder · · Score: 1
    Comment the data before the algorithm. Data is easier to understand. Decades ago, IBM invented a HIPO outline: Hierarchy, Input, Processing, Output. This is a checklist of what should be commented first.

    Comment code by sprinkling examples:
    ... // Sname = "Joe User"
    ... // fSname = "Joe" and lSname = "User"
    ...
    ... // This regex makes sure fSname isn't '23skiddoo
    ... // nCount = 17 iff there are 17 people named "Joe User" in our database.
    The idea is that people figure out the general from the particular better than they figure out the particular from the general. Learning goes in the reverse direction from math. First they see the pattern in the data then they begin to understand the abstract theme.

    Source Code control system and IDE's need to invent a way to allow code reviewers and testers to comment the code, even when they are not allowed to alter the source.

    Coding By Contract helps document things. So do assertions and Unit Tests. Executable comments, so to speak, are more believable.

    Names matter. The more obscure the variable, the longer the name.

    Fix slashdot to allow <code>, dang it!

    --

    I18N == Intergalacticization
  171. My Special Technique by slffea · · Score: 1

    I have never seen this mentioned, but my special trick for commenting
    is to reference as much as possible the book or paper where I got the
    algorithm. Many of us who have been graduate students have gotten
    into the habit of obsessively referencing anything we have
    written because we know the frustration of forgetting the source of a
    particular fact. This should also be done with code.

    An added bonus to this is that you have the book reference do the
    documenting for you which will likely be better anyway since the original
    paper can use fonts, symbols, greek letters, etc., to clearly express an
    equation rather than just text.


    Here is an example of my Free
    Software FEA code.:
    /* This program calculates the eigenvalues of a tridiagonal
          matrix using the QR with Wilkinson shift. It is taken from
          the algorithms 5.1.3, 8.3.2 and 8.3.3 given in "Matrix Computations",
          by Golub, page 216, 420, 421.

          I have made a significant amount of optimization to take
          advantage of the tridiagonal stucture of T.

                                                    Updated 9/2/00

            SLFFEA source file
            Version: 1.3
            Copyright (C) 1999, 2000, 2001, 2002 San Le

            The source code contained in this file is released under the
            terms of the GNU Library General Public License.

    */

          .
          .
          .

    #define BIG 1.0e+12
    #define SMALL 1.0e-12
    #define SMALLER 1.0e-20

    int matXT(double *, double *, double *, int, int, int);

    int givens( double *a, double *b)
    { /* This is algorithm 5.1.3
    */
            double tau, c, s, fb, fa;

            fb = fabs(*b);
            fa = fabs(*a);

            .
            .
            .

    --
    San Le www.slffea.com
  172. Re:Check out Rob Pike's thoughts on code commentin by lateral · · Score: 1

    He's used two stupid examples of commenting

    Actual comment from actual production code:

    return 1; # returns 1

    L.

  173. Re:Check out Rob Pike's thoughts on code commentin by truedfx · · Score: 1

    In C, it's a conceptual difference. The return value of waddstr isn't important and in fact exists only because C doesn't have any other convenient way of indicating an error condition. waddstr is a procedure because it has side effects.

    errno's not exactly convenient, that I'll admit. Anyway, what does this then mean for functions/procedures for which either the side effect or the result can be important? For example, can Perl's map function be called a procedure when it's used as an alternative way of writing foreach?

    I used to use Pascal, so for me, if you make a distinction between procedures and functions, if any value is returned, it's a function to me. If it's called for side effects, it's not suddenly a procedure, it's nothing more or less than a function with side effects.

    The compat name does matter because it's exactly the point. Compact names make for hard to read code. And claiming that it should be window_add_string_returned_error just means that you are totally missing the point and don't understand the issue.

    If waddstr is a function (which you don't agree with), the post I replied to basically said it should be named something like that. All I did was notice that that's what it said, and point it out in hopes of clarification (which I got).

  174. Re:Check out Rob Pike's thoughts on code commentin by arkanes · · Score: 1
    You're taking the OPs comment too literally and reading too much into them. Yes, the name of a function (note that the OP draws a distinction between functions and procedures - C doesn't have such a distinction, so you have to conceptualize a little) should reflect what it returns. That does not mean you use a pseudo-hungarian notation and append the return type to the name, but that the phrasing of the name should indicate the return value. isWindowRaised() returns a boolean. getSystemSettingsAsTree() returns a tree (but is redundant and should be called getSystemSettings if that is the only way to get system settings). Procedures (ie, functions with side effects) should be named by what they do, clearly. There's a convention in C code, especially old C code, to make your function names as concise and non-literal as possible, that is a flaw (not in the language, but in the culture) and should be avoided. setWindowString is a much better name than waddstr.

    Anyway, what does this then mean for functions/procedures for which either the side effect or the result can be important?

    Such functions are generally poor practice. If you have to have one, name it appropriately. The awkward naming is probably a good sign that you're doing something wrong - a function called updateBalanceAndReturnInterest is something you should probably refactor. Note that perls map originates in functional programming, where side effects are prohibited, and using map to generate side effects is terribly bad practice. Of course, 75% of perls common idioms are terribly bad practice, and that is one of the reasons for it's reputation as a readonly language. If you're mapping values to other values, use map - that what it is for. If you're applying a method to a collection, use foreach.

  175. Re:Check out Rob Pike's thoughts on code commentin by rjstanford · · Score: 1

    There's a convention in C code, especially old C code, to make your function names as concise and non-literal as possible, that is a flaw (not in the language, but in the culture) and should be avoided. setWindowString is a much better name than waddstr.

    Actually, it is a flaw in the language - or at least it was. For some time, there was no requirement for C compilers to treat anything more than the first n bytes of the function name as significant. At first I think it was platform-dependent, then "at least 8", and it grew over time. If you tried to have setWindowString and setWindowOnFire both, you could have a namespace collision. This influnced the standard libraries extensively, which in turn influenced most other C code for many years.

    --
    You're special forces then? That's great! I just love your olympics!
  176. Got excited for a moment.... by bigbigbison · · Score: 1

    When I saw commenting classes in five minutes, I got excited because I thought it would tell me how to grade my student's papers more efficiently...

    --
    http://www.popularculturegaming.com -- my blog about the culture of videogame players
  177. Re:Check out Rob Pike's thoughts on code commentin by truedfx · · Score: 1

    You're taking the OPs comment too literally and reading too much into them. Yes, the name of a function (note that the OP draws a distinction between functions and procedures - C doesn't have such a distinction, so you have to conceptualize a little)

    I did, by assuming the meaning of "procedure" and "function" was the same as in a language which uses the keywords "procedure" and "function". Silly me.

    should reflect what it returns. That does not mean you use a pseudo-hungarian notation and append the return type to the name, but that the phrasing of the name should indicate the return value.

    That's what I did. Adding the return type would turn waddstr into waddstr_int. waddstr_error describes the return value.

    isWindowRaised() returns a boolean. getSystemSettingsAsTree() returns a tree (but is redundant and should be called getSystemSettings if that is the only way to get system settings). Procedures (ie, functions with side effects) should be named by what they do, clearly. There's a convention in C code, especially old C code, to make your function names as concise and non-literal as possible, that is a flaw (not in the language, but in the culture) and should be avoided. setWindowString is a much better name than waddstr.

    That I mostly agree with.

    Such functions are generally poor practice.

    I think there are legitimate reasons for it. Since you don't like the map example, how about C++'s new? (Admittedly, it's not really a function, but I think it makes the point clear enough.) Normally, its return value is important, but if your class manages itself, it may actually be reasonable to discard it.

  178. SQLite sourcecode by Anonymous Coward · · Score: 1, Informative

    Anybody who thinks we should rely on self-evident code instead of comments should look at the SQLite sourcecode. Every function has a clear, detailed comment which says nothing about how the function works, but does tell how it fits into the overall program. No amount of code restructuring and variable renaming will do what those comments do. It's the easiest-to-understand opensource code I've ever seen.

  179. Comment tips by geemon · · Score: 1

    Dang! I thought the article would give me a surefire method to always write +5 Insightful comments...

  180. comments by bjb16m · · Score: 1

    D4mn3d college professors! Real programmers don't comment their code. It was hard to write, it should be hard to understand ;)

  181. so? by jrock-jr · · Score: 1

    And in other news, Beatles Beatles has found the cure for cancer on the internet.....

  182. Re:Check out Rob Pike's thoughts on code commentin by bored · · Score: 1
    You can tell he doesn't know what a programmers editor is for, by his rules for variable/function naming. Plus, he apparently hasn't done much maintence programming. Its rules like he gives out that give maintence programmers nightmares. Any editor worth its salt can autocomplete long variable names. Having multiple word names requires some kind of break especially when there are abreviations. is "startrap" read as "StartRap" or "StarTrap". This is usually just a case of someone who can't type. I find that people used to using star_trap find it easier just to type StarTrap. 99% of the stuf in K&R is bad style and is evident all over unix and the standard C calls. For example sbrk() does what? Once you know its "StackBreak" aka StackLimit() then your fine. Then there is atoi(), strtok() (which is completly fsked up, and doesn't work in MT enviroments) and the many other things any C programmer knows what they do, but forgets the pain of trying to look up how to convert an ascii string to an integer, or find a substring when they had just started programming.

    No i'm not encouraging people who have variable/function names like "ArrayIndex" instead of "i" (they should be shot). Rules like he is encouraging cause people to call there variables "maxaddr" instead of "MaxPhysicalBusAddr" when you are a kernel programmer and it could be a virtual address, physical address, pci bus addresss offset etc... Variable function rules should read more like

    1. Be explicit
    2. Don't make up uncommon abreviations
    3. Use a consistent naming convention and stick to it. (underbars for local names, mixed case for class names, suffexes for parameters, whatever floats your boat)
    4. Learn to use your editor so your not affraid of variable names with more than 5 characters


    5. I know this is a M$ hater web site but just about any programmer can learn a thing or two by picking up the "Windows Native API Refrence" and looking at the function names. They are usually pretty long, but its generally pretty easy to understand what they do, and what the parameters they take are. For an example of bad naming conventions just look at the linux kernel source which is full of evil shit for example (not the worst) http://lxr.linux.no/source/kernel/rcupdate.c
      which has wonderful things like "call_rcu_bh()" "rcu_do_batch()". After you read the half page comment it makes sense, but some of this is just basic stuff. Plus about 50% of the functions in that module don't even have single line comment about what they do, any side effects, locking requirements to call etc...

  183. Re:Humour in the Linux kernel - on fire by LlamaDragon · · Score: 1

    I've seen this a lot over the years, but I thought it was actually a reincarnation of much earlier (pre-linux, maybe old mainframe era?) code with the possible explanation being that at that time it was originally written printers catching fire was a much more common threat than it is today.

    But...I could be wrong. :)

  184. I wish good code were self documenting... by ilfak · · Score: 1
    Alas, the expressive power of programming languages is limited.

    You can not document everything required to understand the code in the code itself. Sure, it must be easy to read and comprehend but the self documenting stops there. There always be some aspect you can not put into the code.

    My favorite comments is

    // FIXME: ...
    Seriously, comments must be added if the time spent writing them is less than the time which will be gained trying to understand the code.
  185. Open Source help... by NoName+Studios · · Score: 1

    I had a friend ask me to help him fix a bug in an open source program so he could make it run on his system. I downloaded the code and it didn't have any commenting anywhere in the entire project. I couldn't even figure out where to start looking for the bug. Similiar to my very early complex programming projects. I had to reread the code completely to figure what some of the functions did. I also ended up commenting as I went.

  186. Good commenting? by Anonymous Coward · · Score: 0

    A good comment is one which is written for its readers.

  187. indeed, but to be both traditional & slashdott by Phil+Urich · · Score: 2, Funny

    Soviet Russia
    "Season mention" comments you
    In Winter: Profit

    --
    I remember sigs. Oh, a simpler time!
  188. Re:indeed, but to be both traditional & slashd by gstoddart · · Score: 1
    Soviet Russia
    "Season mention" comments you
    In Winter: Profit

    Summer has ended
    Portman sitting in hot grits
    Alas, never be.

    The season is put
    In the opening stanza
    Excellent effort
    --
    Lost at C:>. Found at C.
  189. Is that you?! by kentyman · · Score: 2, Funny

    //
    Midn, is that you?
    //
    I haven't seen you in like 30 years!
    //
    How've you been?!
    //

    --
    You know where you are? You're in the $PATH, baby. You're gonna get executed!
  190. sarcasm by weierstrass · · Score: 1

    i've thought about this. but there's a whole subset of sarcasm which, even in spoken language, is entirely deadpan and doesn't have any indicators of sarcasm.
    (I think this is the part that Americans have trouble with)

    --
    my password really is 'stinkypants'
    1. Re:sarcasm by obtuse · · Score: 1

      Conversely -
      (No one but Americans has trouble with deadpan sarcasm.)

      --
      Assembly is the reverse of disassembly.
  191. Question for all the coders out there.. by TiggertheMad · · Score: 2, Insightful

    I am an old school coder, and I see a lot of this stuff these days:

    if (foo) {
    // Bleah
    // Bleah
    // Bleah
    // Bleah
    }


    Why do people put the opening bracket on the same line as the conditional? where the hell did this come from? I see it a lot in JS, and more modern C/C++ code. I always though you were supposed to use carrage returns and tabs to make it easy to see the body of a conditional:
    (underscores for whitespace; damn you slashcode!)

    if (foo)
    {
    _____ // Bleah
    _____ // Bleah
    _____ // Bleah
    _____ // Bleah
    }


    Did I miss something? Are all the 'cool' coders doing this now, and I'm just old?

    --

    HA! I just wasted some of your bandwidth with a frivolous sig!
    1. Re:Question for all the coders out there.. by aaza · · Score: 2, Insightful
      Believe it or not, one place it comes from is presentation slides (PowerPoint, or just plain overhead transparencies).
      It lets you get the whole example on the page in a font that is readable from the back of the lecture hall.

      Personally, I prefer it like this. The opening brace on the line with the conditional (for, while, if, etc), the conditional block indented, and the close-brace at the same indent as the start of the conditional. I tried a few other ways*, but didn't like them: they weren't readable enough for me.

      * Other ways tried:
      Open and close brace on separate lines to condition, at the same indent, code indented further (which you have above)
      Braces and code indented further than the conditional, but lined up with each other
      Braces indented from conditional (lined up with each other), code indented from braces [this was the worst]

      It's largely a matter of personal choice, or project code rules, really.

      --
      In theory there is no difference between theory and practice.
      In practice, however, there is.
    2. Re:Question for all the coders out there.. by strider44 · · Score: 1

      The main (and obviously original) place that it comes from is that the original Brian Kernighan and Dennis Ritchie textbook for C used the bracket on the same line compressed style. This is still used as a standard reference so new students learn bad outdated styles.

    3. Re:Question for all the coders out there.. by Chemisor · · Score: 2, Insightful

      > I am an old school coder
      > Why do people put the opening bracket on the same line as the conditional?

      You must not be very "old school" if you don't know the answer. The cuddled braces are the original K&R indentation style; they are what C was supposed to look like.

      Another answer is that there are two different ways to look for blocks. I look at indentation as a clue to the new block and when I see a brace on a line by itself I immediately interpret it as:

      if (x);
      {
      }

      This is especially true when I can't see the end of the line. Obviously, it doesn't take long to switch mental gears, but it is inconvenient. No, I am not going to switch to this style. You have to indent the code anyway and since the indentation change already says "new block", the brace is redundant, and therefore should not be emphasized. I might also point out that the braces are only required for multiline blocks anyway, so looking for indentations is a skill every C programmer needs, wherever he places the braces.

      People who put braces on separate lines look for the opening brace itself to signal the start of the block and panic when they see indentation level change without it. It is really just another way of looking for blocks, and I am disappointed that it is so commonly taught.

    4. Re:Question for all the coders out there.. by petermgreen · · Score: 1

      i tend to open a block on the line that causes it but i do use tabs so i guess i'm somewhere between your two examples.

      the tabs alone are perfectly enough to mark the fact there is a block there no need to waste another line of vertical space by pushing the opening brace down.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    5. Re:Question for all the coders out there.. by jallen02 · · Score: 2, Insightful

      I started coding doing K&R C style braces. I have used them for many many years. I have recently been trying the opening brace on a separate line. It isn't so bad. There are a LOT of languages out there other than C. You can make a bunch of logical arguments for both ways. It is almost like vi vs. emacs. I can spot blocks either way. I also do a lot of Ruby coding which doesn't even use braces and instead uses the end statement to denote the end of the block. So you actualyl *have* to know what statements can start a block to even begin to know if you should be looking for an end to the block.

      As long as you are consistent with your style others will be able to read your code. Maintainability matters more than stylistic preference and both styles are maintainable. They are called STYLES after all.

      And technically automatically interpreting a line without a brace as a terminated statement (IE: with the semicolon) can be just as bad as programmers that can't find a block of code. You should know the language well enough that you can interpret any common brace style. Ok.. no more nit picking.

      I think one of the reasons it still dominates is it still gets used in book writing to condense lines of code. Almost all developers read code examples written here and there. I think this is big on continuing the tradition. When I was working on a my PHP book I know I used the brace on same line as the conditional method because it saved lines.

      In the end being consistent trumps stylistic preference. The best argument I have seen is for condensing code. It does save a line or two here and there if you really need it. With 1280x1024 being a relatively common display resolution used by developers these days I don't think it is such a big deal to have an extra line for the braces :-)

      Jeremy

    6. Re:Question for all the coders out there.. by DeafByBeheading · · Score: 2, Informative
      With 1280x1024 being a relatively common display resolution used by developers these days I don't think it is such a big deal to have an extra line for the braces


      <disgruntled 1024x768 coder>
      How big a deal it is depends a lot on the kind of code you're writing. If you've got lots of small ifs, tight loops, and small functions, the braces *do* take up a significant chunk of screen real estate.
      </disgruntled 1024x768 coder>
      --
      Telltale Games: Bone, Sam and Max
    7. Re:Question for all the coders out there.. by ebbe11 · · Score: 1
      You have to indent the code anyway and since the indentation change already says "new block", the brace is redundant, and therefore should not be emphasized

      No, you don't. In C and languages derived from it, the compiler couldn't care less about indentation. It cares only about braces. The following code snippets will yield the exact same result even though the indentation is wildly different (underscores added to get at least some form indentation (damn you, Slashcode)):

      // Snippet A
      if( test )
      {
      _ ExecuteThis( something );
      _ ExecuteThat( something_else );
      }

      // Snippet B
      if( test ){
      ExecuteThis( something );
      ExecuteThat( something_else );
      }

      // Snippet C
      if( test ){ ExecuteThis( something ); ExecuteThat( something_else ); }
      whereas these two snippets will produce different results even though the indentation is the same:
      // Snippet D
      if( test ){
      _ ExecuteThis( something );
      _ ExecuteThat( something_else ); }

      // Snippet E
      if( test )
      _ ExecuteThis( something );
      _ ExecuteThat( something_else );
      Using indentation to look for code blocks is courting disaster - unless you use Python, of course :-)
      --

      My opinion? See above.
    8. Re:Question for all the coders out there.. by Kosgrove · · Score: 1

      I think the more important question is "Who gives a crap how your braces are structured?" I mean, seriously... it's so far down on the list of priorities in terms of making code readable that it really should be left to the personal preference of the developer. If you're writing new code, use your own brace style. If you're editing existing code, use the original author's brace style.

      There. Problem solved.

      And if carriage returns and tabs vs. spaces are really affecting the readability of your code, you're either developing on a really old platform (I think the AS/whatever C compiler couldn't deal with tabs or something.) or you need to get a better development environment. I use VS myself, but I would imagine that Eclipse doesn't have issues handling carriage returns and spaces/tabs.

    9. Re:Question for all the coders out there.. by Chemisor · · Score: 1

      > No, you don't. In C and languages derived from it, the
      > compiler couldn't care less about indentation.

      We format code for people, not for the compiler. If I were writing code just for the compiler, I could put everything in one line, delete all whitespace, and name all my variables x42. If you did that while writing code for your employer, you'd be fired immediately.

      > whereas these two snippets will produce different results
      > even though the indentation is the same:

      Every programmer's editor is perfectly capable of autoindenting the code for you. Even my ancient vi can do it. In such an editor it takes some effort to screw up indentation, and that effort would have made your mistakes obvious if you tried to type in your examples.

      > Using indentation to look for code blocks is courting disaster

      You look for blocks in order to separate the code into logical units, not to find bugs in it. Debugging and reading are rather different tasks in spite of being inseparably related.

    10. Re:Question for all the coders out there.. by Chemisor · · Score: 1

      > There are a LOT of languages out there other than C.

      Heresy! There are NO languages out there other than C++ :) Seriously, to a hardcore C++ programmer like myself there really are no other general purpose languages. I would use a specialized language for some tasks, of course; Javascript is essential for webpages, SQL is irreplaceable for queries, and shell scripts are very useful for administration work. However, for any serious project there is simply no substitute for C++, and every time I've tried to implement something in another language (notably Perl), I ended up recoding it in C++ as soon as any really complicated task came up. The best language is the one you know well, so it is much better to have perfect knowledge of C++ then to know a dozen languages poorly.

      > And technically automatically interpreting a line without a brace as a
      > terminated statement (IE: with the semicolon) can be just as bad as
      > programmers that can't find a block of code.

      I didn't say I always did that, only that it takes a few distracting seconds to switch to another interpretation style, just as it takes some time to switch between speaking human languages. I interpret a line without a brace as a terminated statement in my code because that is what I usually have. No, not ifs, of course, but I do have a few terminated for loops around. I can't remember using a free block recently, but there are occasional uses for them to manage object lifetime.

      > The best argument I have seen is for condensing code.
      > It does save a line or two here and there if you really need it.

      Saving lines is a good idea whether you need it or not. The more of the code the programmer can see on the screen, the faster he will see its control flow. If a function is so large to require scrolling, he'd have to go back and forth many times. This is particularly bad in C, where all the variables are declared in the beginning of the function. If I had to pick the worst style problem C encourages, this would be it. I hope that all compilers will eventually support declaring variables at the time of use, like gcc now does.

      > With 1280x1024 being a relatively common display resolution used by
      > developers these days I don't think it is such a big deal to have
      > an extra line for the braces

      You just wait a few years, son, and check your eyes again. I work on a 100x30 console (the real console, not an xterm), and that's about as small a font as I can comfortably read all day long. As you can imagine, this is one of the reasons the code I write is as concise as I can make it without losing clarity. In most cases clarity is gained rather than lost.

    11. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      Technically I use two monitors. So I have two screens worth of 1280x1024. I code on one monitor.. which basically is a maximized window of code at a pretty reasonable font size actually. I already have relatively bad vision. Many of my fonts are a size point or two bigger usually.

      I do Java mostly. That is the language I "think" in and know inside and out. I have not done any serious C development in 4 years. I did a good 5 year stretch of hard C development. I am starting to use Ruby. I like Ruby because it takes less code to get things done so I can fit lots of Ruby code on the screen. So I have to agree about saving lines.

      The biggest problem I have is that C++ is just not required for many types of programs. Not sure what sort of development you are doing, so it may be required. Even being one of the best few C++ coders you would be more efficient if you were as proficient in some more dynamic language. (I don't like Perl, either). There will always be a place on a development team for a "Language Expert", but generally you don't need but one of those on a pretty big team. Most programmers do tend to have one language they "think" in. Sadly mine is Java. I don't like it. I think Java is a mess. Ditto for C++. To much baggage in both (design by comittee anyone?).

      For the record I still write C and or C++ in K&R style. It seems perverse not to. I guess I am used to being able to fit more lines of code on the screen. I presently can fit about 53 lines with 120 columns in my fancy GUI editor ;-) So I can afford to use the other brace style and still probably fit roughly the same amount of code on the screen as you can without that style. With it I could probably fit 5-10 more lines of meaningful code pretty easily. Something to think about given that I do believe seeing more code directly translates to productivity.

      Jeremy

    12. Re:Question for all the coders out there.. by hicksw · · Score: 1

      occam offered the resolution: indenting IS blocking.

      And origami was an interesting editor

    13. Re:Question for all the coders out there.. by Chemisor · · Score: 1

      > The biggest problem I have is that C++ is just not
      > required for many types of programs.

      That's a problem indeed; a problem with your thinking, that is. You are thinking that C++ is some heavyweight monster that is only suitable for big problems, while nothing could be farther from the truth. C++ is the lightest language you can use, with the smallest possible footprint. You could go smaller only with C or assembly, neither of which is suitable for anything larger than a small utility program.

      When I think of the enormous VMs required for interpreted languages like Java, I certainly might say that such bloat is "not required" for some small application, and rewrite it in C++. It is guaranteed to be smaller, and quite possibly faster (an I/O-bound program will be slow in any language).

      > Even being one of the best few C++ coders you would be more
      > efficient if you were as proficient in some more dynamic language.

      I disagree. Anything your dynamic language provides is just as easily doable in C++. The difference is that interpreted languages usually have everything and the kitchen sink built in, while with C++ you have to select an appropriate library for your task. With the right library, C++ will do just as well or better than any all-powerful-language.

      I know you'll be mentioning garbage collection next, so I'll explain why I don't need it. While I have no real problem with its concept, I do have a problem with the unfortunate mentality it promotes. GC programmers don't think about ownership and allocate memory too often. In my code, for example, you won't find any memory allocation. At all. You could grep for 'new' or 'delete' all day long and never find one. That's because a good C++ programmer will make use of STL containers for heap management. Those are for permanent storage of various kinds. For short-life objects we use our own GC, called the stack. For heap memory objects, it is extremely important to think about who owns them and how long they will live. In Java the mentality is to just pass around pointers wherever they are needed, reference counting them or whatever, without any thought for such things. That's why there are so many leaky Java programs. In C++ you have to do it the right way -- define an owning object for every allocated block and describe exactly how and when it is allocated and freed. Because it is the right way, I would undoubtedly do it the same way in any language, GCd or not.

      > I think Java is a mess. Ditto for C++. To much baggage in both

      Just because C++ has baggage, doesn't mean you need to use it. Yes, it is quite possible to use C++ in the same way as C. That's what most C programmers do when they switch. They continue to think in functions rather than in objects, refuse to learn about proper design, and complain endlessly how the compiler "does things behind their back". Lacking knowledge about class and template design, they generate slow and bloated code and blame their incompetence on the langauge. Then they go back to C, but, having gotten used to some C++ features, now starting to manually do all those things the C++ compiler used to do for them (like those hand-coded vtables in the kernel modules, for instance) and bragging about being real, macho, cycle-counting programmers.

    14. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      I think C++ is a fairly light weight language in Syntax. And in usage. STL syntax isn't to fun, but it is survivable. I know OO programming very well. I know C programming pretty good. I know the cost of memory and memory ownership from years and years of programming in C. I can understand and interpret x86 assembly. I can get down and dirty with the hardware and tune a C program well. What does not change is that you still have to know and use pointers and all of the syntax required to deal with them in C++. After a time it becomes second nature. And with a little experience in a debugger you can quickly track down most pointer related mischief. What you can't do is manage to write less code in C++. You can make a good run at it with STL and good architecture. However, you will still be writing more code in C++ or Java than you will in a more expressive and concise language. If you have to write less code to accomplish the same goal and you can still do it with performance that, relative to the task, is acceptable why not?

      I admit a lot of Java/C# programmers, myself included on various occasions, can be a little wasteful. On the important stuff I try to keep the code tight and I try and ensure my objects are just as heavy as they need to be and no more. I try to ensure I don't hang on to a reference any longer than I need to. I strive for this because I know memory isn't free. And if you get to wasteful and you have an entire team that lets it slip you end up with a nasty and bloated program (regardless of the language, GC or no).

      I have no problem writing OO code. I tend to prefer OO after writing so much of the stuff. The GoF pattern book was written using C++ and is still just as relevant as always. I know what the stack is too. Java has a stack too ;-). It is still important. Not for memory allocation but if you don't know what the stack is and how it works you won't be as effective in Java either. I remember fixing a method that had way to much recursion. It was quite easy to determine the problem just peeking at the stack and seeing its recursion depth. Just fine for binary trees. Not so great to recurse one level deeper each time you want to spider a new website.

      C++ just is not as productive as some of the languages out there. Lets compare it to say.. Lisp. Lisp for an experienced programmer is a productive language. With modern hardware the cost of Lisp is not so great. A team of experienced Lisp hackers are more productive than a team of experienced C++ hackers. If your language lets you write less lines of code to achieve the same work you will be more productive. If an entire team uses this language the team will be more productive. Good programmers will not abuse a garbage collector any more than a C++ programmer would not leak memory. And you have the luxury of writing good code. And I know.. you have already covered this, but GC does completely eliminate certain kinds of memory leak issues. I know C++ is not some terrible language that produced bloated code and binaries. C++ is where I turn when performance is an absolute. So rarely is performance an absolute with modern hardware. I am doing my clients a disservice to use a language like C++ when I can do the same job for them faster with easier to use tools that let me do my job faster.

      So the argument isn't against C++ because it is a terrible language that can't be used well. The argument is that statically typed languages like C, C++, Java, and C# take more lines of code than a dynamic and expressive language like Ruby or Lisp. If your program meets all of your clients criteria and runs on modern hardware and you can write it twice as fast in a dynamic language why on earth would you spend more time doing it in a language like C++? I wrote code in C long enough to know that even if you are one of the best C or C++ programmers in the world you are still at a disadvantage when compared to a great programmer that knows their way around a language like Lisp or Ruby. It isn't the programmer, it is the language

    15. Re:Question for all the coders out there.. by Chemisor · · Score: 1

      > What does not change is that you still have to know and use pointers
      > and all of the syntax required to deal with them in C++. After a time
      > it becomes second nature. And with a little experience in a debugger
      > you can quickly track down most pointer related mischief.

      The people who complain about pointers are the same ones who don't know how to properly do memory management. I haven't had any "pointer related mischief" in years. Just as thinking about object ownership helps you avoid allocation problems, it will also rid you of all "pointer problems". I think that people are afraid of pointers only because they heard all those horror stories from bad C programmers.

      > However, you will still be writing more code in C++ or Java than
      > you will in a more expressive and concise language.

      You better support that with an example! :) Remember that in C++ you also need to get the appropriate library for your task. If you write everything from scratch, then of course you'll end up doing more work. In your intepreted language you probably have everything already bundled in and have no choice in what constructs you use, whether they are good or bad. The bundled functionality makes that language because it is not possible to natively reimplement them. In C++ it is always possible and is frequently done in order to create better APIs. In Java, you're pretty much stuck with what you have forever and ever.

      > I wrote code in C long enough to know that even if you are one of the
      > best C or C++ programmers in the world you are still at a disadvantage
      > when compared to a great programmer that knows their way around a
      > language like Lisp or Ruby.

      Now, don't go lumping C with C++ here! They are worlds apart. While what you say is almost certainly true for C, it is blatantly false for C++. Once you have objects, the syntax of their creation is of limited importance.

      > The argument is that statically typed languages like C, C++, Java, and C# take more lines of code

      That argument I could never understand. When would you ever be in a situation that you wouldn't know the type of your variables? And how, may I ask, will the maintainers of your code know what's in them if you don't tell them what's in them? Sounds like a recipe for obfuscated code to me.

      Of course, I'm not talking about object polymorphism here, which works just fine in C++, thank you.

      > The truth of the matter is that most classes of programs can be written in more powerful languages.

      I would agree entirely. There is, after all, no more powerful language than C++! ;) [better start defining your terms and giving examples, or how else can I refute your vacuous arguments?]

      > So is your defense of C++ a personal bias or do you really think that C++ is more productive.

      Both. Naturally I'm biased, since I know it so well, but I have also never seen any examples to the contrary. I am also immediately prejudiced against all those "great" new languages; they all claim to be such an improvement over C++, but such claims usually come from not understanding C++. Before you create a fancy new language, you better define clearly what the problem is with the one we already have. Garbage collection is a fine example of a solution to the wrong problem; instead of educating the programmer, change the language, solving one problem while creating a host of others. If you don't understand C++, you are only liable to reinvent it. Badly.

    16. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      > If you don't understand C++, you are only liable to reinvent it. Badly.

      Isn't the saying that you will reinvent Lisp, badly? Greenspun's Rule/Law? ;-)

      This example is of an accumulator generator snagged from Paul Graham's website: http://www.paulgraham.com/accgen.html. Tailored to a problem that functional languages can solve more easily, but it is still interesting.

      I would also recommend: For a Java/C++vs. Lisp comparison.

      And for another programmers take on it where he tries the same thing: C++ hackers take

      Also see another PG article: Succinctness is Power If you google for succinctness PGs article is the first result amusingly enough.

      And here is a pretty famous study done on Erlang: Erlang Study

      I hope we can at least agree that not all languages are created equal. I am honestly not interested in cloning or working in a langauge like C++. I am much more interested in languages like Lisp. I also freely admit that my OO experience leans heavily on Java, Lisp, and Ruby coding. And that I have little real C++ experience. I have done *basic* OO in my C++ programs. I used the STL for a couple of REALLY simple things in one of my later C++ programs but that is really about it. I try to use C++ in its more modern and usable context when I use it, but it is quite a time investment and I am really only after performance if I am using C++ so I keep it as lean and mean as possible and end up with C using objects with new and delete and a smattering of STL when it saves me time and I can easily do it without adversely affect the outcome of my program. So I base a lot of these assumptions on: a lot of C programming, a lot of OO programming, and a little C++ programming.

      You might be onto something about the semantics of OO programming compared to the syntax of the language. It is relatively unimportant as long as the Syntax does not get in the way.

      As for specific types of programs: Web development, simple and relatively complicated desktop applications. Pretty much anything that is not processor bound. I am being vague because I really do believe it in a very general sense. I do a lot of web development.. so in my world I am a little IO bound by network latency. You have to work around big warts like HTTP being stateless and generally you really want to maintain state. I also develop the occasional desktop application (Windows stuff ...Sigh). For Windows programs you really do need to use as little memory as you want, but you can still get away with using .NET which runs in a VM and is GCd. I really do focus on web development and network programming, though. I have written all sorts of programs such as search and data indexing stuff. It is still fast enough with hundreds of megabytes of data and it isn't C++.

      So in my IO bound world I use the most productive and powerful languages I can convince my team to use without secretly wanting to murder me. There is a bigger learning curve for C++. And to be honest I am not concerned about average programmers. I only want people working for/with me that can wrap their head around any programming language even assembly. So ideally I only want to work with people that can use C++ and be good at it. Only I don't want to use C++ because I think the learning curve is not needed. That said is there REALLY a reason for every programmer to understand pointers? Is it really required. We are coming to an age where entire generations of programmers are raised on Java and GCd languages. I wasn't, but I know quite a few programmers who were/are. Do you really have to know assembly on up? Is that important for every programmer to know? You can't even talk to modern x86 processors directly these

    17. Re:Question for all the coders out there.. by Chemisor · · Score: 1

      > This example is of an accumulator generator

      His example in C++ is not all that larger than the lisp version, and mostly concerns syntactic necessities rather than real code. I would omit the copy constructor (because the compiler can write one by itself) and put the inlines on one line, indented to a common point, to make the real code stand out.

      Also, as you pointed out, it is a functional programming example. That is another big difference between us: I really hate functional programming. Lisp to me is the language of gray-haired academics who have never seen the real world. (This view is corroborated by the fact that there really are no useful Lisp programs in the world. Pretty much all the open source code you'll see on SourceForge or elsewhere on the net is either in C, C++, or Java.) It's not so much the language syntax, but the way of thinking of processes as functional trasformations instead of instruction sequences. Since the latter is what the CPU really does, the former seems totally absurd to me. At one time I was trying out STL predicate algorithms for a while, and while they work fine for containers of integers, they fail horribly for any complex processing involving object containers. They also frequently fail to expand to the loops they represent, creating bloat and inefficiencies. So I finally rewrote everything with iterative syntax. The clarity of the code improved dramatically and so did code size and performance. Needless to say I don't use them any more.

      I see the same problem as a plague to mathematics in general. The insistence on describing every system as a function increases complexity beyond all reason. It is this insistence that makes the Shrodinger equation totally useless in describing molecular interactions. If physicists started thinking iteratively and locally instead of creating giant global system equations they would no doubt come up with their GUT much faster and avoid ridiculous things like quantum mechanics.

      > I would also recommend: For a Java/C++vs. Lisp comparison.

      I'd have to see the C++ code to critique. A cursory look over the Lisp version suggest that a nearly direct translation to C++ would be possible.

      > And for another programmers take on it where he tries the same thing: C++ hackers take

      Invalid link.

      > Also see another PG article: Succinctness is Power

      Not necessarily. Just because you have to type less, doesn't mean the code is easier to write. Writing APL code can be pretty damn hard, and it is the most succinct language in existence ;) Readability is also a pretty big factor, as APL demonstrates with flair. To a procedural programmer like me, C++ is far more readable than Lisp and always will be.

      > So in my IO bound world I use the most productive and powerful languages I
      > can convince my team to use without secretly wanting to murder me.

      Convincing your team to switch languages is an entirely different issue from which language you yourself want to use. When on a team, you use the language the team is familiar with. It is counterproductive to use a team of Java programmers to write a C++ application. If you want to do that, you hire a team of C++ programmers. In general you would choose the language before choosing the team.

      > That said is there REALLY a reason for every programmer to understand pointers?

      Is there a reason for every programmer to understand that memory can be addressed? That's what pointers are all about. An address in memory. You understand pointers when you understand how your data is stored in memory, and I would argue that there are few things more important for a programmer to know.

      > Do you really have to know assembly on up? Is that important for every programmer to know?

      Yes. So he would know how much things cost. These days programmers raised on Java are becoming totally ignorant about the cost of what they do. It is because of them that we have obese obscenities like OpenOffice, which tak

    18. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      >and I would argue that there are few things more important for a programmer to know.
      I would change that to *C/C++* programmers. As a Java programmer I very rarely have had to fall back on my assembly and lower level knowledge. And when I did it was to fix problems in a Java app. I was the fixer. And it turns out it *WAS* from lazy programming. But I used what I knew and found and fixed the problem. The program was still done and with a few minor changes was (for a Java program) not all that memory hungry.

      And as far as changing math symbolics. I think if you did that you would end up with Math that looked like COBOL. Its interesting but you are like PGs antithesis He is pretty much loves math and favors languages that trend towards the symbolic (not as far as APL.. ICK!). I am in between. Yet.. when you know how all of that Math works you can look at one page of arcane symbols and comprehend it much more quickly than if you had to go through pages and pages of more verbose math.

      >That is another big difference between us: I really hate functional >programming.

      Well I guess to be honest I still have not bridged the gap over to purely functional way of thinking. And you do have to wonder. PG has a PhD in computer science and obviously likes thinking that way. But some serious programs *are* written in Lisp. Like the backend of Orbitz is done in Lisp and is pretty damn good at finding stuff. (A little slow at times, but never inconsistent).

      I am still an OO thinker at heart. I alert my objects that I want them to do things and model programs in my head in terms of objects. I think that way easiest. I don't think it would be to difficult for me to get good with C++ given my C experience and my OO experience. Though I am sure I will have bad C habits that need eradicating I have quite a head start.

      Dynamic typing. My first and cynical thought is that I am just lazy. There is just a LOT more to it. I don't like having to have an apparent compiler for my code. I don't think its needed to look at assembly to ensure my code is being compiled properly. I will put that burden on the compiler designers unless I see things are way off. Then I will get my hands dirty and figure out what is wrong. Otherwise I am willing to trade little overhead for less typing. I really don't think I will ever become a functional programmer, but maybe some day?

      You are making the case for the average programmer when i tis obvious you are not. Anyone that can understand disassembled code and follow their code through it is *NOT* average anymore. You understand the cost of these things so that should make you even better in a language that gets it right almost all of the time and leaves you to focus on your problems instead of forcing you to compile code before you can check your results. I think a bit before I start writing my code, but some of the time getting in there and getting interactive with the code is great. You just can't do that with statically typed languages. You have to recompile.

      So why dynamic: I know the cost overhead I am losing. I know how far from the silicon I am. (It has been guessed that each step away from the machine is an order of magnitude loss in performance). Thats ok processor speed has been increasing tremendously every year for a long time. Because we don't have to account for every last byte of data and a little excess is ok. Because an object can be *ANYTHING* I want it to be and other good programmers will understand what is happening in my code. I don't need to put a big huge sign on my identifier saying "LOOK AT ME, I AM A STRING!". The times I actually need to know the system can tell me what type the object is. Otherwise life is good. I spent 5 years in C and I got good enough that I didn't have pointer or memory related issues anymore. I thought in C at a time. But it always felt like the language was in my way of solving my problems some of the time. With Java that feeling lessened some. With Ruby that feeling almost goes away. My code is certainly no

    19. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      Meanwhile.. while the rest of the world has moved on from this thread we are still at it two days later. LOL. I will be away for the weekend and such. Feel free to email me and continue this. slashdotdrop (AT)yahoo.com. I will send the email I typically use from there. I dont like giving out my real address here.

      P.S. Read your /. Journal as well. Good stuff there. Particularly liked the article on poverty.

      Jeremy

    20. Re:Question for all the coders out there.. by Chemisor · · Score: 1
      > I don't need to put a big huge sign on my identifier saying "LOOK AT ME, I AM A STRING!".

      That is an argument against full Hungarian notation, not against static typing :)

      Let me try rephrasing the question one more time: how can you manage to not think about the type of the identifier? When I think of variables, I think primarily of the type rather than the name. For example, here's a class I designed a couple of hours ago (just the data fields, for clarity):

      class CClassInfo {
      public:
      typedef uint32_t classid_t;
      typedef vector<ifid_t> ifidvec_t;
      public:
      classid_t m_Id;
      classid_t m_ParentId;
      ifidvec_t m_Interfaces;
      string m_Name;
      string m_LibraryName;
      };

      My thoughts went something like this: "ok, I need an int for the classid, another int for the parentid, a string for the name, a string naming the library it's in, and a list of interfaces it exposes." When I think "m_Id", I automatically think "integer", and I would be curious to discover how you would think of it in some "typeless" way. You see, what it is makes a big difference: if it is an integer, searching is quite inexpensive and I won't worry about doing it often (this is in a compiler-type application, which spends about 40% of its time looking stuff up). If it were a string or a GUID, I'd be more concerned with performance and might add a separate index or a hash table to avoid doing hundreds of string comparisons during a search, I would also have second thoughts about using it as a key for parent class lookup, probably switching to using something else for that purpose. Similarly, I'm choosing to store strings in the object rather than in a separate stringtable to make the lookup code cleaner. This decision implies that I would want to try implementing the db reader such that it will load records on demand (with readahead through a sliding buffer, allowing me to reuse already existing async loading code) instead of reading it all in at once as I would have had to do with a stringtable.

      Then I'd type them in in the order I thought of them and give a quick visual check for alignment. string and vector are both pointer-grain, and so is the vtable ptr. The classids are 4 bytes (fixed-size type because it will be directly written to a binary file), and so should be grouped together to avoid padding on 64bit platforms. I happened to think of them together already, so no reordering was necessary. No problems visible in memory, so I might stop here. Later, when writing serialization routines I realize that the interfaces vector (which is a list of 4 byte ids) should precede the string for optimal packing (vector may end on 4-grain, while I may later want to align to 8-grain if I later decide to write some 8byte int, so starting a 1-grain string in there would save space), so I quickly jump to the header and switch them (reading memory sequentially gives the best cache utilization because the read cache will prefetch stuff that way, and declaring them in order will generally cause the memory block allocated by the containers to be contiguous)

      The above thought process obviously takes a lot less time than the explanation. I can usually complete all of the above considerations well before I finish typing the class in. It's not because I'm an assembly wizard. It's because I always think of these things whenever I create a new class, and have been doing it for many many years. Practice and habit make them automatic and I hardly notice I'm doing it.

      > So instead of ALWAYS having to specify a type I just check the type when it matters.

      How do you avoid stupid errors where you mistype the variable name and end up passing to a function something completely different from what you intended? In C++, the compiler will stop and say, "Whoa! That function works with integers, are you sure you want to give it a Window object?

    21. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      However, if you are VERY fast at fitting square pegs to round holes can you tell the difference?

      Ok ok.. so I do think about types. A LOT. I write classes all of the time (In Ruby and Java). A class is a type. Everything in Ruby is an object. IE: print 4.class will tell you the class of the integer object. My programs are nothing but big ole compositions of types, some I define, some I don't define. So I think about the type ALL the time. I know what types my objects are. The system knows what types my objects are (when it needs to know). So there is no need for me to litter my code with typing information when everyone interested in knowing the type knows it already. So why do you have to specify the type? Instantiating an object of a particular type tells you the type. I just think type safety is overrated. I just dont feel I am missing out when I don't have compile time type safety. I had it for years and it helped with some classes of problems, but those are pretty easy for any experienced programmer to avoid save the typo style errors.

      Have you ever seen Photoshop in action? It uses several hundred megabytes on many images. Most of the overhead is purely in keeping track of big images, NOT some innate overhead of the language it is implemented in.

      Most Ruby programs I have seen use LESS memory than a comparable Java program. There is a bit of constant overhead (literally just 3-4MB) on Windows and that is it. From there it grows as you allocate objects. Y! Instant Messenger takes up about 25MB of RAM on my system. A GUI I wrote to manage a few long running processes here in Ruby and Tk takes like 7 to 10 MB. Less than almost any program I have written. Even Calc takes up 2-3MB of RAM these days.

      I did always think that Lisp's problem was an interesting one. I won't defend Lisp as hard as I might defend Ruby (which is a procedural OO language).

      I have written a non blocking Ruby server that gracefully deals with at least a couple hundred connections PER second without breaking a sweat (HTTP). Files only. It ate about 15 MB and served a static HTML tree using intelligent caching rather well.

      Also the one dead article was the most supportive of the case you are making. (I didn't do it like that on purpose). This C++ programmer took the example and implemented it using standard STL. It took him about 150ish lines compared to the 43 of the Lisp program. He rewrote bits and pieces of the STL to do a little more magic so that some of the iteration constructs were not so ugly and managed to get his program down to like 48 lines and it was semantically VERY similar to the Lisp program line for line. So I do think that it is possible that C++ can be made to have similar levels of abstraction, it just takes more work behind the scenes above and beyond basic C++.

      I don't make mistakes like passing objects. I never mistype code. Praying regularly improves the quality of my code. All kneel before the fickle god Cx86RubyJavaLispCO+BOL+CFo+rtan or perish.

      Seriously. You do get the benefit in a dynamic langauge of being able to rapidly prototype things and work through ideas. Compile time will catch some errors runtime may not. But then, that is life isn't it?

      Heh nice story about debugging programs via assembly. The program I helped triem the memory usage down on mystified their programmers. They were exclaiming how it was garbage collected and they couldn't possibly be leaking memory and that my initial analysis was just wrong. When I found then hanging onto reference via certain globally scoped collections they were VERY sheepish. And it was blatantly obvious (took me a couple of hours to find). Oh well.

      So if our two languages offer roughly the same level of abstraction (I will take is for granted you can make C++ relatively expressive) and there isn't all that much overhead to the Ruby interpreter, just a few MB. And we can also assume that for MOST problems it is algorithm and data structure choices that make the difference, not the underlying implementati

    22. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      I just wanted to clarify a few things. Our discussion has had some tangential points about FP but has mostly cnetered around dynamic vs. static typing.

      I think functional programming is really neat. However, for all of the time I spent using Lisp I still don't call it up as my programming language of choice in my head. I tend to think OO and Procedural in something akin to Java in my head. Java isn't such a terrible language. I have used it so much and like OO and procedural so much that it has just kind of became my default over the years.

      Types are important. I just don't see how specifying the type in code is a requirement. I gain rapid prototyping and a more fluid programming environment which can be really handy when dealing with rapidly changing projects or clients that don't know what they want. This flexibility to bend and stretch and kind of organically grow the software really helps. The whole "I will know what I want when I see it" problem. Sure we start off with a pretty good spec on most projects, but clients and their ideas will always differ from what is written on the spec doc. I have had better experience in dealing with changes in the scope of a project with more dynamic languages.

      Ok back to code for a minute. Lets say I have a line of code like this:

      thingee = new FooBar();

      I now have thingee holding onto a reference to a FooBar object. I know its type. It is of type FooBar. It is very difficult to miss the fact that I just made a FooBar object. So where does that leave me. Well I didn't specify the type thingee can hold. In the world of static typing if I tried to make thingee hold a reference to anything other than a FooBar object I would be really sad. That *CAN* be a good thing. But what if I really wanted thingee to be able to hold references to other objects of any type. In Java I can do this by just making thingee a reference to an Object. Voila now it can hold anything. I just eliminated type safety and gained a little dynamic fun. But you see the language does not like for you to do that. It complains when I do things to the Object that it doesn't think I should be doing. I can only do Object things to and with thingee because it is only an Object. So it does not let me do something like that. Thus it feels like the language is stopping me from doing things that occasionally I may really want to do. In dynamic language world we will just assume the programmer knows what he is doing when he asks the object referred to by thingee to do something. If not you get an error. But then you run into the same problem dealing with generic collections. Java bolted Generics on to deal with this so that you can Type your collections using some compiler syntax. I don't like it as I don't think it really does much to help. Yet you can now have compile time safety when using collections very similar to what you have in C++. I insist that my language let me do just absolutely CRAZY stuff like invoke ANY method on an object. Its my fault if I screwed up and the object referred to by thingee does not have that method. With type safety I don't have the flexibility. With type safety I do have a little extra comfort but I don't have quite as much flexibility about what my references point to.

      To me this is great. I can break the rules in the eyes of a strongly typed programming language and it does not freak out. I like being able to do this. It has been immensely helpful. Combine that with things like mixins (Ruby's answer to multiple inheritance) and you can create objects that have different modules mixed in to dynamically tweak an object as it is going. So its less about its type and more about what the object can do at a given point in time. So in my experience so far I start thinking in terms of what a particular INSTANCE of an object can do at the current time. Not what the class can do as a whole. Check out this link on duck typing: Duck Typing(And yell at me if it is broken again) To me this just seems more in

    23. Re:Question for all the coders out there.. by Chemisor · · Score: 1
      > It complains when I do things to the Object that it doesn't think I should be doing.

      I'm still not quite clear what you are doing here. You have made thingee a reference to a FooBar object; then you call some member function on thingee that FooBar doesn't have. What will happen then? Will you get a runtime error or what?

      In C++ the analogy would be:

      auto_ptr<Shape> thingy = new Circle;
      thingy->Draw();
      thingy = new Rectangle;
      thingy->Draw();

      Using the textbook Shape example, I can point thingy to things that have a particular interface, defined by the Shape class. It makes perfect sense to point thingy to a Circle object or a Rectangle object, but it certainly makes no sense to point it to a MyBankAccount object, and the compiler will helpfully point this out to me. In a dynamically typed language you would not get an error until you ran the program and got to the point of invoking some Shape method, which MyBankAccount doesn't have. In most cases this will work exactly like that, but what if MyBankAccount has a Draw method that withDraws all your money? Your dynamic language will say "Hmm, this looks like a duck right here. Let's see if it walks like one." calling the Draw method anyway without any error. The Draw method drains your bank account as it is supposed to and the computer things everything is just fine. Then, eventually, a few months after you have released the product, some irate user starts calling in death threats.

      > I insist that my language let me do just absolutely CRAZY stuff like invoke ANY method on an object.

      Exactly! And, in following up the above example, how can you be sure that a method that looks like a duck walks like a duck? With static typing I explicitly define what interfaces an object supports, and I explicitly specify what interface I intend to use by declaring the pointer I intend to call members through. I do that because I know what interfaces I have implemented on my objects. I know I can call rect->Draw() because I know that Draw() exists and that it will draw the rectangle. When I call some other object's sdfrtu->Draw(), how do I know what sdfrtu does in there?

      > Sure we start off with a pretty good spec on most projects, but clients
      > and their ideas will always differ from what is written on the spec doc.

      Yes, but just because you can call a different method on an object, doesn't mean that method would suddenly spring into existence. If you were calling thingy->Draw() and the client suddenly decides you should be doing thingy->ResizeAndDraw() instead, you can't just change the call and expect everything to work! You'll still have to go and implement ResizeAndDraw() on all your shapes before anything happens. That's if you remember, that is. A dynamic language will let you implement Circle::ResizeAndDraw and stop there. After all, the client only wants to do it to circles for now. A static language would force you to recognize that you have just altered an interface and that thingy->ResizeAndDraw() might not be always valid any more.

      And instead of waiting until the user hits some weird special case when thingy is a Rectangle, the compiler can tell me now that here's a potential problem, so I can properly alter Shape to contain ResizeAndDraw. If I decide that there is no obvious default action (like calling Resize() followed by Draw()), I can make the call pure virtual, which will help me ensure that all derived classes have it implemented too.

      A dynamic language might let you get away with postponing this work, but you will have to do it eventually. Worse, some green-behind-the-ears intern will be eventually asked to debug some inexplicable problem the user is having. Will he know how to fix it properly? And how long will he curse you for not having done it properly in the first place? And how much will your relationship with that client suffer as a result of this totally preventable bug?

      > With type safety I d

    24. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      I don't know that I am purposefully trying to avoid specifying an interface. I have developed a few libraries and the first thing I did was wrote down everything I wanted the library to do. Then I sat down and mapped out the consumer's interface to the library. IE: The tip of the iceberg. I tried very hard to make sure that my API would not need to be changed even though I knew my library would grow so that all of my code using it would not need to change. Once you have all of that the code just falls in place. I get it. What if somewhere deep in your program and just on occasion you really want an instance of an object (just one instance) to have different capabilities?

      Lets say you have a creature in an online game. A big bad creature. What if I don't know what capabilities I want this creature to ahve up front. What if the game needs to determine well into runtime that the creature can have different capabilities. Why should I have to specify, before runtime, all of the possible interfaces and places this creature gains its capabilities. Lets say the creature starts off with a swim capability and a jump capability. Then later in the game he gets a potion that gives him shoot laser beams from eyes capability. Should I really have to design an interface for the creature that specifically states the creature can possibly have this capability? Why not just attach it to him at runtime? What if in general the creature is just not going to have this capability save for special instances. I would have to provide some sort of interface in the code that specifies he could possibly have this capability at compile time. Or in say.. Ruby at run time I can just attach this capability (mix-in) to him. Then the creature can shoot laser beams. The creature can just have a little code that checks for a capability and uses it. I can see where there may bea little difficulty in, "How does the creature know what capabilities he has". Well we can check or when he takes a certain action if he DOES have that capability then the system lets him do whatever he was trying to do. So if heinvokes the shoot laser beam from eyes command and he does not have the capability he just can't do it. If he tries to swim and he does not have the capability something bad may happen. Why do I have to specify all of that. The shoot laser beam has a well defined interface. The creature himself is a well defined interface. All of the capabilities are well defined interface. I just think it is useful to reserve the right to dynamically mix and match these well defined interfaces. I know I could use base classes of capabilities that would give me the same benefit and clearly spell out that creature has an attack interface. Lser would then implement the attack interface along with all of the other interfaces he should have. And then by having a collection of objects that implement the attack interface. I can then dynamically configure my creatures attack capabilities. However, I had to spend time doing that (IE: specifying the interface). Whereas I can just attach it to him when he needs it instead of having to absolutely specify that he has a collection of attack objects that define his attack capabilities.

      I just don't see it as an error in my thinking. The creature does not have a clean and stable interface about shooting lasers from his eyes. He has *NO* interface that tell him anything about laser beams OR attacking. Yet the laser can still be attached to him and he can still have that capability to attack with no specification of it. Why is that SO terrible. It is just what I would expect from a dynamic programming language. I am still clearly specifying what the attack interface is. And what special properties the shoot laser beams from eyes attack has. So if all of these things have good and stable interfaces why does it hurt to mix them from time to time. I mean.. an attack (shoot laser from eyes) that has the swim capability is silly. But a creature that has swim and and shoot laser from eyes makes perfect sense. I can just keep mixing in a

    25. Re:Question for all the coders out there.. by Chemisor · · Score: 1
      > Should I really have to design an interface for the creature that
      > specifically states the creature can possibly have this
      > capability? Why not just attach it to him at runtime?

      But you are designing an interface when you do this. When you "attach" a capability, you are merging that capability's interface with the interface of the creature. You would do exactly the same thing in C++ as your Ruby "mixin", like this:

      class CLaserBeamShooter {
      public:
      void ShootBeam (Point2d target);
      };

      class CSuperDuperCreature : public CCreature, CLaserBeamShooter {
      };

      CSuperDuperCreature c;
      c.ShootBeam (pt);

      This is not a very good idea though. When you talk about capabilities that can be gained or lost at runtime, you are confusing "is-a" relationship denoted by inheritance with a "has-a" relationship implemented with member objects. A better way of defining a creature with different capability types would be:

      class CAttackCapability {
      public:
      virtual void Attack (Point2d target) = 0;
      };

      class CLaserBeamEyes : public CAttackCapability {
      public:
      virtual void Attack (Point2d target);
      };

      class CCreature {
      public:
      typedef vector<CAttackCapability> attackvec_t;
      typedef const attackvec_t& rcattackvec_t;
      public:
      inline rcattackvec_t PossibleAttacks (void) const { return (m_Attacks); }
      inline void GainAttackCapability (const CAttackCapability& a) { m_Attacks.push_back (a); }
      private:
      attackvec_t m_Attacks;
      };

      This way you get the important ability to enumerate all possible attacks this creature can currently do. This list could be used to create the "Attack" menu in your game UI or to allow random attack selection by the creature AI. I bet you can't think of a way to do that with your design! ;)

      You may want to read Martin Fowler's book called "Refactoring". It offers many examples of class design methods like this.

      > The creature can just have a little code that checks for a capability and uses it.

      This should be the first warning sign that something is wrong with the design. Objects don't check for capabilities. They either have them or they don't. If you need to check for it, it shouldn't be a part of the interface; it should be a plugin. That way the object can treat all of them identically and after writing that generic code you will never have to touch it again no matter how many new plugins (capabilities) you may have in the future.

      > What if somewhere deep in your program and just on occasion you
      > really want an instance of an object (just one instance) to have different capabilities?

      Then you need another class to specify the interface for that object. It doesn't matter if you only have one instance of it. If instance A of class C does something different from all the other instances of C, then A is not an instance of C. A derived class of C can have additional capabilities and be instatiated as A. Really now, typing up a derived class with one extra method is no more difficult than whatever it is you have to do to modify A in your dynamic language.

      This is more of a philosophical issue. Your "special" instance is no longer the same as all the other instances. It is a different "kind" of object, which in OO programming necessarily means that it is an instance of a different class.

      > He has *NO* interface that tell him anything about laser beams
      > OR attacking. Yet the laser can still be attached to him and he
      > can still have that capability to attack with no specification
      > of it. Why is that SO terrible?

      Because you are violating the programmer's expectations for working with objects of that class. When an object's behavior does not conform to expectations

    26. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      And I guess this is where we differ. To me it seems ok if my creature becomes something I did not define in any interface anywhere. Debugging him should not be hard if you have full capability to perform introspection on the object at runtime. So basically you take issue to features and paradigms Ruby people espouse? IE: that it is ok to take several well defined interfaces and then mix them creating an interface that is defined nowhere to acheive whatever capability you need.

      Don't pity me to much. I have grown some of my Ruby code quite a bit. It has just never seemed all that difficult to debug when problems arise. The ways in which you mix interfaces and apply them to objects happen at very well defined points. It is possible to pretty easily determine whena nd where things are being mixed so you can determine: in code where the interfaces are being mixed. And at run time you can determine what interfaces are being mixed. So you know where, and at runtime you know exactly what. Using introspection you can quickly determine everything the creature has. I think the whole point is that you don't have to define in code what all you can attach to an object. You find this scary for maintenance and debugging. In practice this just hasn't been that much of an issue for me.

      If I want to iterate over all of the attack capabilities my creature has I do have access to all of the modules (IE: capabilities) that have been mixed in. I can then determine which of those are attacks and do whatever I want. It is a bit coarse in that it is a list of all included capabilities. However I can just enumerate over the list and save a list of my attack capabilities. Then I could pick a random attack from the list of attacks and do it. So I think it should be possible to do that. I could then save that list of attacks and have the equivalent of a vector for all of my attack capabilities as an instance variable. Butnot until I need it! It is sort of funny you mention Martin Fowler: he really likes Ruby. Not that this in any way validates the langauge or anything, I just find it an interesting point.

      One thing to be clear about... Mixins are NOT classes in Ruby. A module (the Ruby term for what you are mixing into classes) can carry state, but you really shouldn't put to much statefulness into them. They are good for giving capabilities, though. So you get a lot of benefits of aspect oriented programming where you can have cross cutting modules that you can then mix to a lot of different classes. A good example would be something like logging. Just mix in the logging module and then your object can log stuff. Again you think this is bad. How will others know that my foo object has the logging capability if I just attach it to the object at run time. I suppose you could have a logging interface or just go about using composition. But really what makes more sense: implementing a logging interface, giving an object logging capabilities (never specifying it specifically), or going the has-a route and just using composition to give the object a logger? Logging is an important service. Most of your objects are going to want to be able to log stuff, but not all of them. So why is it bad to avoid specifying which objects have logging until run time? It is a cross cutting service that almost any object can theoretically use. it seems silly to have to inherit that interface. With a mixin you avoid the need for multiple inheritance. let me guess, "Why avoid multiple inheritance it isn't nearly as bad as it has a reputation for being.".

      And as I mentioned earlier. In my Java code I would probably just have a collection of attacks the creature could perform. Which is more or less what you suggested as an ideal solution. IE: my creature has-a colleciton that holds all of the attacks he has. So my creature has-a bunch of capabilities. They just aren't granted with object composition. But then modules are not really classes. They are really just collections of methods that *can* maintain state if they really need to. W

    27. Re:Question for all the coders out there.. by Chemisor · · Score: 1

      > So basically you take issue to features and paradigms Ruby people espouse?
      > IE: that it is ok to take several well defined interfaces and then mix them
      > creating an interface that is defined nowhere to acheive whatever capability you need.

      I don't think you are doing what you think you are doing. I just looked at some Ruby tutorials, and to my untrained eye those mixins are nothing more than multiple inheritance. I wasn't able to figure out what the difference was, but you definitely have to define a class to mixin (Ruby calls them Modules, but I see no reason to differentiate them from classes. It must be a terminology thing. In C++ these things would be classes), and the syntax for mixing is the same as specifying a base class in C++. The tutorial mentions that there are "problems" with multiple inheritance that this supposedly avoids, but fails to mention any of them.

      The capability to "extend" the class is basically the same thing as defining a derivative class and creating it with a copy constructor. Ruby seems to be simply replacing the vtable for the class with that of the new class with the extensions. I shudder to think that an object I gave some function can suddenly become a totally different object, as if I gave it a lamb and got back a wolf. I don't know how you can stand debugging such astounding transformations. If you can, you must be one hell of a wizard; I would never allow such unclean things in my code.

      Since this discussion is suddenly all about Ruby, I guess I should look at it a bit closer. I've looked at http://www.rubycentral.com/book/index.html for examples and explanations. Feel free to suggest others if you disagree with my conclusions.

      The language doesn't seem all that different from C++ in substance. All the OO capabilities are there, and aside from the quaint notation the code looks pretty much like it would when translated to C++. It is as if the designer really hated C++ and decided to do everything as differently as possible. That must be the justification, since I found no features that I would classify as improvements over C++.

      There is even the ironic requirement of using C to extend the language, which is truly a laughable point considering the C++ can be extended using C++ just fine.

      When I look at those examples, the words that come to mind are "sloppy", "wobbly", "tacky", and a few other unprintable adjectives. To a C++ person the lack of structure in the code is acutely painful. (From what you've said, that might be what you find so appealing) I'm not sure exactly what is creating that impression, the feeling of a pile of logs where one expects a building, but this problem alone is enough to instill a permanent deep aversion to the language in my mind.

      > It is sort of funny you mention Martin Fowler: he really likes Ruby.

      I don't base my opinions on the opinions of others. If Kernigan and Ritchie themselves proclaimed C to be evil and Ruby to be the pinnacle of quality, I would simply shrug, mutter something about how misguided they are, sigh and go back to coding. In C++, of course.

      > It is possible to pretty easily determine whena nd where things are being
      > mixed so you can determine: in code where the interfaces are being mixed.
      > And at run time you can determine what interfaces are being mixed.

      Maybe your programs just aren't that big. uSTL is ~12kl and it is downright tiny. My C++ projects routinely exceed 50kl in size and I've worked with ones as large as several million lines. There is more than enough complexity in them to worry about without intentionally introducing interface inconsistencies like the ones you're describing.

      > If I want to iterate over all of the attack capabilities my creature has I
      > do have access to all of the modules (IE: capabilities) that have been
      > mixed in. I can then determine which of those are attacks and do whatever I want.

      This is very non-object-

    28. Re:Question for all the coders out there.. by jallen02 · · Score: 1

      I didn't mean to turn this into a Ruby vs. C++ discussion. I guess when I think of C++ and the reasons I don't like it or have always been averse to it I think of Java and Ruby as the two OO langauges I use. So in learning these languages you read about how they eliminate features that were so terrible in C++.

      Like in Java where you are presented with Java as the savior to the problem of memory management. And I think to myself yeah.. I REALLY hated malloc at first. After time I came to only get along with malloc and managing my own memory. I never was happy with it. It always got in the way at some point. It introduced whole classes of bugs in my programs that GC eliminated. I was "sold". Java was the business language du jour so I learned that instead of C++. C++ was and is a commonly used language at the time but Java was more popular and seemed as good a place to go as any for a marketable skill. So that is where I went. I was so happy I had things that helped me avoid the pitfalls of C/C++ (as I thought of it then). I know C and C++ are different now, but that is my line of thinking.

      I am also a web application architect. So I naturally look at tools that have good libraries for web development. Java and Ruby are very strong in this area. I look at C++ and I see very few web development frameworks. I mean practically no one uses C++ for web development. People would go cross eyed if you just mentioned using C++ for web development. It is not something I can change or rectify. I would have to stop developing web apps to really use C++ on my day job. So I just never get around to it. And compared to Java Ruby is much easier to work with and the rails (MVC for web apps) implementation is really good. I am still doing full OO modeling to express my applications but I am using a language that is dynamically typed. It seemed a lot easier to me. I don't even know of any C++ web dev frameworks. I also didn't look. That is probably just my lack of knowledge.

      In my Java solutions I almost always use log4j and a singleton to do logging. So that I can agree with. I was just trying to come up with an example of a cross cutting service that you might want objects to have and that was a bad example.

      And from the very onset the mixin facility is presented as Ruby's answer to multiple inheritance without the mess of multiple inheritance. I have never used C++ hugely. So I am always modeling things the Java way. That means interfaces and abstract classes, NOT multiple inheritance. Multiple inheritance was expressly taken from Java because developers screwed up using it to often. So having a facility like the mixin seems like a step up to me. More flexibility. ALMOST multiple inheritance. Not sure about mixing with a private scope. I don't think you can.

      Presently I work with an application that is about 140kl of code written in a mix of Java and a language called ColdFusion.

      The thing that has always struck me about C++ and Java is that the languages CAN be naturally expressive and short on the line count for code. Yet it seems like you have to know a lot more and work a lot harder to get the code line count down. It always seems like Java and C++ have far to much boiler plate. I am guessing that you would argue each and every line is important and there is nothing extraneous about it at all.

      In Ruby when you mix a module in it holds a reference to that module. So if you change that module any class that has it mixed in is automatically updated. So not only can you change what mixins you refer to you can change the code while the program is running. So you can have self modifying code that changes itself while the program is running. I know.. happens pretty rarely. But for long running server process if you just needed to fix a bug in an attack module you could just fix the bug and then the problem is solved. In a C++ app you would have to reload the process.

      The biggest program I have ever worked on is only like 250kloc. Not huge, but not really small either. Big enough that y

  192. Good Code Is Self Haiku'ing by kahanamoku · · Score: 1

    For I Equals One
    To Four Hundred And Twenty
    Do Function, Next I

    --
    ----- Concentrate on promoting more than demoting.
    1. Re:Good Code Is Self Haiku'ing by Vo0k · · Score: 1

      As you prove, bad code does too.

      For I Equals One
      To MAX_FUNCTION_ITERATE
      Do Function; Next I

      Never hardcode numerical constants, even in Haikus!

      --
      Anagram("United States of America") == "Dine out, taste a Mac, fries"
    2. Re:Good Code Is Self Haiku'ing by kahanamoku · · Score: 1

      following your example, it would be better to say:

      For I Equals START
      To MAX_FUNCTION_ITERATE
      Do Function; Next I
       
      ;-)

      --
      ----- Concentrate on promoting more than demoting.
  193. Comments can be a refuge of lazy programmers, too. by ChaosDiscord · · Score: 1
    People use the 'code should be self documenting' excuse because they are lazy and don't want to take the time to actually write documentation.

    Code should be self documenting because humans are bad at maintaining redundant things. Code and comments tend to diverge. You either spend time being very careful to update both the code and comments, or you spend time discovering that the comments are out of date.

    Keep in mind that "code should be self documenting" is a rule of thumb, not an absolute law. Commenting something that is cryptic by its very nature is a good idea. Documenting the interface to a function is helpful. "Code should be self documenting" isn't lashing out against documentation and comments as a whole, it's lashing out against people who write clumsy, confusing code and slap some comments on as a fix. It's lashing out against people who comment on the "how" while completely glossing over the "why". Unfortunately proper commenting balanced with self-documenting code is frequently glossed over in course. Assignments require comments, but students are really graded on quantity, not quality.

  194. Example by Anonymous Coward · · Score: 0

    Perfect example:
    "This is not a good comment"
    Read Slashdot comments.

  195. one-liners in comments by roesti · · Score: 1

    I comment my code pretty heavily, and I use one-liners all the time:

    // I knew I was dyslexic when I went to a toga party dressed as a goat.
    public static void main (String[] args) {

            // A Buddhist at a hot dog stand said, "make me one with everything".
            System.out.println ("Hello, world!");

            // If being a mother were easy, fathers would do it.
            for (int i = 0; i < args.length; i++)
                System.out.println ("Hello, " + args[i] + "!");
        }

    }

    etc.

  196. devo comments by blyon3 · · Score: 1

    Years ago, when writing lots of S/360 BAL, I'd often be able to use the following
    comments for sections of assembler code:

    go forward,
    move ahead,
    try to detect it,
    it's not too late
    to whip it
    whip it good!

    These days, my favorite comment
    is:

    # Don't touch this unless you know WTF you're doing!

    Which, of course, is no comment at all....

    1. Re:devo comments by antispam_ben · · Score: 1

      # Don't touch this unless you know WTF you're doing!

      Which, of course, is no comment at all....


      No, actually it implies a lot about the intricacy and possible side effects of changing the code. It's roughly equivalent to this 1960's FORTRAN comment:

      C DANGER! DANGER WILL ROBINSON!

      --
      Tag lost or not installed.
    2. Re:devo comments by Vo0k · · Score: 1

      Yep.
      Sometimes the code looks unoptimal, with some null padding and redundant jumps. You change it and things suddenly stop working, despite the fact the code runs ok in the debugger and all you did was some clean-up.
      But the code gets copied to some magical memory area. The null-padding is skipped and matches some magic values/registers that shouldn't be overwritten. Changing the length of the program breaks stuff. There is an unchecked race condition carefully avoided by counting CPU cycles (extreme optimization) and further optimizing one thread makes it trigger the race condition problem because it ends too early. You move a section of code and suddenly target of JMP is more than 127 bytes from its source.
      Things are ugly down there.
      And if program is self-modifying?
      If you perform maths on a jump address, to skip into a specific point of a just-generated matrix of procedures?
      double(**a)(); ?

      DON'T TOUCH.

      --
      Anagram("United States of America") == "Dine out, taste a Mac, fries"
  197. How to write comments... by joto · · Score: 1
    From my experience, the way to write comments, is to make them say exactly the things you want to know when you inherit some other bozos code after 10 years...

    Here's my list of the MOST important things to make clear in code:

    1. WHAT is this shit supposed to do?
    2. WHY do we need to do that?

    Of course, there are other things that could be valuable as comments, such as:

    • HOW does this shit do whatever it's supposed to do?
    • WHERE does this shit get its data from, and WHERE does it put it?
    • WHO came up with this braindead design anyway?
    ...but these are less important than the two above...

    Obviously, I'm the kind of guy who thinks a short README.txt is infinitely more interesting than thousands of "x++; // increase x by 1" lines...

    If you can't even understand what some code is supposed to do, or why anyone would want to do that, then you really have a problem understanding the code. And to tell you the truth, it happens pretty much all time for me... While a program might have a documented purpose, an individual class, or even function or method has a documented purpose, very often you will have to dig pretty deep before you even find out the major components and interfaces of a big program (I.e. which files should I hunt in for changing how part foo behaves...).

  198. Code thriller by Centurix · · Score: 1

    I like to make my comments interesting by inserting snippets from bash.org, keeps the code reviewers occupied... /*
      what is wrong with slashdot.org?? I am almost done reading my 1997-2001 Slashdot.org cache CD-ROM set, if I finish and its not back up, I may perish
    */

    --
    Task Mangler
  199. I had a funny idea for a ThinkGeek T-Shirt... by ndansmith · · Score: 1

    No #

    1. Re:I had a funny idea for a ThinkGeek T-Shirt... by Anonymous Coward · · Score: 0

      got#|&!fire

  200. 5 Ws of Coding by lawpoop · · Score: 1

    I think I'm getting my Ws confused here. How would you differentiate the Why and the What of code? Right now I'm thinking that the What is plain-English pseudocode. Would you agree?

    --
    Computers are useless. They can only give you answers.
    -- Pablo Picasso
    1. Re:5 Ws of Coding by booch · · Score: 1

      I would agree with that. I also agree that it's a tad difficult to distinguish between why and what.

      Most of the why folks seem to think that comments should be reserved for things like "chose algorithm X because Knuth says it's fast". While I agree that should be included, I also think it's helpful to use comments such as "frobulate the widget". Not when the code reads "widget.frobulate()", but when the code is more like "fr = getFrobulator(xyz.widget.picElement[1]); fr.frobulate(xyz.widget.contexts[3]);". And no, it does not always make sense to factor that out into a separate method to make the code completely self-documenting. In this example, you'll often want to choose a different picElement or context.

      This guy does a good job of explaining why versus what comments. I also found this subthread to have good discussion of the topic.

      --
      Software sucks. Open Source sucks less.
    2. Re:5 Ws of Coding by lawpoop · · Score: 1

      It's interesting that the What and Why are confusing here. I've been thinking about the 5 Ws and what they tell us about our perception of reality. Here's what I'm thinking:

      Who - What human or intelligent agents are involved.
      What - Things that are involved, or a synopsis of events in noun form (i.e. a killing, a breach of contract).
      When - At what time events took place.
      Where - At what location events happened.
      Why - The motives of the actors involved.
      How - The mechanics of purely physical events (i.e. a tree falling and hitting a roof), or the steps a 'Who' took to accomplish a goal or plan.

      If the 5 Ws are all we can verbally use to inquire into reality, it's interesting to me that we have one that deals specifically with motive and planning. This is like the 'intuitive psychology' that evolutionary psychologists say are hard-wired into our brains.

      --
      Computers are useless. They can only give you answers.
      -- Pablo Picasso
  201. How I roll by hobbit126 · · Score: 0

    I always am interested in seeing different styles as far as commenting. I've read some interesting things here. I figured I'd share an example of my own style:

    http://hobbit.ninebit.org/commentexample.html

    I think that most people will probably find this all way too verbose. It suits my needs well though. I've been using it for years. Once you get used to it, it isn't too bad to write, and it's very nice on the reading side.

    I put comments at the top of the file explaining what is included and why you would include or run the file (depending on if it's an app or a library.) This is so that I know right when I open the file what I'm about to read. I include a list of authors here so that you know who to go to with questions. I do *not* include the date or any other information that is either useless or can be found by looking at the properties of the file itself.

    I put comments at top of classes explaining what they are for in context of the entire application/library. This is so that when I locate the class I know exactly what it's for and how it fits into the grand scheme of things.

    I put comments at the top of methods explaining what they are for in context of their class. This is so that I know exactly what a specific method is for.

    Occasional decorated grouping comments to provide easy visual navigation of the file.

    Most of these comments don't fall out of date too quickly by nature of *what* is commented (purpose)

    Beyond that:
    A good editor will give you the navigational tools you need to find your way around a good bit of code and visualize the class structure a bit.

    A good source control system will give you all you need in terms of modification notes, dates and authors. The only reason that I keep the author list in the source file is for convenience, and because it's one of those things that if it gets out of date it's not really a huge deal.

  202. Re:Check out Rob Pike's thoughts on code commentin by pommiekiwifruit · · Score: 1

    Well, it's the linkers that have the problem really. Blame IBM and their poxy 6 character limit on function names for mainframes for much grief. I'm annoyed at the current (modern) linker I am using which has a 32 character limit, which is very annoying for generated labels (coming from filenames from content creators).

  203. under interogation? (the obvious post) by Chapter80 · · Score: 1

    No comment.

  204. Hard problems by Dire+Bonobo · · Score: 2, Insightful
    > If it is not obvious from the code, it should be refactored.

    If it is obvious from the code, your project is too simple.


    (Flippant, but not totally false. I work on research code that does...significantly complicated things. It can be hard enough for me to keep track of the interactions of the algorithms even when I'm designing them on paper; translate them into code, and the result is not at all trivial.

    What my code does can be hard to understand when I've made a serious effort to clearly explain what it does in prose; even then, I expect understanding what it's doing to require effort from other researchers in my subfield. To expect any of them---much less a more junior researcher---to understand what is going on from the code alone is simply nonsensical. They would dismiss it as a waste of their time, and rightly so.

    If code were that easy to read and understand, it would be found in most computer science research papers; that such papers avoid it like the plague suggests that's not the case, even for less-complicated problems.)

  205. Re:Check out Rob Pike's thoughts on code commentin by Anonymous Coward · · Score: 0
    In code imported from Japan:
    Font font; // <Japanese word for "font">
    And I know a little Japanese, but I'm not fluent, so I had to translate the comment to discover this.
  206. Season on the FIRST line by Anonymous Coward · · Score: 0

    A Leaf falls to remind
    the rule for Haiku is
    Kigo for season on first line always
    --- Sorcery

  207. Curious how others handle changing code... by oddtoad · · Score: 1

    A common experience for me is that my understanding of my classes and their true purpose changes overtime. This of course means that my comments must change if they are to keep up with my code. This means that I must rewrite a lot of comments which is really throwing away work...something I hate to do. A lot of times I know that a class will change as my understanding of it's role becomes clearer when I code other classes with which it will interact, so I purposely hold off on commenting until things become clearer. Unfortunately, following up doesn't happen as often as I wish. I know we are supposed to understand everything up front before we start coding, but that's just not realistic and a lot of important insights occur while coding. So I'm currious to hear how other /. handle this issue.

  208. Re:Check out Rob Pike's thoughts on code commentin by phlamingo · · Score: 1

    In general, Pike's essay is too general to be specifically useful.

    However, I believe this is the smartest thing he says in this essay:

    I argue that clear use of function pointers is the heart of objectoriented programming. Given a set of operations you want to perform on data, and a set of data types you want to respond to those operations, the easiest way to put the program together is with a group of function pointers for each type. This, in a nutshell, defines class and method. The OO languages give you more of course - prettier syntax, derived types and so on - but conceptually they provide little extra.
    Of course, it has nothing to do with comments ...
    --
    I had forgotten how much cooler teenagers look when they are smoking. Oh, wait ...
  209. Okay by weierstrass · · Score: 1

    You proved me wrong :)

    --
    my password really is 'stinkypants'
  210. Emphasize the WHY not the WHAT by angel'o'sphere · · Score: 1

    The WHAT:

    For a class 2 or 3 sentences about WHAT the class is doing should eb sufficient. Similar for methods one sentence of comment WHAT the method is doing should eb enough.

    I only use more than the reccomendation above if a non obvious design pattern is involved.

    I (and most in my company) don't comment set/get methods. Except there is something special to know about.

    The WHY:
    I coment stuff that looks unusal, e.g. a typical for loop goes from 0 to n - 1, to iterate over n items. But some times you start at 1 or count up to n or count to n - 2. WHY? Thats worth a comment imho!

    If the flow of a method is not obvious I might add a one line comment above a section like:
    { // open file ... some code // read header ... some code // read contents ... some code // close and finalize ... some code
    }

    However in such a situation its more appropriated to refactor the complete method to call private helper methods:
    {
          file = openFile();
          file.readHeader();
          file.readContent();
          finalizeAndCleanUp();
    }

    And now: you don't need any comment at all.

    My background:
    I learned commenting from books teaching programming languages. And I have the opinion most people did.
    That was stupid :D as the programs comments only tried to explain the syntax or semantics of the -- for me -- new language. So indeed stuff like: i++; // increment i where written there and I did copy that style for a while (20 years ago, ofc).
    Such a comment is of course complete nonsense if you know the language.

    Regards,
          angel'o'sphere

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  211. If shakespeare were a programmmer... by AuricTheCodePoet · · Score: 1

    I would like to see somebody attempt to write code using Iambic pentemeter... hahaha Good code should be easy to read, stupid coders should be beaten over the head...

  212. Haikus are... by guanno · · Score: 1

    Haikus are poems
    with seventeen syllables
    in three lines of verse