Slashdot Mirror


Comments are More Important than Code

CowboyRobot writes "I was going through some code from 2002, frustrated at the lack of comments, cursing the moron who put this spaghetti together, only to realize later that I was the moron who had written it. An essay titled Comments Are More Important Than Code goes through the arguments that seem obvious only in hindsight - that 'self-documenting' code is good but not enough, that we should be able to write code based on good documentation, not the other way around, and that the thing that separates human-written code from computer-generated code is that our stuff is readable to future programmers. But I go through this argument with my colleagues, who say that using short, descriptive variable names 'should' be enough as long as the code is well-organized. Who's right?"

164 of 1,021 comments (clear)

  1. Even more annoying... by Anonymous Coward · · Score: 5, Funny

    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

    1. Re:Even more annoying... by eobanb · · Score: 2, Interesting

      Well then, just employ a code comment moderation system.

      --

      Take off every sig. For great justice.

    2. Re:Even more annoying... by Klar · · Score: 5, Insightful

      hah I also grade as a university TA, and let me tell you what is more annoying than that... people who don't know how to indent their code, and want you to help debug it! Ahhhhh!!!!!

    3. Re:Even more annoying... by zachtib · · Score: 2, Interesting

      Thats why I love eclipse, auto-indenting (Ctrl Shift F) comes in handy when fixing other peoples' code

    4. Re:Even more annoying... by FuzzyBad-Mofo · · Score: 2, Funny

      And a metamod system to deal with the inevitable poor moderation. Hmm, Slashcode as a source control system? Scary thought..

    5. Re:Even more annoying... by Anonymous Coward · · Score: 2, Insightful

      Emacs will handle that too...

    6. Re:Even more annoying... by s100w · · Score: 2, Funny
      Some of your graduates most have taken jobs at my company.
      /**
      * Gets the name
      * @returns String name
      * @author RG
      * @throws Exception
      * @param boolean
      */
      public String getName(boolean b) [
      if (b) {
      return magicalSideEffectGetter();
      } else {
      return name;
      }
      // Changed by RG 10/18/1999
      // Re bug fix #1044
      // return name;
      }
      Of course, the old code, revision date, and author is in CVS. And the bug is in the bug database, but ... more comments are better, right? In the real world, this method would be about a page long.
    7. Re:Even more annoying... by Anonymous Coward · · Score: 5, Insightful

      You know whose fault that is? The morons that mark you down if you don't comment trivial programs like Hello World.

      I actually ended up doing three introductory programming courses at college and university (overlap in curricula), and I've been marked down for not including this type of comment in all three courses.

      printf("Hello, world!\n"); /* send "Hello, world!" to the console and move to the next line. */

      The problem is that they try and teach you to write comments prematurely. When all most people on the course can write are programs like Hello World, they really can't see the use of comments and there are no good examples to give. The use of comments should come after things like functions etc IMHO, so that students can actually see how comments can be useful.

    8. Re:Even more annoying... by AndroSyn · · Score: 4, Funny

      1994 is calling and it wants its Sparc IPX back.

    9. Re:Even more annoying... by coaxial · · Score: 5, Funny

      I came across that with a grad student at my univ. I told him that I couldn't read his code because it wasn't indented. He said, "I was going to back and do that later." WTF? I thought that was going to be the Quote of The Day, but it turned out he wasn't done yet. I started indenting every line as I walked through a function. Seeing this, he inquired, "How are you moving those lines over?" My answer? "Tab."

      Shocking.

    10. Re:Even more annoying... by Gilk180 · · Score: 5, Funny

      An emacs post replying to an Eclipse post and you choose to point out how bloated emacs is?

    11. Re:Even more annoying... by llamaluvr · · Score: 2, Insightful

      Don't forget about students who use assert()'s for validating user input!

      --
      Insightful: 76, Off-Topic: 379, Flamebait: 24, Funny: 152, Interesting: 201, Underrated: 55, Troll: 9, Total: 896
    12. Re:Even more annoying... by el-spectre · · Score: 5, Funny

      As a freshman I had a professor who kept giving me shit about not having enough comments, so my next program looked something like this: ...
      a=5; //assign integer variable 'a' a value of 5
      b=2; //assign integer variable 'b' a value of 2
      print(a+b); //print to the console the sum of integer variable 'a' and integer variable 'b' ...

      and so on, for about 200 lines. Worthless commenting? Sure, and childish too... but it was amusing and I never got docked for insufficient commenting again :)

      --
      "Faith: Belief without evidence in what is told by one who speaks without knowledge, of things without parallel." - A.B.
    13. Re:Even more annoying... by aixou · · Score: 4, Funny

      Heh.. his roommates probably think he's having some marathon maturbation session when he's in his one of code-indenting sessions (presumably with the space bar?)

    14. Re:Even more annoying... by Anonymous Coward · · Score: 5, Informative

      in vim, with C code, you can just do:

      gg=G

      and it will reindent a file for you....

      I hate programmers who refuse to learn about their tools.

    15. Re:Even more annoying... by T-Ranger · · Score: 5, Insightful

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

    16. Re:Even more annoying... by Ratbert42 · · Score: 3, Funny

      I just ripped this comment out of our code today: // close the file
      closeFile();

    17. Re:Even more annoying... by JohnsonWax · · Score: 4, Insightful

      The problem is that they try and teach you to write comments prematurely.

      No, the problem is that they try and teach you to write code prematurely.

      Document your application, requirements, constraints, and system interactions (what the engineer does). Then write the code (what the coder does).

      What you will quickly learn is that it's better to be the engineer than the coder. What you'll realize is that the engineer is the client-side guy that figures out how to solve the challenge presented and the coder is the guy who can live in Manipal.

      The computer scientist is another guy altogether, that sets the boundaries within which the engineer must work and provides many of the tools.

      Somehow CS education has gotten horribly derailed, and asks students to combine the equivalents of electromagnetic theory, power system design, and basic home wiring in one curriculum. No wonder enrollments are plummeting - nobody knows what a CS major is or should do.

    18. Re:Even more annoying... by tomhudson · · Score: 4, Interesting
      What should be done is: Take this 1000 line programme. Add on 5 lines. Add on 20 lines. Add on 100 lines.
      Better yet - remove 5 lines. remove 20 lines. remove half the lines ... and it better still work!
    19. Re:Even more annoying... by neckjonez · · Score: 2, Interesting

      the classes in which I learned the most about programming was not so much writing my own code, but "here's a pile of code, it does this. expand it to do this and this and this other thing"

      very very good learning experience, because you then learn the value of comments as well as extending a program.

    20. Re:Even more annoying... by rve · · Score: 5, Interesting

      At work, we are not allowed to use comments in the code.

      Allowing comments would "encourage coders to use clever tricks" according to the technical director.

    21. Re:Even more annoying... by Coryoth · · Score: 2, Interesting

      Document your application, requirements, constraints, and system interactions (what the engineer does). Then write the code (what the coder does). What you will quickly learn is that it's better to be the engineer than the coder.

      Interestingly there are a number of formal languages to do this, some of them rather similar to programming languages. For example you can use an algebraic specification language like CASL - it provides a structured way to define datatypes, operations on datatypes, and the axioms that the types and operations need to obey for the requirements to be met (For the mathematicians out there: an implementation is then a (many-sorted) universal algebra, and a specification is a presentation). There are things like refinement calculus and theorem provers to help you refine your requirements into an ever more specific specifications. Once that is done the actual programming is pretty much monkey work: there are extremely specific bounds on every datatype, every function, to the point where it is merely a matter just doing what you're told. The interesting part happen with the initial requirements specification and the refinement and design of the specification.

      I happen to like CASL, and chose it here because the the syntax is similar to programming languages, but it is far from the only, or even the most popular specification language. You could try Z, or VDM, or B-method, or OBJ3, or any of the myriad other languages out there. Formal specification languages ought to be far more widely used than they apparently are. Isn't it about time more "software engineers" started paying attention to them?

      Jedidiah.

    22. Re:Even more annoying... by PickyH3D · · Score: 2, Insightful

      You cannot read code before you can write code. Your idea should be the 4th step. Let them do the basics, and then learn to mess with something intermediate. After all, that many lines of code is going to be intimidating to someone not intending to go past that level of the course.

    23. Re:Even more annoying... by geminidomino · · Score: 5, Funny

      So tell us, since you have an inside view:

      When is Longhorn actually coming out?

    24. Re:Even more annoying... by Wavicle · · Score: 2, Interesting

      Obviously you didn't learn shit. NO MAGIC NUMBERS means:

      I think the gp post is implying that the students didn't understand why "no magic numbers" was a problem, so they worked in magic numbers anyway without grokking why you would give a number a meaningful name.

      That is they didn't understand:

      MAX_VALUE = 17;
      if ( x > MAX_VALUE )

      vs.

      SEVENTEEN = 17;
      if ( x > SEVENTEEN )

      --
      Education is a better safeguard of liberty than a standing army.
      Edward Everett (1794 - 1865)
    25. Re:Even more annoying... by zonix · · Score: 3, Funny

      What should be done is: Take this 1000 line programme. Add on 5 lines. Add on 20 lines. Add on 100 lines.

      Better yet - remove 5 lines. remove 20 lines. remove half the lines ... and it better still work!

      Pfft! Just remove the comments! ;-)

      z
      --
      What would an EWOULDBLOCK block, if an EWOULDBLOCK could block would? -- me
    26. Re:Even more annoying... by Shawarma · · Score: 2

      I've actually been looking for some of these ebay-for-coders sites.
      Do you have any URL's?

      --
      Parse error: parse error, unexpected T_ELSEIF in /var/www/slashdot.org/comments.php
    27. Re:Even more annoying... by conradp · · Score: 2, Insightful

      As a freshman I had a professor who kept giving me shit about not having enough comments, so my next program looked something like this: ...
      a=5; //assign integer variable 'a' a value of 5
      b=2; //assign integer variable 'b' a value of 2
      print(a+b); //print to the console the sum of integer variable 'a' and integer variable 'b' ...

      and so on, for about 200 lines. Worthless commenting? Sure, and childish too... but it was amusing and I never got docked for insufficient commenting again :)

      Yes, it's worthless and childish. What would have been better? This:
      numberOfApples=5;
      numberOfOranges=2;
      print(numberOfApples+numberOfOranges);

      If code is well-written and uses good abstractions, good variable and function names, and short functions, it needs far fewer comments and is more understandable.
      --
      "To be absolutely certain about something, one must know everything or nothing about it." -- Olin Miller
    28. Re:Even more annoying... by FireFury03 · · Score: 2, Informative

      people who don't know how to indent their code, and want you to help debug it!

      So tell them to go away and come back when it's properly indented. Point them at the tools they need to automagically indent their badly indented code. They'll never learn if you don't tell them that they have an unreadable coding style and explain to them why intenting is a Good Thing.

    29. Re:Even more annoying... by ashultz · · Score: 2, Funny

      I can't tell if this is a real comment or a joke.

      gg=G to indent C code? The only way to learn a command like that is to have it whispered to you in the alley behind the Bang and Bracket pub at midnight by a Romanian Documentation Smuggler.

    30. Re:Even more annoying... by jim3e8 · · Score: 2, Informative

      gg go to first line
      = indent
      G until end of document

      vim has an excellent help system. :help 30.2 takes you right to the relevant section (30.2). Lo and behold, "If you have really badly indented code, you can re-indent the whole file with: gg=G".

      This is what it means, "learn your tools."

  2. Gotta document that code... by TripMaster+Monkey · · Score: 5, Interesting
    From the Summary:
    ...I go through this argument with my colleagues, who say that using short, descriptive variable names 'should' be enough as long as the code is well-organized. Who's right?


    You are. No question.

    I have a saying I like to use when people (usually managers) try to persuade me to take the quick/cheap way out:


    "Any time/money you save by cheaping out now, you'll wind up having to pay back twice over on the back end."


    I've yet to see this maxim disproved, and it's just as applicable to coding as it is to anything else. Your colleagues are certainly correct when they state that the code must be well organized, but this simply isn't enough. If you don't put in the necessary time (minimal, really) to properly document your code, you'll wind up spending a lot of time trying to figure out just what you did and why. Also, even if you can remember exactly what your code is all about, the guy that comes after you probably won't...proper documentation is professional courtesy. I suppose they'll learn after they spend a few hours puzzling over a piece of old code (that's how I learned...:P ). Sooner or later, not documenting properly will bite them in the ass.

    --
    ____

    ~ |rip/\/\aster /\/\onkey

    1. Re:Gotta document that code... by Fjornir · · Score: 5, Insightful

      The canonical form of your maxim is "If you don't have time to do it right the first time, when will you find time to do it again?". The correlary is: "The problem with quick and dirty is that dirty remains long after quick is forgotten."

      --
      I want a new world. I think this one is broken.
    2. Re:Gotta document that code... by eobanb · · Score: 2, Funny

      Judging from your indenting, I'm sure glad I don't have to read YOUR code.

      --

      Take off every sig. For great justice.

    3. Re:Gotta document that code... by RootsLINUX · · Score: 5, Insightful

      I agree. Giving your variables descriptive names is a good practice, but it's not nearly enough "commenting". If you have a piece of code that manipulates the values of those descriptive variables with bit masks to spit out a value, how is someone supposed to know what you just did? I think the adage "you don't document your code, but you code your document" is a little extreme, but it gets across the importance of code documentation. I'm working on an open source project of my own right now. I went back to modify a piece of code that I hadn't touched for nearly 4 months, only to make absolutely no sense of what the hell I was doing there. Luckly I commented it extremely well so after reading the comments I was able to get that "Oh yeah..." feeling and make the appropriate modifications without breaking the code. Lesson: commenting code may take you some more time now, but it's going to save you a hell of a lot of time later.

      On that topic, what are some good examples of well-commented code? Rather than just see words, I'd rather see real-life applications of these practices. For starters, here's typically how much I comment my code: Allacrost source code (note: not all files were written by me, by I try to stress heavy commenting on the rest of my team)

      --
      Hero of Allacrost, a FOSS RPG for *NIX/*BSD/OS X/Win
    4. Re:Gotta document that code... by Fjornir · · Score: 2, Insightful
      ...how does that work when I need hardcopy again?

      I actually agree with you though -- as long as the indent character in question is a tab. People who want to indent with spaces need their heads examined.

      --
      I want a new world. I think this one is broken.
    5. Re:Gotta document that code... by Xyrus · · Score: 2, Insightful

      Comments are essential to maintaining any project.

      It's annoying when I go to the person who wrote a chunk of code fom a couple months ago to ask them some questions, they look at the code and have no idea why they were doing what they were doing.

      I've always followed the philosphy that I should write and comment code so that someone who wasn't a programmer could read it and understand what was going on. This makes it very easy to go back even years and know exactly what the code was doing and why it was doing it.

      But you need to write good comments and good code. I've actually seen this in code: /**
      Gets an array.
      @return An array.
      */

      Array GetArray() ...

      The other one I live seeing is data structures containing non-descriptive field names: //Holds temporary data
      struct TmpData
      {
      int a;
      int b;
      float c;
      };

      Completely useless.

      Good code and good comments makes everyone's life easier. I've seen a lot of good code, I'd like to see a lot more good comments as well.

      ~X~

      --
      ~X~
    6. Re:Gotta document that code... by snorklewacker · · Score: 5, Insightful
      You are. No question.

      Hello. I question. Look, if you need comments to explain the code flow because your method spans four screens and has six levels of conditionals in two levels of loops, all the comments in the world won't help you.

      Especially if you change the code and now the comments are wrong

      I have had the joy of maintaining lovingly commented code with all these huge blocks at the start showing what args get passed and what happens, and I can't understand a god damned thing about what it's doing, because the code all looks like
      (void *((ebuf->qs) > VRT_FBUF) ? etranf(&q) ...
      All generalisms are wrong.
      --
      I am no longer wasting my time with slashdot
    7. Re:Gotta document that code... by rkcallaghan · · Score: 5, Insightful

      Sooner or later, not documenting properly will bite them in the ass.

      Actually I have found that more often than not, not documenting properly only bites someone else in the ass.

      This is likely the source of the problem, and the least likely to change. I suppose it could be part of the QA process to check for notation on code, but I somehow suspect that with programming jobs on a one way trip to Bangalore that readability it secondary to "works cheap."

      ~Rebecca

    8. Re:Gotta document that code... by B'Trey · · Score: 2, Insightful

      The code needs to be well documented, where "well" means both "correctly" and "frequently." Lots and lots of poor documentation is just as bad as little or no documentation. And documentation, no matter how well done, will not fix lousy code.

      So I don't question. The story poster is correct. Code needs to be well documented, and neither good organization nor descriptive variable names is a sufficient replacement for documentation. But you're absolutely correct too that documentation is only a small part of what it takes to write good code.

      --

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

    9. Re:Gotta document that code... by Stradivarius · · Score: 2, Insightful

      If you don't put in the necessary time [...] to properly document your code, you'll wind up spending a lot of time trying to figure out just what you did and why

      The corollary to this is the need to maintain existing comments when the code is changed. Misleading/outdated comments can sometimes be worse than none at all.

      proper documentation is professional courtesy

      I couldn't agree more. Good documentation gives you context and insight into the motivation of a past developer, which can be priceless when trying to understand unfamiliar code. Good variable names can give you the "how" the code is implemented, but good comments give you the "why".

    10. Re:Gotta document that code... by AWhistler · · Score: 2, Interesting

      And don't forget the maxim that seems to be prevalent everywhere, even though everyone "knows" this shouldn't be....

      "There's never enough time to do it right, but always enough money to do it twice."

    11. Re:Gotta document that code... by coaxial · · Score: 4, Insightful

      I actually agree with you though -- as long as the indent character in question is a tab. People who want to indent with spaces need their heads examined.

      There's no solution to the indention problem. You'd think simply mandating tabs would work, because that way everyone can set the tabstops to whatever they want, but in practice it doesn't work. People don't setup their editors the same way. Some have "tab indents with tab", which would be the correct choice, but other have "tab indents with spaces". Then you have those that refuse to use tab at all, or decide to use spaces to align certain blocks, and so you get a mix of tabs and spaces in a line. The line looks right with tabstop=4, but looks like crap with the default tabstop of 8. This assumes people don't untabify on open and save. That replaces all tab characters with spaces.

      In practice, a file that is touched by enough people will end up having every line indented to some screwy level with nothing lining up correctly. I know. I've seen it.

    12. Re:Gotta document that code... by skraps · · Score: 2, Interesting
      The only time comments should be in code, is when the effect of the code is different than it appears to be - different than what a reasonably skilled programmer would expect. That is the only reasonable use for comments. For reference, here is a quick list of arguments and my canned responses: I need comments because I can't understand the code otherwise. You should be writing simpler code. If the code is too hard to understand by itself, then it is your job to make it simpler. It's not the code that's complex - it is the concepts in use. A newcomer may not have the necessary background to understand. And you think "trial by fire" is the best way to get newcomers aquainted with the code?!?? Document complex concepts in... guess what... documents. Function headers allow me to easily see what parameters the function takes, and what it does, without reading deep into the code. The arguments are also handily right there at the top of the function definition, for that reason. If you need function headers to understand what the function does, then 1) pick better names, and 2) write shorter functions. My organization requires a certain amount of comments. Change your organization.

      Most importantly, realize that comments can lie, but that code can not lie. After time, comments get out of sync with the code, and instead of having zero usefulness, they start having negative usefulness.

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    13. Re:Gotta document that code... by BasilBrush · · Score: 2, Funny

      Unless you use python. People using a different indenting style to the original programmer will learn the hard way that that's not going to work.

    14. Re:Gotta document that code... by rokzy · · Score: 4, Insightful

      >People who want to indent with spaces need their heads examined.

      speak for yourself. I know my 4-space indents will be the same regardless of whatever editor and/or settings are used. and I won't get warnings about the tab character from my f90 compiler.

    15. Re:Gotta document that code... by coaxial · · Score: 2, Insightful
      Hello. I question. Look, if you need comments to explain the code flow because your method spans four screens and has six levels of conditionals in two levels of loops, all the comments in the world won't help you.

      That's not true. One line comments won't help, but a large descriptive comments will. If you can explain the code by talking about it, then you can explain the code by writing about it.

      Especially if you change the code and now the comments are wrong

      You're incompetent if you don't change the comments to match the code. You're equally incompetent if you come across incorrect comments and leave them in. You're supposed to the job, so do it.

      I have had the joy of maintaining lovingly commented code with all these huge blocks at the start showing what args get passed and what happens, and I can't understand a god damned thing about what it's doing, because the code all looks like
      (void *((ebuf->qs) > VRT_FBUF) ? etranf(&q) ...


      As Fred Brooks said, "There is no silver bullet." Clearly written code can't replace comments. Clearly written comments can't replace poorly written code.
    16. Re:Gotta document that code... by spammacus · · Score: 5, Funny

      All generalisms are wrong.

      Isn't that a paradox? :)

    17. Re:Gotta document that code... by gregmac · · Score: 4, Insightful
      Rather than just see words, I'd rather see real-life applications of these practices. For starters, here's typically how much I comment my code:
      tmp = last_update; // tmp = last update time
      last_update = SDL_GetTicks(); // Set the last update time to now
      tmp = last_update - tmp; // tmp = difference between now and last update
      fps_timer += tmp; // Increase our fps millisecond timer
      fps_counter++; // Increase our frame count


      There's also something as far as too much commenting. Don't get me wrong, I can't stand uncommented code. I learnt, like most people, the hard way -- go back to edit something I did 6 months ago, and have no idea what's happening.

      But I don't think this is useful: // tmp = last update time. You've just spelled out in english what tmp = last_update; says in code. Comments don't add anything if you can just read the code and figure it out. If anything, it's a waste of time.

      Here's my version of your same section
      // find the time since our last update
      tmp = last_update;
      last_update = SDL_GetTicks(); // now
      tmp = last_update - tmp;
      // add time and increment counter
      fps_timer += tmp;
      fps_counter++;
      This isn't really the greatest example, but I like to comment sections of code. The details can be read by looking through the code, with "hints" as needed (for example, reminding me that SDL_GetTicks() is the current time).

      Well commented blocks mean you can skim through the code, getting a quick overview of what's happening, without having to read in much detail.
      // find matching entry in hash table
      while (....
      .....
      .....
      }
      You don't have to care about the details of the look, you just know by the time you hit the } you've found what you wanted.

      Don't take this personally or anything. Your code is very readable.. there's just lots of extra comments (granted, I've seen worse) that are really just not worth putting in.

      (also, proper indenting is as, if not more, important.. of course, /. is butchering my indenting.. so please don't harass me about that because i couldn't agree with you more ;) )
      --
      Speak before you think
    18. Re:Gotta document that code... by jesup · · Score: 5, Interesting
      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; "<ecode>" doesn't work exactly like 'pre'

    19. Re:Gotta document that code... by skraps · · Score: 5, Insightful
      That comment is a good match for the code it is with. I never write comments like that unless dealing with a 3rd party interface, or something else that is a brick wall I can't refactor across, and there is something very quirky or unusual about it. The 'if' in the last snippet you quoted is very complex, and I would probably try to decompose it into a few functions and/or objects as necessary to make it clear what is happening. For example, you could start by replacing the 'if' with:
      if(message.is_complete())
      break;
      This clearly expresses the intent of the code you quoted (assuming I understood it correctly). Here, I've created a 'message' object to encapsulate some of the logic. The entire loop may be changed to look something like this:
      while(!message.is_complete())
      {
      packet_t packet=connection.get_next_packet();
      message.receive_packet(packet);
      }
      Now, the "is complete" decision making is abstracted to the "message", which seems to me the right place for that responsibility. Another thought is that the [1] should be changed. I'm guessing that you are referring to the second byte of the received packet, and using it as a flags field of some kind. If that is the case, why not go ahead and make a struct that represents the header layout, and reference the flags through a bitfield in the struct? If you do that,
      (*curr)->GetPayload()[1] & FU_E_BIT
      Becomes
      (*curr)->header->flag_end_of_message
      ...which seems clearer to me.

      You could continue along these lines, and get to a point where it would be obvious what the code does. The comment in that snippet also addressed "why", in addition to "how". I would move the "why" explanation into a document that defines the protocol.

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    20. Re:Gotta document that code... by Jeremi · · Score: 4, Informative
      x = x++; // add one to x


      is obviously not useful


      Not only is the comment not useful, it's factually incorrect... the behaviour of that line of code is undefined.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    21. Re:Gotta document that code... by ComputerSlicer23 · · Score: 3, Insightful
      The concept I remember most from "Code Complete" is comments should tell you why or what are you doing something, but it shouldn't tell you how you are doing. The how should be obvious from the code.

      Never tell me you are adding shifting the varaible by 4 bits, instead tell me, you are converting from bytes to 16 byte blocks due to a chunks size conversion because that's the size the output device expects blocks to be written in.

      Don't tell me you are swapping variables, tell me why the values should be exchanged.

      Don't tell me you searching for the max value, tell me what the max value is used for when you find it. That sort of concept.

      One easy way to do that, is to look at code and the comments. If the code and the comments could get out of sync because you changed the implementation, the comment is wrong. You documented the how not the what.

      There are cases where the how is important, especially when there are things where the "how" doesn't behave naturally. Oh, this sorts numbers, but it is intentionally sorting the ASCII values of the numbers when represented as a string. That'd be very useful to know. I'd expect a sort to work based on the binary values.

      The other rule I remember from code complete, and from "Writting Solid Code", was the concept of laying out the pseudo code that explained what you wanted to do at a high level. Then filling in between the comments with the implementation. It was a very good way to end up with documented code.

      Kirby

    22. Re:Gotta document that code... by slashdot.org · · Score: 5, Insightful
      Here's what my version would look like:
      //---
      // TODO: gracefully handle wrap-around of SDL_GetTicks()
      // not implemented yet because it only happens every 40 years
      //---
      tmp = last_update;
      last_update = SDL_GetTicks();
      tmp = last_update - tmp;
      fps_millis_timer += tmp;
      fps_counter++;
      My philosophy is that:
      1) production code is not a tutorial of the C(++) language. It's okay to assume the reader knows their stuff. A bad example:
      tmp = last_update; // tmp = last update time
      2) production code is not documentation on the APIs that it uses. APIs have their own documentation, the reader either is familiar with it, or can find documentation. A bad example:
      last_update = SDL_GetTicks(); // now
      If the API is only used in one file, then you could point at the documentation right where the header is included. If it's used on a project level, then it should be pointed to at the project documentation.
      3) comments are just as much about why you didn't do something a certain way as it is about why you did do something a certain way.
      4) the obvious; name your variables correctly. Instead of:
      fps_timer += tmp; // Increase our fps millisecond timer
      use
      fps_millis_timer += tmp;
      5) if you are implementing using a spec, somewhere in the top of the file describe the revision of the spec. Additional comments can describe the section of the spec that they relate to.
      For example:
      // Init GDT, see section 6.3.1
      virtual_machine.gdt.base = base;
      virtual_machine.gdt.limit = limit;
      6) NEVER put actual values in comments. For example:
      com1.baudrate = 9600; //set baudrate to 9600
      The code already shows the actual value, and all too often the comment doesn't get updated.
      Sometimes it's okay to list the possible values:
      out_p16_d8( base + CSR, 0x66 ); //0x61 = 1x, 0x62 = 2x, 0x66 = 4x, other val illegal
      but I only prefer that when this is the _only_ place where it is used. Otherwise you'd use enums and/or refer to the documentation section/page
      7) write top level documentation to explain what the software is actually supposed to do. It's amazing how often this is missing. Write one bloody page that describes to a programmer that doesn't know ANYTHING about the software what the hell it's supposed to do, and how it's accomplishing this. It also helps tremendously if every file has a little description in the header. And I'm not talking about what license the code is distributed under.
    23. Re:Gotta document that code... by crazyphilman · · Score: 2, Informative

      I'm stuck doing VB6 on a legacy app, right? And the previous programmer was a complete jackass. For example, in this one function I'm working on, he's just doing a very simple SQL select pulling down two values in one record, and returning true if the record exists, and false if it doesn't.

      First of all, he didn't properly handle errors, so if anything goes wrong, his object just sits there in memory (no garbage collection in VB6!). Our servers have been crapping out lately, so this was a valuable discovery for me. Second, when he fetches his data from Oracle, he inexplicably sets the lock type to "adLockPessimistic" (with a static, client-side recordset that doesn't get updated!!!) which locks the affected records until the recordset is done with them. Which I suspect means that if there's an error and the recordset doesn't get closed or set to nothing, the records will be locked until some timeout occurs. Another tip about why the server might be choking (lots of users hitting the same records, ha ha, what fun). And, on top of that, he's not cleaning up his objects, so it's not like the recordset ever releases the records in the first place. I mean, at some point they're getting released, but it's not HIS code that's doing it.

      So, I rewrote the whole thing correctly, fixing the error handling and making sure objects were cleaned out, switching to a static recordset with optimistic locking, etc, shortening and speeding up the code. I might speed it up some more by making it readonly, I dunno. Thinking about it.

      And, so I'd remember what I did and why, I added brief notes stating why I chose the lock and cursor types I did, why I used adUseClient instead of server, etc. In other words, I pointed out the nonobvious stuff that the code didn't explain.

      I'm hoping that the next programmer to come along, who might not be that good at ADO, will read what I wrote and understand why it should be done a certain way.

      I think good comments are about context, and sharing the thought process of the original programmer, and adding nonobvious info.

      Sorry I didn't have code to share, but it's at work and it's late. :(

      --
      Farewell! It's been a fine buncha years!
    24. Re:Gotta document that code... by ajs · · Score: 2, Informative
      I tend to follow these rules about documentation:
      • Document every subroutine/method/macro/functional unit
      • If you find yourself having to document a free-standing chunk of code, consider modularizing
      • Write system/functional/etc. documentation seperately (in the same file in some langauges, but NEVER IN THE CODE) to give yourself a chance to abstract the concepts that the code represents.
      • Add inline comments to free-staning code without modularizing, only when the reader's assumptions might be violated (e.g. I tend to document my use of POSIX time routines because they LOOK like Y2K bugs, but are not).
      • When documenting routines, include the meaning of parameters and the meaning of the return value (if any) as well as the general function of the routine
      • Avoid globals where possible, but document each when used
      • Keep documentation well formatted so that it does not obstruct code visually.
      Following these rules, I have never produced code which someone who knew the language I was programming in could not read and understand. When I write Perl code and use some large Schwartzian Transform, someone who does not know Perl might be confused, but I can't really stop and document every line of code for everyone who doesn't know the language. If I'm doing something particularly hairy that might not look sane to a reader who knows the language, then I comment it.

      There's code that I wrote 15 years ago that someone came to me a few years ago to ask about using in a college class, so I guess it works out ok ;-)
    25. Re:Gotta document that code... by Neurotoxic666 · · Score: 2, Informative
      Maybe he should've wrote it appropriately:
      All generalisms are wrong. // Joke
      --
      You are more than the sum of what you consume. Desire is not an occupation.
  3. Use long variable names by Joey7F · · Score: 2, Funny

    Just go ahead and use the long names, that alone will reduce documentation/commenting

    --Joey

    1. Re:Use long variable names by p3d0 · · Score: 4, Insightful
      This same point arises every frigging time someone talks about comments. As I say every time: A variable name can only tell you what the variable is, not why you chose to make it that way.

      Now with that out of the way, here's my philosophy on variable names... Every variable name should be as long as necessary to describe what the variable is. Having said that, the shorter, the better. If you have a lot of long variable names, then you probably have not found the most elegant solution to your problem.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    2. Re:Use long variable names by agm · · Score: 2, Funny

      I skip it and use "l" instead. Variable names that start with k are reserved solely for developing KDE apps.

    3. Re:Use long variable names by el-spectre · · Score: 2, Informative

      Yeah, but mathematicians have set letters (or symbols) they use to represent things (m = slope, for example). Programmers don't have that, except for i and j :)

      --
      "Faith: Belief without evidence in what is told by one who speaks without knowledge, of things without parallel." - A.B.
    4. Re:Use long variable names by natrius · · Score: 2, Insightful
      When you read
      y = mx + c
      sure, the variable names are short, but there's a hell of a lot of (implicit) commenting. The commenting has been shoved in your head since seventh grade, when Ms. Krabappel explained what they meant to you, and has been reinforced over and over since then. If there's that much commenting for the variables that you're using, then by all means, use short one letter variables. This usually isn't the case.
  4. Comments more important? by Rollie+Hawk · · Score: 5, Funny

    Has he read the ones here?

    --
    Before any liberals are tempted to mod up one of my comments, a word of warning: I'm actually making fun of you.
  5. huh, just like /. by eobanb · · Score: 4, Funny

    ...where comments are more important than articles.

    --

    Take off every sig. For great justice.

  6. Perl POD Documentation by LogicX · · Score: 2, Interesting

    How about Perl's POD Documentation? I do a lot of hacking of Matt Simerson's Mail::Toaster and Nictool projects, and I find that the Perl POD Documentation system, combined with well-named variables is easy on the eyes, and leads to it being well interpreted by an outsider.

    --
    May this post be indexed by spiders, and archived for all to see as my Internet epitaph.
  7. Comment. by stealth.c · · Score: 2, Insightful

    Always comment. Always. I'm not a career coder, but I've done enough to know that if it's a project of any noticeable size at all, and you intend to read the code later, take the extra few seconds and COMMENT THE STUPID THING. It makes life a lot easier. The only thing that probably doesn't need commenting is a simple BAT file or a shell script. Comment!

  8. Write code like someone else will maintain it by John+Seminal · · Score: 4, Interesting
    that using short, descriptive variable names 'should' be enough as long as the code is well-organized.

    This works for code I write that nobody else will ever maintain. Even then I can get tripped up, I'll have to lean back in my chair and try to remember what I was thinking when I wrote the code.

    But if you write code you're getting paid for, or code for an organization, anything but personal stuff, write good comments. Variable names might give a good idea about what data the variable holds, but it does not tell us much about how it is used.

    When I took my first programming class, the most frustrating part was the documentation. I thought it was retarded and stupid and a waste of time. But now I realize it is very important once you write something more significant than "Hello World".

    --

    Rosco: "If brains were gunpowder, Enos couldn't blow his nose."

    1. Re:Write code like someone else will maintain it by bakes · · Score: 2, Insightful

      ..and try to remember what I was thinking when I wrote the code

      People sometimes forget that you are not only documenting WHAT the code is doing, but WHY you are doing it that way. You can usually figure out the what from the code itself, but trying to figure out the why can be next to impossible.

      I wrote some code years ago to calculate (Australian) Capital Gains Tax liabilities. I knew it would be a hassle to update the code when the tax laws were inevitably reviewed and updated, so I went out of my way to put notes about EVERYTHING into the source code. Where I would normally have put in a short quip, I put in a longer descriptive comment.

      Five years later when changes had to go in, it took me an hour or two to get back up to speed with how the program worked, but without that extra documentation it would have taken far longer and I would more likely have broken it when trying to patch it.

      --
      Ho! Haha! Guard! Turn! Parry! Dodge! Spin! Ha! Thrust!
  9. Not necessarily comments... by kwoo · · Score: 3, Interesting

    In my opinion, comments are useful -- but literate programming is where it's at if you're looking for the best way to document your code.

    Knuth did a lot of work in the area -- if I remember correctly, all of the sources to TeX are written in a style understood by the "web" literate programming tool.

    There was also a good article by one of the Perl folks (Nathan Torkington? M.J. Dominus? Chromatic? I can't remember.) on POD, and how although POD wasn't literate programming, it was still useful. That article was great in that it showed a middle ground that may be more palatable to your non-LP-fanatic programmer.

    That being said, I prefer full-on LP for large projects.

    1. Re:Not necessarily comments... by chromatic · · Score: 2, Informative
  10. Something i notice by bmajik · · Score: 5, Insightful

    i do a lot of code reviews at work and nothing makes me happier than good comments.

    but just putting a bunch of blocks of comments that are like "get customer", "build record", etc are basically useless. If you use programming by intent then its more or less obvious that the code

    GetCustomerFromDatabase(foo)

    is going to do something with a database and get a customer. a comment telling me that is useless.

    what i like to do is write a few paragraphs of text at the top of a function. it explains my general approach, why im doing certain things the way i am, why im not doing other things, and why the function even exists.

    essentially the comments should be enough that anyone that knew the problem space ought to be able to read them and come up with more or less a similar implementation.

    then, in the body of the method anytime i do something that i feel isn't completely obvious, i put a 1 or 2 liner infront of, i.e. "we have to do this because zergs are sensitive"

    the end result of all of this is that code reviews can see what you were thinking at the time the code was written.. and you're documenting assumptions about the problem, the apis, your understanding of the language, etc, all right in the code. it makes finding errors pretty easy.. someone that can't even read source code can read the comments and get an idea of the correctness of your approach.

    --
    My opinions are my own, and do not necessarily represent those of my employer.
  11. Re:Documentation encourages complacency of thought by Fjornir · · Score: 3, Interesting

    "Don't get suckered in by the comments -- they can be terribly misleading. Debug only code."
    --Dave Storer

    --
    I want a new world. I think this one is broken.
  12. Nah by Anonymous Coward · · Score: 5, Funny

    Variable names should be proportional to the size of their scope within the code.

    1. Re:Nah by Anonymous+Brave+Guy · · Score: 4, Insightful

      Blockquoth the AC:

      Variable names should be proportional to the size of their scope within the code.

      That was modded (+1, Funny), but I think it was a serious comment. It wasn't a bad rule of thumb, either.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    2. Re:Nah by Fjornir · · Score: 2, Funny

      So the length of a variable name for a global var should approach infinity?

      --
      I want a new world. I think this one is broken.
    3. Re:Nah by mazarin5 · · Score: 2, Funny
      int main()
      {
      unsigned char ucGlobalVariableNamesShouldBeReallyLongEspeciallyI fTheyAreImportantAndYouNeedToKnowExactlyWhatTheyDo AndYouDontReallyFeelLikeUsingProperCommentsAndJust RetypingAReallyLongNameLikeThisIsSoMuchMoreConveni entAndGodForbidYouShouldMakeASpellingErrorLetMeTel lYouHowFrustratingThatCanBeAnywaysImRamblingBackTo ThePointWhichIsThatSuperLongButDescriptiveVariable Names = false;
      return 0;
      }
      --
      Fnord.
    4. Re:Nah by slashdot.org · · Score: 2, Funny

      That was modded (+1, Funny), but I think it was a serious comment. It wasn't a bad rule of thumb, either.

      Heh, it would have been funny if he'd said "Variable names should be inversely proportional to the size of their scope within the code."

    5. Re:Nah by slashdot.org · · Score: 2, Funny

      yeah. Nothing can cause quite the same thrill as declaring a global "int i".

  13. Joel on Software by TrueJim · · Score: 4, Interesting

    "There's a subtle reason that programmers always want to throw away the code and start over. The reason is that they think the old code is a mess. And here is the interesting observation: they are probably wrong. The reason that they think the old code is a mess is because of a cardinal, fundamental law of programming:
    It's harder to read code than to write it."

    From Joel on Software
    http://www.joelonsoftware.com/articles/fog00000000 69.html

    Always comment.

    --
    I hope that after I die the one word people use to describe me is "resurrected."
  14. What are programming languages for? by FhnuZoag · · Score: 2, Insightful

    Why on earth do we even have commenting? I mean, we went through the whole programming language concept precisely to make instructions to computers human-readable. Ideally, commenting should be obsolete - the language and its syntax should make it obvious what needs to be done.

    If it turns out that after all that, our code still isn't intelligible, then isn't this some monumental failure of C, Java, BASIC and the rest, whose whole raison d'etre is to make weird things make sense?

  15. New Techniques and Better Programmers. by X-rated+Ouroboros · · Score: 5, Insightful

    If the comments are clear, a better programmer than you can come along later and say "What the hell was this guy doing?" and then replace your lines of fumbling crap with much cleaner/clearer code.

    It's the difference between being able to see what you were trying to do vs. figuring out what you actually did.

    Call it "Intent Oriented Programming" if you want.

    --
    Simple Machines in Higher Dimensions
    1. Re:New Techniques and Better Programmers. by el-spectre · · Score: 2, Insightful

      Also, if you're doing something weird, but for a good reason, comment it so someone later doesn't "clean" your code and fuck it all up.

      --
      "Faith: Belief without evidence in what is told by one who speaks without knowledge, of things without parallel." - A.B.
  16. They are by MarkusQ · · Score: 3, Insightful

    Comments are a maintenence nightmare. They get out of sync with the code, and (especially when the code is bad to begin with) people read them instead of the code.

    That means over time the human's understanding of what the program does starts to diverge from the computer's understanding.

    This is not good.

    If something is too hard to understand the way it is written without comments, it should be rewritten. You will save time in the long run, trust me.

    Remember the old adage: Don't get suckered in by the comments--the bug is in the code.

    --MarkusQ

  17. Re:And this, my friends, is why offshore outsourci by John+Seminal · · Score: 2, Insightful
    And this, my friends, is one of the reasons why offshore outsourcing is doomed. You understand comments are important. For people in India schedule is far more important than comments. So they'll cut&paste shit all over the place and leave it uncommented. If you happen to have to work with it, your hair will turn gray pretty quickly

    I disagree. India has more engineers than the USA. And these are smart people. Some of them already know english, and others will have to learn. India is a country with too much poverty and so little oppertunity, that when a young kid is given a chance, he'll learn it all. They are lean (paid little) and hungry (willing to learn). In the USA, we expect $100 an hour to consult, one place I worked at hired an Arthur Anderson consulting team and the lead got over $300 an hour. I bet he would be *insulted* to have to work for $20 an hour. Are you going to tell me that the guy in India won't take that wage?

    If it means people in India will have to learn english, they will learn english the same way they get their engineering degrees. They will study their asses off like their lives depend on it.

    If people in the USA have half a chance, now is the time to take advantage of it and produce a better product than they do in India. Leverege every advantage we have, because the competition is getting better.

    We could say how the Bush administration is screwing us, and to a large extent they are. We never should have let factories leave the USA to mexico. We never should have let outsourcing happen. I hope future presidents start raising the tariff, and force American companies back in the USA. But maybe we need to get a little more lean. It is hard for the avarage employee to give a fuck when you see the CEO get a bonus when he lays people off, or scum like enron managment steal the pensions of employees, but what other option do we have? Change the tax code to tax the wealthiest at a higher rate and pump that money back to the poor? Maybe raise the luxery tax rate? Increase the estate tax? Break monopolies?

    --

    Rosco: "If brains were gunpowder, Enos couldn't blow his nose."

  18. Re:development process by frikazoyd · · Score: 2, Interesting

    You are absolutely right. Some of the better design processes (to me) have involved turning the initial documentation into skeleton code, then writing comments around all the functions and classes that describe exactly what the program is supposed to do. Not only does it provide for excellent commenting and understandable code, it is immensely helpful in the writing of these functions.

    Having a function named "getKey(row r)" with a comment saying /*retrieves the key 'SS#' from row r*/ may seem like overkill at first, but people who go over my work later don't even have to read the function for the code (unless they suspect the function is the source of a bug). They know what it is supposed to do, and a written out comment is generally clearer than a pre:post: with the bare minimum of description that some people prefer.

  19. Uhh... by PrimeWaveZ · · Score: 5, Funny

    UsngShrtCmtsIsOftNotEnghAsOneMyNdToReWrtShtInTheFt r.

  20. The problem isn't lack of comments by jjoyce · · Score: 4, Insightful

    The problem is usually functions that are too long and are not orthogonal. Write short, orthogonal functions and you'll see your need for heavy commenting go away along with the need for long variable names.

    1. Re:The problem isn't lack of comments by beavis88 · · Score: 2, Insightful

      Here you go:

      http://en.wikipedia.org/wiki/Orthogonal_functions/

      I'll reply again in a couple weeks after I've figured out if my functions are orthogonal or not.

    2. Re:The problem isn't lack of comments by RadioheadKid · · Score: 2, Insightful
      Chapter 4: Functions

      Functions should be short and sweet, and do just one thing. They should fit on one or two screenfuls of text (the ISO/ANSI screen size is 80×24, as we all know), and do one thing and do that well.

      The maximum length of a function is inversely proportional to the complexity and indentation level of that function. So, if you have a conceptually simple function that is just one long (but simple) case-statement, where you have to do lots of small things for a lot of different cases, it's ok to have a longer function.

      However, if you have a complex function, and you suspect that a less-than-gifted first-year high-school student might not even understand what the function is all about, you should adhere to the maximum limits all the more closely. Use helper functions with descriptive names (you can ask the compiler to in-line them if you think it's performance-critical, and it will probably do a better job of it that you would have done).

      Another measure of the function is the number of local variables. They shouldn't exceed 5-10, or you're doing something wrong. Re-think the function, and split it into smaller pieces. A human brain can generally easily keep track of about 7 different things, anything more and it gets confused. You know you're brilliant, but maybe you'd like to understand what you did 2 weeks from now. --from Linux Kernel Coding Style


      I find these rules very helpful. Secondly, many times your code evolves and changes, and it's important that you continuously re-examine your functions too see if there are newly created logical dividing points.
      --
      "Karma can only be portioned out by the cosmos." -Homer Simpson
    3. Re:The problem isn't lack of comments by emurphy42 · · Score: 3, Informative

      Er, that's a nonexistent article. Fortunately, a Wikipedia search on "orthogonal" did lead to another article that does exist.

    4. Re:The problem isn't lack of comments by Jeremi · · Score: 3, Interesting
      Functions should be short and sweet, and do just one thing.


      I'd tweak this rule a bit -- it's not as important that the function body be short and sweet as it is that function's header-declaration comment be short and sweet. That is to say, what the function does should be easily describable in one or two simple sentences. That is because most people won't need to look at the function body (looking at the header file should suffice), but they will need to call the function properly from their code (or at least understand why and how it is used in other code).


      Or to put it another way: complexity in the implementation of your function, while undesirable, can at least be "hidden" from the rest of the code universe and safely ignored (as long as your function works as documented in the header). Complexity in your function's API, on the otherhand, is much worse, because it will lead to complexity, confusion, frustration, and bugs in all the other code that uses it. Not to mention that you can always rewrite your function's implementation later if you feel the need to, but changing the interface can be much harder (or even impossible) because of all the other code that has come to depend on its previous behaviour.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    5. Re:The problem isn't lack of comments by adamfranco · · Score: 2, Insightful
      The problem is usually functions that are too long and are not orthogonal. Write short, orthogonal functions and you'll see your need for heavy commenting go away along with the need for long variable names.

      Choice of language has a lot to do with the readability and lack of, or need for heavy commenting.

      Using java, PHP, Perl, etc, I find that I have a hard time writing methods that are much less than 25 lines long just due to the syntax required. PHP has the additional annoyance of not allowing method returns to be used in-line, requiring many temporary vars.

      Something like the following in, say Java:
      public Int sumResults (Int id, String managerName) {
      Int sum = 0;
      results = Managers.getManager(managerName).getStorageMethod( ).getResultsById(id);
      for (Int r : results)
      sum = sum + r;
      }
      Becomes, in PHP:
      function sumResults ($id, $managerName) {
      $sum = 0;
      $storageManager =& Managers::getManager($managerName);
      $storageMethod =& $storageManager->getStorageMethod();
      $result =& $storageMethod->getResultsById($id);
      foreach ($results as $r)
      $sum = $sum + $r;
      return $sum
      }
      Contrast both of these with an equivalent in Smalltalk:
      sumResultsFromManagerNamed: aString forId: anInteger
      |results|
      results := (Managers managerNamed: aString) storageMethod resultsById: anInteger.
      ^ results inject: 0 into: [:each :sum | sum + each]
      Granted, this is just a dumb example, but in practice I've found it vastly easier to write understandable, orthogonal methods in Smalltalk than in any other language I have tried. Combined with a good following of naming guidelines (that are followed pretty strictly in Smalltalk libraries) and its pretty easy to avoid spaghetti code.

      Oh well. time for bed...
      --
      "When ideology and theology couple, their offspring are not always bad but they are always blind." -- Bill Moyers
    6. Re:The problem isn't lack of comments by psetzer · · Score: 2, Insightful

      The thing I found that made making orthogonal functions easier was to take a page from Lisp's playbook. No function should have any side effects other than what it absolutely must, and if it does, that should be obvious from the function name, like closePrintStream(). If you find yourself unable to name the function from its side-effect, there's likely some problem hidden within the design. That means that each function should have at most one side effect. Furthermore, label all functions that call functions that have a side effect, even if it seems trivial. This extends to methods of objects, of course, and try to avoid side effects traveling over object boundaries, and for the love of God, don't have two different objects trying to handle the same responsibility at the same time! If object foo opens a file to read, then object bar had better not be able to close it, or even read from it without opening that file itself (after foo is finished, of course). It's better to do the right thing slowly than the wrong thing fast.

      --
      "Anyone who attempts to generate random numbers by deterministic means is living in a state of sin." -- John von Neumann
  21. Raskin by kebes · · Score: 5, Informative

    JEF RASKIN, professor of computer science at the University of Chicago, is best known for his book, The Humane Interface (Addison-Wesley, 2000), and for having created the Macintosh project at Apple. He holds many interface patents, consults for companies around the world, and is often called upon as a speaker at conferences, seminars, and universities. His current project, The Humane Environment (http://humane.sourceforge.net/home/index.html), is attracting interest in both the computer science and business worlds.

    For those who don't know (which apparently includes whoever is in charge of the linked article), Jef Raskin passed away this february. You can view the official press release, or read more about his contributions to computer science. I don't know when the article was written, but it seems it should mention that Raskin has passed away. In any case, his advice about commenting is good, just as his advice on user-interface design has always been lucid and helpful.

  22. Re:No such thing as too many comments... by Desult · · Score: 2, Insightful

    You need that comment?

    if (kbd_input_rcvd)
    {
    process_input();
    }

    is not clear?

    I think properly modularizing your code (breaking process_input() into its own function), and properly documenting the modules (defining good documentation of input, output, exception conditions, return values, side-effects) is more effective than writing verbose comments (like the one you've noted) in poorly segmented code.

    This whole discussion is a bit short sighted. The better and clearer your code is, the fewer comments will be necessary. The more useful comments you add, the less time will be necessary parsing and understanding clear code. The better your design overall is, the less code reading overall will be required, because you'll have documentation outside of your code that explains how the system works, and where you need to go make changes. Saying one is more important than another is silly.

    --
    -Greg
  23. Indeed by screwballicus · · Score: 5, Funny
    I was recently reading through some code I wrote ages ago and hadn't looked at in years, and wondering...dear god, what's this confused mess trying to do?

    Imagine my relief when I came upon a helpful comment:

    What the hell was I thinking when I wrote this?

    All it took was one comment to put my mind to rest: no, it's not just me being stupid in the present. This code seemed this terrible back then, too.

    Comments save the day once again.
  24. It is not math, it is not universally readable by John+Seminal · · Score: 2, Informative
    Why on earth do we even have commenting? I mean, we went through the whole programming language concept precisely to make instructions to computers human-readable. Ideally, commenting should be obsolete - the language and its syntax should make it obvious what needs to be done.

    If it turns out that after all that, our code still isn't intelligible, then isn't this some monumental failure of C, Java, BASIC and the rest, whose whole raison d'etre is to make weird things make sense?

    This is not algebra in high school where you lose points for not showing your work. This is the real world where an application might have 100's of lines of codes, maybe 1000's. It might be a bunch of classes in java working together. And then there is the logic, the work flow.

    Plus, many companies use peer review for raises and advancement. If your peers have a hard time understanding your code, it will hurt you later.

    Most people today don't work 30 years for one company. That means someone else will get stuck with your code.

    Now either you will give that person months to go through all the code, to try and figure out how it works, or you will have code with comments that will help him hit the ground running.

    --

    Rosco: "If brains were gunpowder, Enos couldn't blow his nose."

  25. Comments Should Reflect Intent by Bob9113 · · Score: 5, Informative
    I found the following in some production code, which quickly and concisely demonstrates why many comments are highly questionable:
    /** Always returns true. */
    public boolean isMagilla() {
    return false;
    }
    That's the core problem with many comments, but it can be avoided. Comments are good when they state the intent or business case for a block of code, acting as a guide to the meaning of a block for subsequent developers. They are bad when they profess to know the actual outcome or implementation of a block; only the code itself can accurately reflect the state of the code.

    The above would be far more useful like this:
    /** Tells whether this instance meets the magilla criteria. */
    public boolean isMagilla() {
    return false; // currently, no MyClass meets the magilla criteria.
    }
    Now the intent of the method is clear, and anyone coming along who wonders why it's hard coded will know under what circumstances they should change it to a formula (namely, if MyClass becomes capable of meeting the Magilla criteria).

    Comments can be good, but they should always be a guidepost to the intent of a block of code, and not attempt to explain how the code achieves that goal.
  26. Re:development process by BreadMan · · Score: 2, Insightful

    I found that writing the comments *first* my methods/functions is the way to go. This helps me organize my thoughts and makes finding where I should be refactoring much easier. After writing the comments, I fill in the code. By doing so, my comments focus more on the concepts and less on just restating what the code does.

  27. Comment interfaces, not implementations by bunratty · · Score: 4, Interesting
    My basic rule of thumb about comments is to comment the interface. In C/C++ this would mean writing the comments at the beginning of all function declarations in .h files instead of .c files, and in Java would mean writing Javadoc comments at the beginning of all methods. The idea is that if you know what a function/method does, you should be able to understand how it does it. The inside of functions/methods should have minimal comments, usually just a one-line comment for each major section explaining what that section does. Sometimes how the function/method works needs to be commented, as in:
    void sort(int arr[]); // sort arr, ascending
    ...
    // Uses quicksort
    void sort(int arr[]) { ... }

    Of course, there are always exceptions. When I was writing low-level code that manipulated hardware registers, I wrote a multi-line comment before each line of bit-fiddling code, complete with what the code did and a cross-reference into the hardware manual. Something like:

    // Set the serial port to big-endian mode
    // See SlurpSCC manual page 3-5
    bitset(slurp->serial, bit(13));
    --
    What a fool believes, he sees, no wise man has the power to reason away.
  28. Comments Should Come From Good Design by GaryPatterson · · Score: 2, Interesting

    Surely commenting comes as a result of a good design practice.

    You start with a functional spec, from which a design spec is derived.

    The design spec is then broken into functional units, which are each divided further and further until the code itself seems obvious.

    The final design is given a walk-through to verify with peers.

    This design could pretty much be converted into a set of comments, each of which describes how the code should function.

    The problem comes when coders just give it a go, write stuff on the fly and don't bother with design. It could be brilliant code, but most often it's just plugging local holes without reference to the overall design.

    Comments are generally a good coding practice, and should fall naturally out of a good design phase.

  29. Debug code not comments by iplayfast · · Score: 4, Insightful

    I find that for simple code that requires little thought, little in the way of comments is required. Sometimes comments just get in the way as the code progresses over time, and the comments don't. It's better to code with long descriptive variable names, and structures then depend on comments.

    For example which would you rather read.

    #define AgentNameLen 41
    #define CustomerNameLen 51

    struct CustomerID
    {
    int CustomerID;
    char AgentName[AgentNameLen];
    char CustomerName[CustomerNameLen];
    };

    or

    struct CoID //Customer ID structure
    {
    int ID; // ID number for the customer
    char AName[41]; // Agent Name
    char CName[51]; // Customer Name
    };

    To me the first is much more clear, and throughout the code will be obvious as to it's use. The second is mildly clear, but will degrade as new things get added to the structure.
    The first also allows things like
    for(int i=0;iAgentNameLen;i++)
    which makes it very clear that you are iterating throught the agent name.

    Algorithm's should be documented, as much as possible, at the top of the function, and any function that takes more then a screen should be looked at to see if it can be broken up into smaller functions.

    (Almost) Always code towards maintainability, never speed. Usually it pays off within the year.

    So to sum up. In order of importance:
    80% code clearly with an eye towards maintainablity
    20% comment

    1. Re:Debug code not comments by lifeblender · · Score: 2, Informative

      I have one major suggested change for you: Comment your thoughts. If you spend half a day or more figuring out how to solve a problem, then your solution AND the thought process that let you get there belong as comments. This can be several pages. If you do this, you will never repeat mental work, and anyone (including you) reading your code will have one hell of a guide. Also, when there is a ton of code, comments are a guide. You did a lot of work just deciding on the organization of the code, so document that with comments too.

      Basically, I write down anything that I don't want to have to figure out again. It saves me so much time with large projects. You have to keep this level of agressiveness up to keep the comments up to date, but if you get used to putting your thought processes on paper, then you'll get used to editting them on paper, too.

      --
      Playing pornographics games during the day is evil! Play at night!
  30. Re:No such thing as too many comments... by BarneyRabble · · Score: 3, Interesting

    Don't laugh. As an old school COBOL programmer in my youth, documentation was everything. Now that other languages have come along, you really need to document what you do, you can't just be lazy and not be willing to explain what your code does, This is what is happening to every program tha I see (C++. and M). Poor documentation, poorly written code, and very little commentary on what the particular function does.

    My spin on this, your are a very poor communicator to your co-workers if you can not put a few simple words to a function in your program.

  31. The What, the Why, and the How by wowbagger · · Score: 2, Insightful

    There are three things the poor maintainance programmer who has to maintain your code needs to know: The What, the Why, and the How.

    The What: What is this code trying to do. This is where your design documents come in, as they tell what the overall goal of the program is.

    The Why: Why are you doing what you are doing? Why are you writing to this hardware register twice? Why do you divide this value by 1800 here? This is where comments are needed - to explain that the hardware sometimes doesn't take the value on the read, or that the nominal deviation of this signal is 1800 Hz.

    The How: How are you getting the work done. This is where well written code with well chosen variable names comes in.

  32. The only thing worse is old comments by subStance · · Score: 2, Insightful

    Out of date comments are far far worse than none, and this happens with absolute certainty.

    People will usually update variable names, but they won't update comments, especially when the IDE makes comments a different colour - your eyes don't even see them after a while.

    You think spaghetti code is bad with no comments - try it with misleading comments.

    --
    Servlet v2.4 container in a single 161KB jar file ? Try Winstone
  33. Quality not quantity by MagikSlinger · · Score: 5, Interesting

    Having RTFA, I can see what he's trying to get at, but as someone who has (unfortunately) found himself spending most of my 10 year career in programming cleaning up other people's poop. At first I thought it was because I must have done something wrong that I kept ending up being assigned this work, but as I came to realise, it was because I make the code better than I found it and I have a knack for fixing stuff other people give up on. I also had silly managers who assign work to the people least qualified to do it.

    At any rate, some observations:

    1. 20 lines of comments "documenting" your code before you write it (or even after you write it) is far less useful than writing the code COHERENTLY and CORRECTLY in the first place.

    Last month, I had a 1200 (yes 1,200) line method with huge blocks of documentation before big pieces of code. I still can't quite tell you what it thought it was doing. The code was a for loop wrapping around code to handle 3 different and mutually exclusive situations. Instead of identifying which of the 3 situations it was and creating a method for each situation, the person just stuffed it all in with lots of comments documenting everything the article's author said. The code was still unmaintainable.

    2. Comments are useless unless they are kept up to date

    Part of the reason that code was so difficult to figure out was because most of those big verbose documentation comments referred to a completely different implementation. After the programmer had written the first case, she encountered some other bad cases and eventually had to completely change a block of code embedded in this 1200 line for-loop. The code was now correct, but the comments no longer had anything to do with that block of code.

    3. Don't be clever when you can be clear

    I have made a solemn vow to hunt down and hurt anyone who puts "clever" code in my project. I am so sick of trying to figure out what some obfuscated piece of code in C, C++ or even SmallTalk is doing. And find out it was just a "clever" way of doing something pretty straight forward like iterating over a list. There was no speed gain from the clever trick, and the code wasn't even a bottleneck to begin with. *sigh*

    4. If you don't know how to solve the problem, write some experiment code in a separate app to figure it out. Then take the time to do the "right" thing in the production code.

    3 days from final for a video game. The CD streaming library for the Sony Playstation was making this strange "hic-up" sound at rare moments. By this time, the original author of this code has long since gone to another company. So I plunge into the code and found that the original programmer didn't know how to write streaming code so he created this hack of a hack of a hack of a test (ad nauseum). The code was programmed by accident, not design. No amount of comment before coding could help this. If the author had dumped the code, wrote documentation describing everything he learned then wrote the code, things would have been a lot better.

    5. Unrelated to comments, but use variable names that make sense. Don't name them arbitrarily or to amuse yourself!

    That CD sound streamer code I mentioned above used quirky names for variables. Can you tell what "little_ninja" is supposed to be just from the name? When I confronted the coder about this quirk of his (in another library he wrote), he got all huffy and didn't understand why people didn't appreciate his little puzzles or his sense of humor. It galls me he still earns a paycheck in the industry.

    --
    The bitter lessons of a veteran coder: http://bitterprogrammer.blogspot.com
    1. Re:Quality not quantity by professorfalcon · · Score: 2, Funny

      variables that do something relatively mindless I name 'Gilligan'

      Do particulary sexy variables get named Ginger or Mary Ann?

  34. What do you guys think of the following code? by francisew · · Score: 4, Insightful

    I kid you not, this is real code my supervisor writes.

    if(preproct(7) >=thres), for j=size(at,2),at(:,j)=at(:,j)-maa;,for i=1:size(at,1),at(i,j)=(at(i,j))/(stda(i)+.0000000 01);,end,end,end

    Note that this is matlab code, where commas are both an end-of-statement indicator (it's also possible to use just a semicolon), and an array index separator. The nice thing about this code, is that I can at least guess where most of the variable names come from. Oh, and there was *no* line break in the original code. Hooray for the avoidance of those wasteful '/n' characters?!?!

    To answer the original poster: yes, comments are of vital importance.

    Then again, if a program is structured right, things can be organized into sections, each of which is then commented, as opposed to a bunch of seemingly random lines with comments spaced throughout. Sometimes the layout of code, in conjunction with good variable names, is the best possible method of commenting it. The one thing comments are good for is to assure that someone not familiar with the particular language being used, will still understand the purpose of the code.

    1. Re:What do you guys think of the following code? by natrius · · Score: 5, Funny

      Please don't post my code on Slashdot.

      Come see me in my office.

      - Your Supervisor

  35. Speak, Memory! by guet · · Score: 2, Interesting

    program.files.each do | class |

    class.methods.sort.each do | method |

    5.times { method.refactor! unless method.elegant? }

    end

    if problem_domain > current_language
    choices << comp.lang.each
    current_language = choices.best
    project.restart
    evangelise(current_language)
    end

    end

    comments << intentions.remove(implimentation_details)
    puts comments

    def refactor!
    method.split! unless method.size < Too_Big
    method.rename! unless method.name.clear?
    end

    def evangelise(lang)
    slashdot.comment.post
    puts "#{lang} is the only real language"
    end

    goto (1.0/0.0) and $beyond

    http://www.rubygarden.org/ruby?MoviesTheRubyWay

  36. Hmmm... by ta+bu+shi+da+yu · · Score: 2, Insightful

    Well, that assumes that you have a nice, clear set of steps (like the example above). However, if you have a series of very complicated, non-intuitive steps that MUST be done, then commenting is pretty much essential.

    --
    XML is like violence. If it doesn't solve the problem, use more.
  37. You're right, but Raskin is wrong by Univac_1004 · · Score: 3, Informative
    Raskin (who did not write code himself, but was more of a essayist) was a devote of "Literate Programming", first promulgated by Knuth: http://www.literateprogramming.com/knuthweb.pdf/

    In "Literate Programming" the comments are all important and the code itself is trivialized. The code, as Jef told me, is like "raisons in the muffin of the comments." There are paragraphs of verbiage which might go on about the history of the project, why certain features were discarded, etc., etc, and might not even explain what the following line or two of code was concerned with.

    It's really very difficult to deal with code that has been written in this style ("literatized?" ) since the actual structure of the program is severly obscured. It serves as an example of how overdoing a good thing is usually a bad thing.

    Jef was a nice guy, and I recommend his book, "The Humane Interface" for its many interesting ideas. His attempt to put them into practice in the Archy project http://rchi.raskincenter.org/aboutrchi/index.php/, was not completed before his death. Even for that, Archy is very close to his vision.

    But since Jef was in many ways an extremist, one can demonstrate in Archy his pushing of his concepts to the limit resulted in the end fully maching his goals. Somewhat like "Literate Programming", in fact.

  38. You need both by Bilx777 · · Score: 2, Insightful

    I think that BOTH the comments and the code need to be readable. I've seen code with lots of great descriptive comments, but when you look at the actual code you can't tell if it does what the comments say it's supposed to do. The same holds true for the reverse. I've see code that's well structed, readable, descriptive variable names, etc. But without some comments about how all the pieces fit together the code can still be confusing.

  39. There will always be losers by menace3society · · Score: 4, Interesting
    There will always be loser "programmers" who write code without comments, or write code without useful comments, or modify usefully-commented code without modifying the comments. Everyone I've seen who's ever put up an example of how code is self-documenting and that comments are just extra text saying the same thing have fallen into the second category. Of course things like "prints a message" or "check to see if i==0" are stupid comments. But that's just a straw man if you want to say that all comments are useless (I dare these people to read uncommented assembly of more than about 40 lines, and tell me the code documents itself).

    The true useful skill lies in reading sloppy and/or wizardly code. Some people think that they have job security if they write impenetrable code, but then they can just be fired and all their code rewritten. If you can read others' "unmaintainable" code, you enable your employer to save money by not having to rewrite everything the guy they just fired wrote. So they'll want to keep you around as they fire/downsize everyone else. I It doesn't really matter what kind of code you write, since you can read whatever. advise everyone to start reading up on the Obfuscated C Contest, and practice figuring out what evertyhing does. Then you can handle any kind of code thrown at you, and the code you actually write becomes of secondary importance.

  40. Good comments are good by localman · · Score: 2, Informative
    using short, descriptive variable names 'should' be enough as long as the code is well-organized.

    Definitely not. No matter how clear your code is, it only gives you an idea of what is going on the small scale. You often need comments to describe your big-picture motivation. But the comments have to be good too.

    Here's a classic bad comment:
    // add one to the total
    ++total;
    That's useless. But a comment can help:
    // the total doesn't count the root node of the tree
    // (since there's no actual entry in the DB for node "0"),
    // so we just add that in here...
    ++total;
    No matter how clear you write the code you're not going to get that much understanding without a comment.

    It's just a simple example off the top of my head, but that's how I use comments. The code clarity is all that's needed to tell what you are doing, but comments can tell you why you are doing it. You need both for truly maintainable code.

    Cheers.
  41. Tests are more important than comments. by refactored · · Score: 2, Insightful
    Haven't you ever heard the maxim, "Debug code, not comments". It reflects the fundamental problem with comments.

    The problem with comments is there is no constraint to keep them...

    • Current
    • Correct
    • Meaningful
    • Unambiguous.

    Code Reviews help, but not enough.

    There is a better way. It is called Test Driven Development. Tests are the least ambiguous, most correct and current commentary on the code. They are also always at the correct (higher) semantic level than just paraphrasing the code.

    Given a choice of reading comments or reading well structured tests, I will read tests any day. I at least know if they run, that they are true.

    Google knows.

    1. Re:Tests are more important than comments. by rossifer · · Score: 2, Insightful

      Until you end up trying to fix a bug five or ten years down the line.

      Uhhh, no. That's when the massive body of unit tests saves your bacon. You had to make a change that caused the tests to start failing. Once the tests are all running again, your system has at least the level of quality it had before you made your changes.

      You and your team do have to follow a rule of not deleting possibly relevant tests. Ever.

      Those tests don't do you jack if all they do is tell you there's a bug.

      Sounds like you haven't written many unit/functional tests. The way it works is: you write tests for small pieces (A, B, and C) and then you write the tests for the part of the system that uses those small pieces (ABC).

      If the test for B and the test for ABC are failing, pray tell... where's the problem?

      What's worse than commented code without tests? Gaggles of tests and not a comment in sight!

      This is just trolling.

      Regards,
      Ross

  42. I learned the hard way by amigabill · · Score: 4, Interesting

    My learning experience about commenting code was a difficult one. Like many, while in college I wrote the code and then went back to comment it so the profs were happy.

    Then I did a co-op with an automated storage/retreival systems company in their software department. One of the processes involved in a communications system needed some work. The code was licensed from another company in another country. There was no documentation for this communications system. There was very little commenting in the code. Luckily it wasn't in a foreign language. Unluckily it was wrong, apparently the structure of this program was similar to that of another, which was mostly gutted and rewritten, but a few old-program comments survived to be the ONLY comments in the new program.

    Sure, the sources could be reverse engineered to provide the documentation required. I did it. It took a few weeks.

    After that, I didn't leave comments for last anymore. It's been a good thing. I now work for a semiconductor design company and often write perl scripts or skill-language scripts to automate tedious tasks. I think I'm abou thte only one in the office that comments such scripts in any way. It's nice to read what stuff does when I have to revisit code many months or years later. I hate having to revisit someone else's code because it's nearly guaranteed to be completely barren of anything human-readable.

    Listen up kids! Commenting is GOOD! Your professors aren't just being jerks. Learn the easy way and hopefully save yourself a great deal of trouble with your own code. Other people's code will always suck, but your own shouldn't have to.

  43. semicolons in column 80 by morcheeba · · Score: 4, Funny

    I had a co-worker who needed a little help with his program. It was C code, but all the semicolons were in column 80, arranged in a nice column. Yikes. He casually said "what, you've never seen that?". Turns out that part of his problem was that he was using float to represent a byte position in an extremely large file. He knew enough that UINT32 wouldn't do it, but ...

    1. Re:semicolons in column 80 by SComps · · Score: 2, Funny

      I popped my coding cherry on RPG II. My momma was right, I later regretted not waiting.

  44. I remember a technique... by aduzik · · Score: 2, Interesting

    whose name escapes me at the moment. But the idea is that you write comments that are like "psuedo-code" but much more English-like than ordinary psuedo-code. Then you refine the comments down further and further until you replace the lowest-level comments with individual statements, and the higher-level comments stay in as documentation. I remember trying this once and, while overkill for the simple project I was doing, I wrote some damn fine (and readable!) code that way.

    --
    If it's not one thing it's your mother.
  45. i know how it feels by eLamer · · Score: 2, Interesting

    as a full-time student who worked part time during summmers coding a php/mysql/flash based website... i know exactly how important comments can be. last summer, i'd have to go back to code i wrote the year before in order to update it or something along those lines, and i'd stare at it for hours thinking... "wtf is the point of this? i know it has some point, but i can't put my finger on it!" since then, although i have done very little as i was replaced by an immigrant from india... (grrr).. i have pledged to make decent comments in my code that detail what in god's name is going on.

  46. Top Ten Code Comment Do's List by Anonymous Coward · · Score: 5, Insightful

    1. Comment each function
    - Function name
    - what it does
    - parameters
    parameter name - what is is for and any restrictions on it (i.e., must not be null)
    - return value (all possible return values)

    2. Add comments to each file you modify so that over time, the file becomes better documented

    3. Add ASSERT() like comments and ASSERT() or equivalent to your code

    4. Use dividing comments like a line of dashes to seperate blocks of code

    5. Put in a '?' comment for code that you do not understand (good for function headers)

    6. Avoid stupid naming schemes for your local variables since that makes it harder to comment

    7. Review your code for both logic and comment completeness after you code it before committing it to version control

    8. Tag your bug fixes, code enhancements with a comment followed by a dash, date, and your initials. This is essential for large projects or for anything you will be working on for more than 6 months.

    9. Format your comments so that multiple line comments line up on the left hand side (increases readability)

    10. Don't count on java doc or equivalent as being good enough code documentation.

    1. Re:Top Ten Code Comment Do's List by bytesmythe · · Score: 4, Funny
      1. Comment each function
      - Function name
      - what it does
      - parameters
      parameter name - what is is for and any restrictions on it (i.e., must not be null)
      - return value (all possible return values)

      /*
      * Function: p-inc
      * Purpose: adds one to a positive integer
      * Input: x, the integer to be incremented.
      * Possible return values: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752,

      --
      bytesmythe
      Hypocrisy is the resin that holds the plywood of society together.
      -- Scott Meyer
    2. Re:Top Ten Code Comment Do's List by zerouk99 · · Score: 2, Insightful

      You could just say:
      * Possible return values: [2 - 4999]

      hehehe..

    3. Re:Top Ten Code Comment Do's List by dooglio · · Score: 5, Interesting

      1. Comment each function
      - Function name
      - what it does
      - parameters
      parameter name - what is is for and any restrictions on it (i.e., must not be null)
      - return value (all possible return values)

      ****

      I really hate having parameters documented in a comment block above the function declaration, because it seldom gets updated when the function signature itself is changed.

      I worked with a guy who used to format his functions like this:

      void my_func( // My function does foo
      int arg1, // arg1 documentation
      char * arg2, // arg2 documentation
      ...
      )
      {
      // Function guts go here
      }

      The nice thing about this method, although the "look" of a function is broken up, is that when you add or change parameters, the programmer is a lot more likely to change the documentation as well.

      When you're under the gun to get the code out, the less the developer has to do to change the docs, the more likely it is they will be changed.

    4. Re:Top Ten Code Comment Do's List by Nurgled · · Score: 2, Interesting

      I think you really mean:

      if (! (potion_a && potion_b))

      ...or...

      if (! potion_a || ! potion_b)

      As you wrote it, the combination of potion_a and potion_c would have been valid, because ! potion_a would have returned false. Of course, there's also the fun perl construct:

      wrong_potion() unless potion_a && potion_b;

      (If you don't like perl's postfix if shorthand, feel free to flip that back round "the right way" and add the braces.) (The word "potion" is one of those strange words that just always looks like it's spelled wrong. Maybe my brain is trying to read it as "option"! :))

    5. Re:Top Ten Code Comment Do's List by HomeworkJunkie · · Score: 5, Informative

      We comment all functions and classes using the Doxygen format. This means that the comments can be used to generate HTML, PDF or man pages for the functions and classes. It will also generate call trees if required. Very useful.

      --
      "Why take life seriously, you're not coming out of it alive anyway."
    6. Re:Top Ten Code Comment Do's List by Wavicle · · Score: 5, Funny
      * Oh man... I'm so tired of typing these numbers!

      You should have written a function to generate the list of numbers for you:

      /*
      * Function: num_list
      * Purpose: Returns a list of positive integers greater than one
      * Input: x, the largest positive integer in the list.
      * Possible return values: "2", "2, 3", "2, 3, 4", "2, 3, 4, 5", "2, 3, 4, 5, 6", "2, 3, 4, 5, 7", "2, 3, 4, 5, 6, 7, 8", "2, 3, 4, 5, 6, 7, 8, 9", "2, 3, 4, 5, 6, 7, 8, 9, 10", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20",

      * Hmmm, I think I need a new function to generate the comment for this function...
      */
      --
      Education is a better safeguard of liberty than a standing army.
      Edward Everett (1794 - 1865)
    7. Re:Top Ten Code Comment Do's List by zsombor · · Score: 2, Insightful
      • 1. Comment each function
      • - Function name
      • - what it does
      • - parameters
      • parameter name - what is is for and any restrictions on it (i.e., must not be null)
      • - return value (all possible return values)

      Give proper name to function and parameters so that all this becomes evident. assert() paramter precodintions at begining so restrictions will be self documented. Make sure that function has simple semantics so return value is also evident, on rare cases when you cant do this add a comment.

      2. Add comments to each file you modify so that over time, the file becomes better documented.

      Refactor each file when you modify and found them not obvious: to make them obvious. Commenting will not fix this, you are just introducing pieces of documnetations that can/will get ouit of sync.

      4. Use dividing comments like a line of dashes to seperate blocks of code

      Separate them in different functions, that you can write tests agains individualy.

      8. Tag your bug fixes, code enhancements with a comment followed by a dash, date, and your initials. This is essential for large projects or for anything you will be working on for more than 6 months.

      Use facilities provided by your source control management tool. cvs/svn/clearcase/(...) has annotate, blame, praise fuctions: use them instead and you will be able read them even after 6 years.

      Format your comments so that multiple line comments line up on the left hand side (increases readability)

      Write them on top of commented item, this way they will not go off screen, you be able to print for them more without much fuss.

      Don't count on java doc or equivalent as being good enough code documentation.

      Extend when you find the need for it.

    8. Re:Top Ten Code Comment Do's List by wagemonkey · · Score: 4, Insightful
      The nature of the language should affect the number and style of comments.
      I'm working with a 4GL, and the stupid comments are driving me more insane, especially the GPs no8 - tagging. I HATE tagging with a vengeance - that's what version control is for. Even worse is the unbelievably moronic practice of commenting out the old code and putting the changed line below it. We get one line of code replaced by 3 lines of comment and a liine of code - the comments are two lines of tags marking the start and end of the changed block and the old line of code - which is often only 1 character different from the new line. I WANT TO HIT THE WHOEVER STARTED THIS - REPEATEDLY.
      For example I have been working on a 900 line program where 400 lines are 'comments' - sometimes you only see 1 line of code per page. Now imagine the effect upon search tools - you want to use find+grep to look for code to change, and 95% of the hits are 'comments'. It's got to the stage where I have written a program to strip all the comemnts for our code and save the result. Don't get me wrong I like real comments - ones that tell me something useful like why the code was written, or any gotchas - but when the signal to noise ratio is this low I won't even worry about losinginformation, the performance hit of all this garbage is too much.

      Please, don't comment for the sake of it, comment only when you have something useful to tell the next coder to read the program - but do write these informative comments.

    9. Re:Top Ten Code Comment Do's List by zsombor · · Score: 2, Insightful
      Look at it this way - if you're in a fly-by-wire plane and the computer system reports an error, do you: (a) want to try and continue anyway or (b) shut down all the computers and engines :)

      assert() is only used during development. By the time it will be embedded in a released fly-by-wire system it was already tested extensively. If not than that is your real problem! Whole point of using asserts is to fail fast during development, so that errors become painfully visible, with a clear message: FIX ME NOW!

    10. Re:Top Ten Code Comment Do's List by CastrTroy · · Score: 3, Insightful

      This is what code versioning does. And it does it a lot nicer then you could ever hope to acheive with your method. When you do enough work with your system, it ends up that there are 60% commented lines, with 40% real lines. Trying to go backwards 1 week would create tons of problems. If there are too many useless comments, nobody will ever read any comments, or feel like putting good ones in.

      --

      Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
    11. Re:Top Ten Code Comment Do's List by Fulg · · Score: 2, Insightful

      Moderate -1, WRONG. Whenever I make a change, I almost always comment out the existing line, put my initials, date, and why I commented it, and then put in my new line.

      Moderate -1, WTF! There is no reason whatsoever to keep old code in comments; that's what source control is for.

      My $0.02, and doing this has saved my butt numerous times when you're sitting at the implementation phase, ready to go-live, and something fails last-minute. (testing be damned!)

      You know, that explains a lot. Never mind then... :)

      --
      gcc: no input sig
    12. Re:Top Ten Code Comment Do's List by Retric · · Score: 2, Insightful

      USE CVS!

      That way you can look at the "clean" code that the system is using and automaticly roll back all changes made to some or all files on a given date. You can even use diff to see what changed over longer periods of time in a given function. And it's automatic so you don't need to wonder if you realy rolled back the code to 12/15/04 you know it's what's in production.

      And you get a simple place to comment the scope of what you where fixing / working on over several files. And can clearly see what files where changed for this fix.

    13. Re:Top Ten Code Comment Do's List by I_Love_Pocky! · · Score: 2, Insightful

      Only in procedural code. That hardly makes sense with method calls.

  47. A database backend would go a long ways... by mosel-saar-ruwer · · Score: 4, Interesting

    GRANDPARENT: Especially if you change the code and now the comments are wrong

    PARENT: You're incompetent if you don't change the comments to match the code. You're equally incompetent if you come across incorrect comments and leave them in. You're supposed to the job, so do it...

    PARENT: As Fred Brooks said, "There is no silver bullet."

    A database backend would go a long ways towards providing a silver bullet, i.e. if instead of writing your code to an ASCII text file, you were writing to a document management system that kept doubly linked associations between the lines of code and the comments associated with those lines of code, and if code/comment pairs had dirty bits, so that if you changed one [e.g. the code], then the dirty bit wouldn't get changed to clean until you verified that the other [e.g. the comment] was correct, then that would go a long way towards solving the problem.

    I think we are still in the infancy of code/documentation/database integration, however.

  48. You new fangled whipper snappers by SpacePunk · · Score: 2, Insightful

    If it was hard to write, it should be hard to read.

  49. Re:Why I think it's difficult by swordgeek · · Score: 2, Interesting

    Hmm. If you have a picture in your brain, you should be able to describe it in plain language. If you can't do that, then the code that implements it is of questionable validity. It doesn't make the code bad, but it does imply that the code is going to be difficult to follow.

    --

    "People who do stupid things with hazardous materials often die." -- Jim Davidson on alt.folklore.urban
  50. Great topic for a funny (but long) story by RetiredMidn · · Score: 2, Funny
    Back in college in the 70's, I worked as a "consultant" in the computer center, assisting users with whatever questions they might have. A freshman taking the entry-level programming course, which used FORTRAN on punched cards(!), came to ask why his program wouldn't compile.

    I opened his listing (printed on non-recycled 11x14 paper), and was surprised to find the listing double-spaced. I tried to figure out how he did it (assuming it was an obscure parameter on the job control card), and eventually realized that he had inserted a blank comment between every line of code (ignore and forgive the periods; I had trouble indenting):

    C
    . INT I
    C
    . REAL X
    C
    . I = 0
    C
    . X = 0.0

    Understand that this meant that, while at the keypunch, he took the time to type a single "C", then feed a new card (taking a couple of seconds), before entering another line of code. (Not to mention the waste of expensive card stock.)

    When I asked why he took the time to generate all those blank cards, he answered, sincerely, (wait for it...):

    "The professor said the program would be easier to debug if we had a lot of comments."

  51. Literate Programming (with caution) by os2fan · · Score: 3, Interesting

    I have written programs in both raw and literate programming style, i prefer the latter. In fact, i wrote a literate-program pre-processor to write programs, and it made the program easier to write and more bug-free.

    In literate programming, you rely on a pre-processor to make the output production, so you are free to put things together as you want. What this means, is that bracketing code (eg open, close files), can be written in the same block, which are invoked separately.

    The main program then ends up looking like a rough scetch, full of commands to include other bits. With wing comments, it is easy to see what is going on.

    /* A rexx script */
    !inc rexxsets ; standard settings
    !inc cmdopts ; process command line options
    !inc fileopen ; open files
    !inc mainprog; main program
    !inc closefile ; close files
    exit
    !inc subs ; subroutines

    One uses a folding editor to search for strings like "!topic". This will not show you a consolidated index, but you can use it to also show where you're are, and any missing bugs.

    On the main, Jon Bentley's comments on Literate Programming are fair (that is, it creates a good environment for writing single-purpose code), but one needs to consider the context the program is written for.

    The form i use was specifically designed to allow all sorts of text-output, so the same file can make as output, eg .CMD, .REX, .TXT and .HTM output, which means that when you run the script you get a perfectly matched set of files, all correctly pointing to each other.

    --
    OS/2 - because choice is a terrible thing to waste.
  52. Necessary on low-level code and interfaces by wtarreau · · Score: 2, Insightful
    Having spent much time on low-level code (assembly or complex C primitives), I can say that comments are important when it is difficult for the reader to understand the sense of group of lines.

    In assembly, this is totally necessary. For example, this old DOS code :
    mov ah,7 # 7=character printing function
    mov bl,7 # color code : 7=white
    mov cx,1 # one char
    mov al,[esi] # character to print
    or al,al
    jz end # stop on NULL char
    inc esi
    int 10 # print it
    end:
    Obviously, without the comments, you won't understand what I wanted to do, and you could for example suppose that I could have replaced 'mov bl,7' by 'mov bl,ah' since they were identical, which was pure coincidence.

    In higher level code, on tree-walking functions, or in finite state machines, you need to comment your intent, because you'll always put bugs, and the only thing which counts is the algorithm that you validated by hand on paper. So you explain what you tried to do, and anybody reading your code (including you) will then understand why some transitions don't work as expected.

    I often ask friends to comment their interfaces so that even themselves know if their input is valid. Example below:
    // opens file "f" for read/write, creates it if it does not exist,
    // creates the parent directories if needed. If f is NULL or empty,
    // opens stdin. Returns 1 if OK, otherwise 0.
    int open_file(char *f)


    But on the other end, I hate useless comments such as all cited in other posts (eg: print "x" on console). They make it difficult to read code.

    Following such rules will generally help people understand your code, and help yourself maintaining it over the years. That's also one reason I quickly forgotten how to code in perl :-)

    Willy
  53. Linus' Opinion by Brainix · · Score: 2, Informative

    I can't believe noone has posted about this yet. Click here (or check /usr/src/linux/Documentation/CodingStyle) for Linus' witty and insightful views on this topic. Chapter 5 in particular.

    --
    Raj Against the Machine! http://social-butterfly.appspot.com/
  54. Good Code vs. Comments by shelfc · · Score: 2, Insightful

    Comments are important. However there are different types of comments each with varying degrees of priority. Comments are primarily code documentation. Code generally starts with some sort of design and design documents are the first stage of code documentation.

    Designs don't have to be monolithic war and peace style documents, rather very high level documents describing the purpose of the code. This generally gives future maintainers of developers an idea of the effect changing the code will have on an application.

    Class Documentation / API Documentation / Java Docs / Perl Docs / .Net XML Docs are in my opinion are the most important forms of code documentation. I very much enjoy reading articles about programming concepts and designs. But when I am coding, it is the API documentation that I spend most of the time reading. My favorite languages are those which provide a large library of useful classes that I can reuse. perl, php and Java have large online communities that produce reusable library. This has two effects.

    Writing such small reusable libraries generally the documentation will be very good. Each reusable library has documentation that allows other programmers to figure out how to use them. This means people writing these libraries are not only good at writing reusable code. They are also good at instructing others about how to use such code. Over time they become experts at documentation and serve as role models for others developer. .Net is an example of a large development group accepting these practices and now trying to embrace such strategies. But there is a much more interesting aspect to this.

    Developers using these libraries become very good at using libraries. As programmers become more experienced, they progressively become more adept at finding reusable code and being able to make it part of a consistent unified solution. Developers who are practicing these techniques are becoming very good at designing and documenting reusable code. Having this community of code exposes developers to an enormous amount of high quality well documented code. This not only allows them to be more efficient developers, but teaches them to be very efficient designers. These are the people who become the respected technical leaders and in the optimistic case your boss or the senior programmers on the projects for your work. Perhaps you are one of those programmers and other a benefiting from your use of such tactics.

    The least import type of code comments are the one or two lines before the while loop. These types of comments document the code at a micro level. At this level you rarely need a lot of comments. In most cases a competent developer requires the ability to decompose the code and this level without a lot of comments. This type of comment is never the less on the forefront of most discussion about code comments. Less experienced developers general can figure out the code is difficult to maintain but may not know exactly why. Not having the experience to point at exactly what makes the code difficult to maintain they assume it lacks sufficient documentation. This argument seems almost immediately logical. Unfortunately there is a flaw in this logic.

    Just because code is difficult to maintain or enhance does not indicate poor documentation. I have maintained lots of well documented code that required hundreds of hours of modification to fix simple bugs or implement small changes. Several years ago I was asked by my company to help when a new application was released to our clients. This code met the acceptable requirements for code documentation. Each file had a header with modification history including date and developer information. Comments we also placed liberally throughout the code. This projected resulted in a single release and is currently being rewritten from the ground up. When I was asked to assist with the analysis the code documentation helped us quickly conclude the application would not be a viable replac

  55. Actual code block by GrouchoMarx · · Score: 3, Interesting

    I love telling this story...

    Last year I had a brief stint at a small software company that had just taken a project in-house that was developed by an outside contractor. My job was to take the code they'd just inherited (which no one there knew anything about) and add some features to it on a tight schedule. Documentation? What documentation?

    The extent of all of the code comments it had was the following (and no, I'm not making this up):

    if(...) {
    break; // break
    }

    If that wasn't bad enough, I knew the original developer personally. She was a former professor of mine and I'd worked for her company only a few months before she had taken that contract.

    As someone who has had to deal with code with descriptive names and no comments or docs to go with them: If you write such code, may you rot in the lowest level of hell along with traitors, used car salesmen, and people who answer cell phones during movies.

    --

    --GrouchoMarx
    Card-carrying member of the EFF, FSF, and ACLU. Are you?

  56. Depends on the comments... by The_Incubator · · Score: 2, Funny
    I recently finished a product that my company inherited from another developer that was going out of business. In the midst of some of the worst code I've ever seen were comments like this:

    //here again we continue with the hack we don't understand

    No joke, that was in production code from developer that I'm sure a lot of you would recognize. There was also something in there to the effect of:

    //we continue again with the +1 magic

    But I didn't find that one, I just heard stories.

    Nick

  57. After coding for 22 years... by coolgeek · · Score: 2, Insightful

    I think it's safe to say comments are for the benefit of those who have not assimilated their language, their APIs, etc. Sure, documenting interfaces is essential as well as how certain data structures are used. Most of the other comments I have seen are completely superfluous and only enhance the understanding of the uninitiated.

    --

    cat /dev/null >sig
    1. Re:After coding for 22 years... by EEBaum · · Score: 2, Insightful

      Just because you've seen lots of lousy comments, doesn't mean good comments don't exist. They do, and are immensely helpful.

      --
      -- I prefer the term "karma escort."
  58. Comments? Pshaw! by MsWillow · · Score: 2, Interesting

    Comments, at ***BEST***, tell you what the author of the comment *hopes* was going on, at the time it was written. The code that follows may well not do anything of the sort; it may have, at one point, only to have been re-written by somebody else at a later date; it may still do what was stated, though that's no longer what's needed.

    Yes, it takes longer, trying to grok uncommented spaghetti code, but doing so on a regular basis will help you develop a reputation for being able to fix any bug, anywhere, any time. It even allowed me to track down a bug in a now-defunct version of Borland C's optimizer, that produced incorrect code when two seemingly unrelated options were selected. There ain't *NO* amount of commenting in the source code that would have helped there.

    Learn to do your job right. Don't depend on what was written in any comments. The compiler ignores comments; so should you. However, as damned few programmers actually know how to debug other people's code, and many are too lazy to read it like a compiler, do add comments to your own code. It makes the stuff easier for PHBs to read. ;)

    For those who want to grok code the way it's executed, I'd suggest you start like I did, by reading old obfuscated C code winners, and running them in your head, comparing what you got with what the computer got. You'll burn up a lot of scatch paper, but eventually, you'll see what I mean.

    --

    Lemon curry?
  59. Purpose of comments by Todd+Knarr · · Score: 4, Insightful

    I'd say you're right, comments are more important. Clearly-written code should make how it's doing things obvious, yes. Comments, though, should say what is being done and why it's being done the way it is.

  60. here's some Pretty Evil Shit - Re:Even more annoyi by Fubari · · Score: 5, Funny
    Here is an example of some Pretty Evil Shit:
    I want to laugh when I read it.
    Some of it is funny.
    Some of it is just scary.
    The human mind can be a freakishly messed up thing.
    http://mindprod.com/unmaindocumentation.html
    It is part of a larger essay about writting crappy code.
    Anybody that even comes close to software development
    should check it out.

    --- begin excerpts ---
    Avoid Documenting the "Obvious" : : If, for example, you were
    writing an airline reservation system, make sure there are at
    least 25 places in the code that need to be modified if you were
    to add another airline. Never document where they are. People who
    come after you have no business modifying your code without
    thoroughly understanding every line of it.

    Units of Measure : : Never document the units of measure of any
    variable, input, output or parameter. e.g. feet, metres, cartons.
    This is not so important in bean counting, but it is very important
    in engineering work.

    As a corollary, never document the units of measure of any conversion
    constants, or how the values were derived.

    It is mild cheating, but very effective, to salt the code with some
    incorrect units of measure in the comments.

    If you are feeling particularly malicious, make up your own unit of
    measure; name it after yourself or some obscure person and never
    define it. If somebody challenges you, tell them you did so that
    you could use integer rather than floating point arithmetic.

    On the Proper Use of Design Documents : : When implementing a very
    complicated algorithm, use the classic software engineering principles
    of doing a sound design before beginning coding. Write an extremely
    detailed design document that describes each step in a very complicated
    algorithm. The more detailed this document is, the better.

    In fact, the design doc should break the algorithm down into a hierarchy
    of structured steps, described in a hierarchy of auto-numbered individual
    paragraphs in the document. Use headings at least 5 deep. Make sure that
    when you are done, you have broken the structure down so completely that
    there are over 500 such auto-numbered paragraphs.

    For example, one paragraph might be: (this is a real example)
    1.2.4.6.3.13 - Display all impacts for activity where selected
    mitigations can apply (short pseudocode omitted).
    then... (and this is the kicker) when you write the code, for each of these paragraphs
    you write a corresponding global function named:
    Act1_2_4_6_3_13()
    Do not document these functions. After all, that's what the
    design document is for!

    Since the design doc is auto-numbered, it will be extremely difficult
    to keep it up to date with changes in the code (because the function
    names, of course, are static, not auto-numbered.) This isn't a problem
    for you because you will not try to keep the document up to date.
    In fact, do everything you can to destroy all traces of the document.

    Those who come after you should only be able to find one or two
    contradictory, early drafts of the design document hidden on some
    dusty shelving in the back room near the dead 286 computers.
    --- end excerpts ---
  61. literate programming by The+Shrubber · · Score: 2, Interesting

    I am surprised nobody has brought up literate programming yet. Completely flips over the relationship between code and comments. You are principally writing a document for human consumption. One in a while, you also toss in a little fragment of code for the computer's benefit.

  62. code = WHAT, comments = WHY by Anonymous Coward · · Score: 3, Interesting

    The code should be written so that it is obviously WHAT it does.

    The comment should explain WHY.

    Not that I use that convention myself, but I often wish that I did :-) Like when I go "ok, it's doing that... But WHY?", I know that I should have put in a comment. But if I go "WHAT the f**k is it doing here", those lines should be rewritten.

  63. Actually, you illustrate a bigger problem by Moraelin · · Score: 4, Interesting

    It's not just that the programs to write are small, it's that they're write-only. You write them once, get graded, that's it. We churn generation after generation of students who are taught that code is written once, then never ever maintained.

    Sure, you learn lots of things about design, software engineering, etc, in university, but they're pure theory. And seemingly useless theory at the moment. There is _nothing_ to illustrate there why some code organization is good, and why spagetti code is bad. All those lessons about maintenance as wasted when you never have to maintain anything, nor ever write anything big enough.

    So while I'll say your idea does have merit, I think it can be done better. Don't just give them 1000 lines of someone else's code. Make them keep building and expanding the same program until the last year.

    E.g., ok, in introductory programming they had to write some 100 line trivial program. But don't throw it away. When the next course comes along, give them the assignment to change or expand that original program.

    E.g., if at some point you also get a computer graphics course, make them add a graphics module to that program. GUI programming? Sure, add a GUI to it. Database programming? Sure, make it save the data in a database. YACC? Ok, make them add a small scripting language to it. Different language? Make them port it to that language. Etc.

    Make it a part of the grade to explain _what_ had to be changed and _why_.

    Eventually it _will_ grow to be 1000 lines, and then it will grow even larger. And more importantly it'll be example of why code has to be readable and maintainable.

    --
    A polar bear is a cartesian bear after a coordinate transform.
  64. variable names are sooooooo easy by speedplane · · Score: 2, Interesting

    I don't understand why people don't use more descriptive variable names. For something stupidly simple like a counter in a 'for' loop, the iterating variable could easily be 'ctr' instead of 'c'. There is zero performance hit and everyone understands the code more clearly. TWO LETTERS, come on man!

    Going further... in c++ member functions and variables should be more descriptive. For instance, in a variable length array class, (mMaxArrayLength, mCurrentArrayLength) are much much better than (max, len) which is the common lexicon.

    I feel (at least in c++) that documentation should only be used to explain high level functionality, the inner workings of a fucntion/method should be evident by the variable/method/class names. It doesn't add code size or decrease performance in any way. And, with the advent of copy and paste, it doesn't really slow development time either.

    BUT.... Even more important than that is consistancy. Whatever coding/documenting style is chosen for a particular project, for god sakes, stick with it. Nine out of ten coding/documenting styles will be exactly the same, with little changes here and there. The most important thing is be consistant with the whole project.

    end of rant

    --
    Fast Federal Court and I.T.C. updates
  65. Comments add information not in the code by apposite · · Score: 2, Interesting

    I find that the most useful comments clarify the underlying code by adding something that may not be possible to get from the code itself. For example the intention of the code may or may not be clear (the code may be incorrect or it could 'mean' several things given the context) but a comment can be explicit about the intention.

    The point is you are not repeating the code statements- you are adding information to the source code. This makes it a lot less likely the comment is going to go out of date. In many cases you can change code and the comment will still remain the same (you are still searching a hash for the RequestItemId- just doing it faster/better/correctly).

    Programming is about translating concepts from a problem domain (Billing, Accounting, CRM, Networking, Memory Paging) into code (be it C, C++, Java, Perl, Pascal..). We endeavour to build functions, methods and objects that map to the problem domain (so we can display a picture, act on a button click, add a charge to a customer's bill...). But this translation inevitably has some tricky bits that are not clear from the code (what format is the time in? why do we have to mask of the data retrieved from disk? why aren't we validating the customer's username?). So it can be useful to put the 'original' (our intention) in there and any useful translation notes (the tricky or non-obvious bits) so that we can make it clear where something is done or not done deliberately- and when it is simply an error.

    Good comments add information not necessarily obvious from code. That makes it tricky to write good comments since you have to look at the code as if you had never seen it before and ask: what isn't obvious about this? Which is why writing the comments before you write the code can be much more effective. After you've written the code it just feels like you are stating the obvious. Which it is- to you, at that moment in time.

  66. what about teaching people HOW to comment? by beforewisdom · · Score: 2, Interesting

    The comments from the TAs about near useless comments was interesting.

    Getting people to do any comments is a conversation in itself.

    However, the TAs brought up a good point. It is not enough to put ANY comments in a file, you need to put GOOD comments in, but who teaches people what good commenting is?

    What works for me is
    - putting a small paragraph at the top of file
    explaining, in general, what the file is for
    ( sort of like labeling a jar with the preserves
    you just put into it )

    - putting a 1-2 line description above each
    non-trivial function

    - putting a sentence fragment above each
    significant or non intuitive ( coding around a
    quirk ) block of code

    I get compliments on how easy it is to understand and maintain my code( often resulting in me getting to asked to write more code - versus the folks who intentionally obscure things in the pursuit of job security ). I can also go back to code I wrote years ago and understand what it is going on.

    I put comments in as I write the code, mostly, so it doesn't feel like a burden.

    If anyone has any other good idea, please do tell, someone somewhere is likely to give it a try.

  67. Author is correct by DukeLinux · · Score: 2, Interesting

    I teach computer programming part time at a local college - when students sign-up :(. 50% of their grade is based on their comments. I have spent too many years in industry to dismiss that value of good comments in code. Commenting first helps you think through your solution then you stomp down your code and clean-up your comments. Time and again this will take you LESS time and produce higher quality code then just banging away.

  68. From a tech writer by clawhound · · Score: 2

    I used to be a technical writer. I really come at code form a documenter's point of view. I found that comments do more to CLEAN UP my code than anything else. Commenting really forces me to consider what I am looking at and what's I'm doing. Comments are great. Good code will never be self-documenting. There's more to good code than variable names. I use comments to describe intent. I use comments to point out idiosynchrasies, and why those are in the code. I use comments to explain the overall logic of the code, and the logic at specific points. All that helps me to find and fix problems faster. That helps me to know where in the code to add new code. That helps me to compare my intent with my execution. And more importantly, this helps the next person greatly.

  69. I must respectfully disagree. by Richard+Steiner · · Score: 3, Insightful

    The three items you seem to object to all have fairly legitimate uses in some computing contexts.

    1. Comment each function
    - Function name


    Why do you need to repeat the name of the function? It's right there in the code.

    Yes, and in some contexts that is precisely the problem. Depending on the language and editor(s) you are using, embedding the function names in comments can be very useful.

    For example, if I use an "FC" command in a Unisys 2200 mainframe editor (say ED or UEDIT) to show all lines starting with "C" (comment lines) in a Fortran program, the results will be confusing if the function names themselves are not specified in a comment line. All I will see is comments with no context.

    By adding the subroutine or function names in the related comments themselves, that missing context is restored.

    5. Put in a '?' comment for code that you do not understand (good for function headers)

    Code with personal annotations should never be released.

    While I agree with this part,

    If you don't understand it, you shouldn't be working with it; go find someone who does understand it instead, or stop and work it out.

    this part of your comment seems limited to "perfect world" scenarios only.

    I've spent most of my career working on mainframe code that was either originally written by people at other organizations or companies, or that was written so long ago that the original designers and coders were either retired or deceased.

    When making a first pass at understanding such code, I've found it to be quite useful to leave various comments in the code so I have a good idea about my level of understanding the next time I have to come into that area of code.

    I've also found such comments useful when left in the code by others, since it reflects their level of understanding as well. Some of the stuff I'm looking at now was originally coded in the early 80's and rewritten by my predecessor, and the comments he's placed in the code have proven to be invaluable to me, even though some of them were speculative in nature. Something like "What does this code do?" in his comments often alerts me to a tricky part in the logic that I'll want to pay special attention to.

    FWIW, question marks and other comments/speculations are commonly used when working on someone else's previously-written code, at least in my experience, especially when that code is only intended for use in-house (the source is not released to customers).

    8. Tag your bug fixes, code enhancements with a comment followed by a dash, date, and your initials. This is essential for large projects or for anything you will be working on for more than 6 months.

    Once again, nothing with personal annotations should ever be released into source control. Not only should I not need to know who wrote or changed a particular snippet of code to fix a bug, I shouldn't even be able to tell by looking at the code.

    When working on code that was written in-house, and which is intended to stay in-house, I *want* to know who made a certain change and why it was done. That type of notation can save me (or another support programmer) a lot of time.

    While those types of details might be handled by the source control system(s) that you work with, keep in mind that some of us work on platforms where analogs to the UNIX-like source control systems many people are used to simply do not exist (and often such a thing isn't really needed).

    When I did Unisys A-series mainframe contract work at a small company in southern Minnesota, they used the unparsed end of each COBOL line as a comment area, and one always placed their initials and a date there so people knew who did which changes and when those changes were created. The editor they used (CANDE) even had a special setting to automagically place a change mark on the end of each line that was modified.

    A si

    --
    Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
    The Theorem Theorem: If If, Then Then.
  70. Comments don't execute by Symbiot · · Score: 2, Interesting
    Comments exist to add value to code. Saying that comments are more important than code is like saying that cooking is more important than food.

    To paraphrase Einstein: we should write as few comments as possible, but no fewer. The reason is that comments don't execute and therefore aren't constrained to tell the truth about the code. So anything about the code that can be said directly in the code ought to be because that makes what's been said inseparable from what actually happens when the program runs. If it can't be said in the code then it ought to be said in the tests. Tests don't force the code to conform to the properties that they describe but the do tell you if it doesn't. They are one step removed but still provable. The redundancy of saying the same thing in both the code and the tests is valuable because the difference in perspective forces a greater degree of precision and, therefore, a higher chance of correctness.

    Saying the same thing again in comments is not useful from the perspective of correctness, so the value of redundancy in comments is limited to the value of redundancy in most communication: if it's done sparingly it adds emphasis, otherwise it's just a harmful distraction. The value of comments is that they can be used to say all of the things that couldn't be said in the code or in the tests. The best code expresses the vast majority of its important information in the code and the tests, but is not stingy about expressing all the rest of its important information in comments. Comments written in this way augment the code without distracting from it.

    Remember:

    The code is the truth
    The tests expose the truth
    The comments embellish the truth
  71. Just 1/10th? by bluGill · · Score: 2, Interesting

    I've seen cases where a fresh from school programmer turned 20,000 lines of complex, hard to understand code into 3,000. The complex code was written by a programmer with 20 years experience. (Hence my belief that you cannot be both a good programmer and a good musician)

  72. Uncommented potion code by CarpetShark · · Score: 2, Insightful

    This is a good example of code that can be improved for documentation and readability, actually. Instead of checking for negatives, which is backwards to normal thinking, you can assume a combination will not work, and then describe the combos that will work:

    Most of your code would look like this then:

    PotionCombo potionCombos[] = {
    { WATER, SOIL, MUD }
    { WATER, BEER, CHEAP_BEER }
    };

    A comparatively small loop function can check the list:

    /* checkPotionCombo

    Check a given combination of potions,
    returning the potion that results.

    Returns: the combined potion, or an empty
    flask if the mixture is invalid.
    */
    function checkPotionCombo(Potion a, Potion b) {
    /* Ensure arguments are valid */
    REQUIRE(isValidPotion(a));
    REQUIRE(isValidPotion(b));

    Potion result = EMPTY_FLASK;

    /* make sure argument order matches the order
    of our combination lists (lower potion
    number first) */
    a = min(a,b);
    b = max(a,b);

    /* loop through each potion combination */
    for (i=0; i<NUM_POTION_COMBOS; ++i) {
    /* check that the potion combi is filled in
    properly */
    assert(isValidPotion(potionCombos[i].a));
    assert(isValidPotion(potionCombos[i].b));
    assert(isValidPotion(potionCombos[i].result));

    /* check if this combination matches the
    arguments
    */
    if ((potionCombos[i].a == a)
    && (potionCombos[i].b == b)) {
    /* this combination works. Use its
    result, and stop searching */
    result = potionCombos[i].result;
    break;
    }
    }

    /* make sure we're not returning junk */
    ENSURE(isValidPotion(result));

    return result;
    }