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

1,021 comments

  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 blueadept1 · · Score: 1, Funny

      I'm really sorry dude. I thought you didn't know what print was :/

      Just flaunting my leet ski11z. Keep it uber.

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

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

      Emacs will handle that too...

    7. 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.
    8. Re:Even more annoying... by Anonymous Coward · · Score: 1, Interesting

      Emacs will also handle /sbin/init and could be a replacement for mister house, but not all of us want to install a such a behemoth onto our workstations.

    9. Re:Even more annoying... by notthe9 · · Score: 1

      So will the MATLAB native editor.

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

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

      1994 is calling and it wants its Sparc IPX back.

    12. Re:Even more annoying... by ZhuLien · · Score: 1

      I cannot speak for everyone, but I have found that over time, I have improved in both my coding style and readability. Because of this, overtime it has been less necessary to comment when I use a 3GL. I now comment where needed to describe intended functionality of obscure code. Any experienced coder should be able to make 90% sense of my code without too much time spent on it. When I use Assembler, I comment pretty much every group of lines which does a higher-level task in a way that is perfectly clear (ie: my Assembler code is *full* of comments).

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

    14. 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?

    15. 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
    16. 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.
    17. Re:Even more annoying... by Dwonis · · Score: 0, Offtopic
      not all of us want to install a such a behemoth onto our workstations

      Says an IE/Win or Firefox/KDE user...

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

    19. Re:Even more annoying... by Brandybuck · · Score: 1

      I've taken five introductory programming courses over the past twenty five years (Fortran, Pascal, assembly, C, C++), and not once have I ever been marked down for not writing a trivial comment. I once took a survey class on languages where I had to write code in everything from Lisp to Snobol, and never been marked down for a lack of hyper-obviousness.

      --
      Don't blame me, I didn't vote for either of them!
    20. Re:Even more annoying... by Bluedove · · Score: 1

      I used to grade student's code as a TA at my university, and I'll tell you what is more annoying than NO comments, this:
      printf("Encrypt message..."); /* print "Encrypt message..." to the console */


      The student must have had his Relevance parameter closer to SCO and the Verbosity set closer to IBM on his//her version of
      commentator

    21. Re:Even more annoying... by Anonymous Coward · · Score: 0

      which is sadder-- students who don't know how to indent, or TAs who don't know how to indent?

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

      Reminds me of an old roommate. After he finished typing a paper in Word, he'd go back and put a pair of carriage returns at the end of every line in order to double space the paper.

      Was kinda funny though when he had to revise the paper later on, having to undo all that work then redo it after making the edits...

    23. Re:Even more annoying... by skraps · · Score: 1

      We must work at the same company... I end up deleting several of these crap comments every day.

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    24. 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.

    25. Re:Even more annoying... by dgatwood · · Score: 1
      IMHO, annoying is trying to parse comments like the above in a dozen or so languages. Fun is taking the resulting HTML and tacking it to the nearest bulletin board so that everyone can poke fun at RG.... Which reminds me, I need to fix the comments on a couple of functions I tweaked today in some software so that a few years from now, I don't end up with my comments tacked to a bulletin board somewhere. :-)

      On a related note (shameless plug?), check out HeaderDoc. Basically, it's like JavaDoc for PHP, Perl, C headers, C source files, C++ headers, Objective C/C++ headers, JavaScript, Java (why not?), Pascal, MIG definitions, and shell scripts... maybe some others I've forgotten about.... It's fun for the whole family... or something....

      --

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

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

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

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

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

    29. 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!
    30. Re:Even more annoying... by Anonymous Coward · · Score: 0

      WTF! What's to indent? One line of dense perl code, followed by 2 pages of comments disecting that code. Then you can grade the student on his/her comment writing style instead of functioning code, right?

    31. Re:Even more annoying... by xgamer04 · · Score: 1

      ... but if using Perl, 1 comment per 2 LOC.

      Um, this depends on how you write Perl code. I'm guessing they had a bad experience, something like $(*#&%@#%(*&%@#%(*&#@%(*@&#%)

      --
      When you look at the state of the world, how can you not become a radical, liberal anarchist?
    32. Re:Even more annoying... by Anonymous Coward · · Score: 0

      I took AP CS in high school, and ended up helping most of the poor schmucks in the non-AP CS class, because the teacher barely understood anything, and sure didn't help the students much.

      I'm afraid I have an ever worse "morons that mark you down if you don't blindly follow rule X" story.

      This teacher's policy was "no magic numbers". But he never explained *why* there should be no magic numbers. So you had code that started out:
      ONE = 1;
      TWO = 2;
      THREE = 3;
      FOUR = 4; ...
      I think the highest I ever saw was 100. Most people only went to 20 or so.

      That way, they could write code that looked like "if (x < SEVENTEEN) ..." -- no magic numbers, Mr. S---!

      (I figure it was a good warm-up for the Laserwriter: it got to print a few pages of easy stuff first before it got to the really horrible code.)

    33. Re:Even more annoying... by Rasta+Prefect · · Score: 1, 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!!!!!

      I'm a CS grad student, and the stuff I see from my fellow grad students amazes me. A pretty large percentage of our incoming students are from India, and it's obvious that a lot of them have never written any significant amount of code. (From talking to a few of them, I get the distinct impression that the indian educational system is pretty much memorize-and-regurgitate all the way up).

      In one case one of my fellow grad students was working on a fairly trivial assignment - Take the results of a web form and email them somewhere. (Yeah, in a grad level class. What a joke.). This was done in Perl, and he was having trouble getting it working. So he asked me to look at his code.

      No indentation. Sometimes two or three statements on a line. Random line spacing. No Comments. No use strict. No use warnings. No variable declarations whatsoever. Variable names like $a, $b, etc. Moreover, he'd turned what is about a 10 line Perl script into a good solid 50+ lines of code. Augh!!

      --
      Why?
    34. 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.

    35. Re:Even more annoying... by Anonymous Coward · · Score: 0

      And other languages with regex facilities are better? Here's a line from a quick java program I wrote the other day:

      *snip*

      Grrr... I failed it!

      Ok, I defy anyone to put a long regex string from code into slashdot. Avoiding the lameness filter with regex is too hard. Everyone's a critic.

    36. Re:Even more annoying... by __aaclcg7560 · · Score: 1

      I've taken five introductory programming courses over the past twenty five years (Fortran, Pascal, assembly, C, C++), and not once have I ever been marked down for not writing a trivial comment.

      You must not have taken a Java course where the instructor will reject your program if he could not generate the JavaDoc web documentation from the source code that was understandable. Once you get into that kind of habit, you document everything.

      Of course, it does get tedious documenting the i, j and k variables in a nested loop structure when most people know what i, j and k do. (Unless it's s, e and x; that requires documentation.) ;)

    37. Re:Even more annoying... by Anonymous Coward · · Score: 0

      Please tell me you wrote a Perl program to generate those comments.

    38. Re:Even more annoying... by el-spectre · · Score: 1

      Sadly I wasn't familiar with the goodness that is mighty Perl at that time.

      I was coding (blech) Ada, I think.

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

      I learned some C in highschool, but not C++. I eventually got around to learning by messing with Half Life mods, figuring out how the OO stuff worked as I struggled to add slight modifications to the code.

    40. Re:Even more annoying... by shadowbearer · · Score: 1

      Then clean it up and make it smaller and faster yet. ExtraC work of course :)

      SB

      --
      It's old. The more humans I meet, the more I like my cats. At least they are honest.
    41. Re:Even more annoying... by Anonymous Coward · · Score: 0

      I liked the way we did it at Berkeley. In all upper-division CS courses you several project throughout the semester and each project requires you to use what you wrote in the previous one. You get to curse the fool that wrote the code you have to work with now. Very nice.

    42. Re:Even more annoying... by greggman · · Score: 1

      >I started indenting every line as I walked through a function

      Hmmm, most modern programmers would just pick "Tools->Beautify Code" in their modern editor and not care how the other person formatted their code.

    43. Re:Even more annoying... by strider44 · · Score: 1

      easy, just replace every new line with a space and keep the semicolons.

      An instant one-line program.

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

    45. Re:Even more annoying... by Anonymous Coward · · Score: 1, Informative
      Obviously you didn't learn shit. NO MAGIC NUMBERS means:

      ERROR = -1;

      if( f(x) != ERROR ) ...

      and not:

      MINUSONE = -1;

      if( f(x) != MINUSONE ) ...

      Testing mystery numbers is bad practice. Any mystery number that you test for has some symbolic meaning. Like true, false, null... and so on.

    46. Re:Even more annoying... by skasingularity · · Score: 1

      Currently being enrolled at a university, I have began to see the worth of comments. Unfortunately, good "commenting style" isn't really ever put into practice. To be specific, I'm currently in a class (Software Practium) which basically requires teams to do large volumes of work in short amounts of time. Comments aren't really mentioned... at all. Why? The time crunch. Having spent 14+ hours in a lab on several consecutive days just to bearly finish one phase of one project, I can tell you there isn't always time for comments in certain situations. Granted, I have looked at some things my teammates have done and just wondered "What the fuck..." Its hard to show someone the effect of returning to code 5 moths later when classes only last about 3.

    47. Re:Even more annoying... by tylernt · · Score: 1

      Could be worse. Back in the DOS/WordPerfect 5.1 days, I saw someone hold down the spacebar at the end of every line until the cursor wrapped to the next line. When he later went to remove or insert a word in the middle of things, it looked like some kind of virus had taken over the screen.

      --
      DRM 'manages access' in the same way that a prison 'manages freedom'
    48. Re:Even more annoying... by Liquid+Len · · Score: 1
      I know ! I program in Fortran 90, and more than often, I end up with stuff looking like:
      ! -- Build Extended Mapping -- !
      CALL BuildExtendedMapping(IFail)
      Well, duh !
    49. 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.

    50. Re:Even more annoying... by Coryoth · · Score: 1

      If you learned Ada then you may want to spend the little extra time required to learn SPARK and learn how to write useful comments that can actually be used to reduce errors by (based on case studies) a factor of about 100 over C code.

      Jedidiah.

    51. Re:Even more annoying... by surprise_audit · · Score: 1
      I worked for a couple of years on a Help desk at a university computer facility. Probably the worst piece of code I ever saw was supposed to calculate pipe diameters and water flow in a hot-water radiator system. It was partially the programmer's fault, but also partially the professor's fault. They'd started with a simple BASIC program and were told to add bits to expand it.

      This particular programmer was jumping in and out of subroutines, using temporary variables to determine what fragments to execute. No big surprise, eventually the program wouldn't get sensible results. I think that's the *only* time I've told someone to flow-chart what he *thought* the program was supposed to do, then toss the source and rewrite it from scratch...

    52. Re:Even more annoying... by GileadGreene · · Score: 1

      It's probably worth noting that even specs written in formal languages like CASL or Z typically include a certain amount of expository natural language to help the reader understand what's going on. Not that I'm suggesting you shouldn't use formal notation - far from it - I'm simply pointing out that formal notation and informal comments are complementary, both in code and in specifications.

    53. Re:Even more annoying... by GileadGreene · · Score: 1
      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.

      Oh so true. David Parnas was pointing out the fundamental differences between Computer Science and Software Engineering years ago. Sadly, it doesn't seem like anyone has listened to him. Steve McConnell echoed the same sentiments fairly recently. I don't think anyone's listened to him either. Hopefully the tide will turn at some point, but I've seen few signs of it so far.

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

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

      So tell us, since you have an inside view:

      When is Longhorn actually coming out?

    56. Re:Even more annoying... by lewi · · Score: 1

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

      I was taught years ago to always pseudocode or flowchart first for all but the simplest programs; so I write pseudocode within stub functions that I create in the program before I do any real coding and there are my comments. All that's left is translating the comments to code and it's done. No need to comment while coding or go back and add comments just to appease someone.

      It is less stressful than trying to remember every code detail until the program is finished and certainly makes troubleshooting easier.

    57. Re:Even more annoying... by jmb_no · · Score: 1

      I found a lot of comments like that in some commercial code once. One of the nicest was: /* Set X to Y + Z */
      X = Y + Z;

      Except of course that the comment was in French.

    58. Re:Even more annoying... by Ed+Avis · · Score: 1
      Yes, or people following a rule such as 'all functions must have a comment at the top describing the parameters taken'...
      // FUNCTION NAME: do_something
      // PARAMETERS: int size, char c
      // RETURN: nothing
      void do_something(int size, char c)
      --
      -- Ed Avis ed@membled.com
    59. Re:Even more annoying... by jmb_no · · Score: 1

      /* Set X to Y + Z */
      X = Y + Z;

      Mind you, it was impossible to understand why the code was adding those numbers, nor, for that matter, what the function was doing.

    60. 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)
    61. Re:Even more annoying... by kiwibird · · Score: 1

      Not that you need it now, but... for my first introductory class, we had the book "Objects first with BlueJ", which I must say is the absolutely best (introductory) programming book I've ever opened, partly because it does just what "should be done": Teaches you to read and understand code, and add your own code to it. I was amazed at how little the next book I read after it taught me in comparison...

    62. Re:Even more annoying... by kbielefe · · Score: 1
      remove half the lines ... and it better still work!

      My first internship I had to do just that. Some test software at a wafer fab had been hacked together over 20 years by a tech who self-taught herself BASIC and didn't know anything about arrays or subroutines.

      The software tested one batch of wafers and printed out a line of results to a dot matrix printer. Based on the results, the wafers would go back in to "cook" for a while longer and another lot would be tested and printed out on a different dot matrix printer. The process was to switch between the two lots, testing and cooking, until the devices met specifications.

      The funny part was the code was in 2 identical halves except for a '2' appended to each variable in the second half to test the second lot. They wanted to switch to a single laser printer and couldn't because there was no memory between tests and you can't print out a single line at a time to a laser printer.

      I added a gui and network interface code, and still had less than half the lines of code as the original.

      --
      This space intentionally left blank.
    63. 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
    64. Re:Even more annoying... by Anonymous Coward · · Score: 0

      Oh hell yes. It sounds funny at first glance, but seriously unless a VERY VERY gifted programmer wrote and then REWROTE the code, you can easily axe 1/10th of the code and still have it work. It'll be more readable, more efficient, and just plain better.

      Such is the nature of code. The sooner people learn the better off we'll all be.

    65. Re:Even more annoying... by Anonymous Coward · · Score: 0

      Lol, funny indeed. I'd like to one up you though...

      I had professors along the same lines, so I quit school. Went to work, got a decent job and now make as much if not more than they do. SO LONG SUCKAS!

      Sorry. Its just this talk of code commenting reminds me so much of the shit I saw in school from students/professors that had no business writing a "Hello World" program. It scared the **** out of me that these people were peers in the industry.

    66. 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
    67. Re:Even more annoying... by Anonymous Coward · · Score: 0

      Not all Indian students who come into CS Grad come with a CS background. Many of them are engineers, not programmers. Many are civil, electrical and mechanical engineers. Even with CS, the emphasis on programming is less than what I see here. In India, if you want to learn practical programming, you do it in a private IT training institute like Aptech, NIIT etc, not go to college.

      I for one, take CS courses and even hope to do an MS when I finish my current course. I am a doctor had not taken a single CS course in India. Naturally I would not know much about low level stuff that you you assume someone coming to CS Grad school would know though I had done a fair amount of programming. But my perspective is different and what I hope to do with a CS degree is different.

    68. Re:Even more annoying... by maxwell+demon · · Score: 1
      Your comments are clearly lacking. It should read s.th. like
      a = 5; // assign the integer constant value 5 to the integer variable named 'a'
      b = 2; // assign the integer constant value 2 to the integer variable named 'b'
      print(a+b); // print to the console the sum of the current value of the integer variable named 'a' and the current value of the integer variable named 'b'
      --
      The Tao of math: The numbers you can count are not the real numbers.
    69. Re:Even more annoying... by aneeshm · · Score: 1, Funny

      At my school , we have the same problem . But because we had not reached a point where comments were useful , we were asked to comment trivial programs .

      I got sick of it , so I commented every cout , cin , and variable and function declaration , but none of the working code . I didn't get marked down , and the teacher hasn't bothered me about comments since .

    70. 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
    71. Re:Even more annoying... by kasperd · · Score: 1

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

      No, they'd just remove the comments. Rather require them to rewrite such that the source have the same size, but the comments to code ratio have been doubled. And of course it must still work.

      --

      Do you care about the security of your wireless mouse?
    72. Re:Even more annoying... by kasperd · · Score: 1, Insightful

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

      It is not the best way to validate user input, but it is better than no validation.

      --

      Do you care about the security of your wireless mouse?
    73. Re:Even more annoying... by el-spectre · · Score: 1

      /* TODO: Add LightenUpItsAJoke method above */

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

      I'm reasonably strict with my commenting - At the top of each function I write a comment giving a brief description of what the function does, what parameters it's expecting and what it's going to return. I then put single line comments in the middle of the more hairy chunks of code explaining what's going on. Of course I also put in /* FIXME: foo */ comments at known bugs and missing features.

      I _still_ look at my code and think "I must've been pissed when I wrote this", but I can actually work out what I was doing. I'm not sure *any* coder can claim to look at their own 2 year old code and immediately understand how it was implemented, nomatter how well documented it was. Comments just speed up the "relearning" process - i.e. the time taken to get back into a similar frame of mind to when you were writing the code originally.

      It's worth remembering that too many comments can be just as bad as too few comments. Good programming practice says that functions should be reasonably short (hopefully short enough that each function can fit on your screen - most developers have pretty large high-res screens to increase the amount of code visibale and reduce the amount of scrolly action in the editor). If you add too many comments then the simplest function can get too big to fit in your brain all at once. :)

    75. Re:Even more annoying... by martin-boundary · · Score: 1
      You bad, bad man.

      You know he was using vi, right?

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

    77. Re:Even more annoying... by Anonymous Coward · · Score: 1, Interesting

      I'm a physicist, working on hardware design for MRI scanners. I do electromagnetic theory, power systems, and basic home wiring. What's wrong with that? I also do messing around with super glue, and coding computer simulations.

      CS is not that useful, as a subject by itself. There are lots of us out here that design software, and code it, but we're not computer scientists. It's just a tool we use at get somewhere.

      What's easier? To teach a computer scientist physics, or to teach a physicst to produce software? Exactly.

    78. Re:Even more annoying... by Sathamoth · · Score: 0

      Just saying "document your code, documentation is good" isn't going to raise the code quality. There's different types of documentation and different situations where documentation should or should not be written. In object-oriented languages such as Java, interface documentation has very important role. To create a simple and quick documentation of your API, JavaDoc is enough. To create an interface documentation, which would explain the usage of the interface, write a unit test, which tests the class behind that interface. Nothing will explain the usage of interface better than the usage example code itself. If the class implementation is using some complex algorithm which should be documented, probably the best approach would be to encapsulate that algorithm into it's own class and plug it into the system with some appropriate design pattern (Strategy, for example), so the documentation "raises" from inner source code level to the class level. If higher-level issues should be documented and explained, such as architectural decisions or more implementation-specific issues like "why we're using algorithm A and not the simpler algorithm B" then source code isn't very good place to write that information (per-component or per-package design documents should be considered in these cases).

    79. Re:Even more annoying... by dascandy · · Score: 1

      That can in fact be very useful. Using a coding style that evolves the code out of the algorithm itself is quite useful in later re-reading: [code] char *readfile(char *filename) { // open file // determine file length // allocate buffer // read file in memory // close file // return buffer } [/code] Everyone with a little coding sense can figure out how to code this in any language (the char *'s are for C) without changing the algorithm for loading the file itself. The algorithm is documented in the code in the area just above the code that does it. Result is that you can see what the code is supposed to do, and can then look to see if it really does that. However: [code] void *dsth(char*x) { int y = open(f, 0x02); int z = lseek(y, 0x0, 0x3); lseek(y, 0, 0); void *b = malloc(z); read(y, b, z); close(y); return b; } [/code] does not make anything clear to me. If I were to make a similar function based on a file with a header, or a packet with a header, I would have no clue what it did. Yet, the lower one should work (didn't test) and the upper one is just comment.

    80. Re:Even more annoying... by beforewisdom · · Score: 1
      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."
      I don't mean to sound like "slashdot hole" but why were you using the tab key to indent that person's code?

      Most editors ( emacs too, when I checked a few years ago ) have code beautifiers that will indent an entire file or block of code in one shot.

    81. Re:Even more annoying... by Anonymous Coward · · Score: 0

      In soviet russia we hate tools who refuse to learn how to program. Da!

    82. Re:Even more annoying... by Anonymous Coward · · Score: 0

      Except he wasn't adding the number of apples and oranges. What he should have done it:

      five=5;
      two=2;
      print(five+two);

    83. Re:Even more annoying... by chemistry · · Score: 1

      You can't engineer it until you understand how to code it. All language are different and you really need to be an expert in the language you are designing for or your coders will think you are the world biggest moron.

    84. Re:Even more annoying... by mpcooke3 · · Score: 1
      I actually find some logic to this. As long as everyone buys in to the concept. It's almost always better to refactor some code or pull it out into a method.

      Most comments i see is for code thats too complicated to understand straight off and almost always it's more complicated than it needs to be, rather than fix it some developer just puts a comment at the top along the lines of:
      /* Divide the doohicky index by the number of submaxatrons and use the result as a lookup value for the wibble hashtable, assume null results are bananas - PS not entirely sure why */
      I always find good OO code relatively easy to understand and just ignore reading the comments, which somtimes are out of date - if I'm not entirely sure what the purpose of the code is I way prefer unit tests to comments as I know the units tests are more likely to be correct - if they still pass.

      Of course none of this applies to perl or regex where i need all the comments I can find.
    85. Re:Even more annoying... by Albigg · · Score: 1

      Production code is bad too. Some people think tabs are useful, some think that 3 spaces is indenting, others 4. It is a royal pain when you combine all differnt indention styles in a single module. Then try printing it to read at home over a beer.

    86. Re:Even more annoying... by Anonymous Coward · · Score: 0

      Quoth an AC:
      in vim, with C code, you can just do:

      gg=G

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

      Yes, it will do it very suckily.
      I haven't yet seen an autoindenter that will work properly in all (or even most) cases.

    87. Re:Even more annoying... by lphuberdeau · · Score: 1

      Commenting language constructs is pointless. If a teacher asks you to comment that way, he should either be sitting in a classroom or get some real world experience. The goal of comments is to explain the algorithms and subtilities in the code. Comments should be in english and not mention variables or values. I'd rather know where the 5 is coming from (I hate magic numbers) than know it's 5.

      --
      Qui ne va pas à la chasse n'a pas de gibier
      PHP Queb
    88. Re:Even more annoying... by computational+super · · Score: 1
      What's easier? To teach a computer scientist physics, or to teach a physicst to produce software?

      Hunh? I took three required semesters of physics , three of calculus, and two physics electives to complete my degree in computer science. Plus I know how to write maintainable code. Bring it on, snob.

      --
      Proud neuron in the Slashdot hivemind since 2002.
    89. Re:Even more annoying... by ptlis · · Score: 1

      Okay, i'll take you up on that - but first bare in mind i've had no 'real' schooling related to programming so... yeah, that's my pre-excuse ;) if(preg_match('/application\/xhtml\+xml;\s*q=(0\.\ d{1,3}|1\.0|[01])/i', $_SERVER['HTTP_ACCEPT'], $matches)) (taken straight from a php content negotiation script i've been working on... be gentle.

      --
      There's mischief and malarkies but no queers or yids or darkies within this bastard's carnival, this vicious cabaret.
    90. Re:Even more annoying... by adabyron · · Score: 1

      That's sadly more descriptive than some comments I've seen such as: int length; // length or: class foo { // class foo

    91. Re:Even more annoying... by Anonymous Coward · · Score: 0

      I'm not sure if this was intentional or not, but that function doesn't throw Exception and the comment says it does =P

    92. Re:Even more annoying... by Retric · · Score: 1

      I don't know php but try breaking your code down into smaller chunks so it looks more like:

      remote_location = /application\/xhtml\+xml;

      if(preg_match($remote _location, $matches))

      Than:

      if(preg_match('/application\/xhtml\+xml;\s*q=(0\.\ d{1,3}|1\.0|[01])/i', $_SERVER['if(preg_match('/application\/xhtml\+xml; \s*q=(0\.\ d{1,3}|1\.0|[01])/i', $_SERVER['if(preg_match('/application\/xhtml\+xml; \s*q=(0\.\ d{1,3}|1\.0|[01])/i', $_SERVER['HTTP_ACCEPT'],'],'],$matches))

      If you write a complex line that does not work then it's hard to see what it's doing but if you have the same line broken down you can look at all the intermeadeat values and see what's going on. If you realy want your program to look like one line of code to scare people you can always build it up when your done but why write code like that when your trying to debug what's going on.

      I think lines of code should do one thing at a time so you can do math like A = B + C + D * E;

      Or compare something
      If ( A == N )

      but doing both at the same time is pointless

      If ( (B + C + D * E) == N )

    93. Re:Even more annoying... by Anonymous Coward · · Score: 0

      How about "remove N lines, and comments aren't lines of code"?

    94. Re:Even more annoying... by John+Courtland · · Score: 1
      Had a S/390 Assembler professor at the university I breifly attended. He was an old, crotchety bastard and I'm a stubborn asshole when I want to be. This didn't turn out well.

      So, I get my third programming assignment back: 37%! Not to toot my own horn, but I'm a pretty good programmer, and me getting a 37% on a programming assignment was unheard of until then.

      After I examined the assignment, I noticed that he fucking took off points for every line I didn't comment! Now, he said, in class, "You must comment every line of code." That's all well and good, and I did comment every line of CODE. The lines I didn't comment were DATA for the print output. I forget how ASSIST liked data to be defined, but in x86 assembler (MASM) it would look like this:
      print_line: db "Initial price"
      db 10 dup(32)
      db "Tax"
      db 10 dup(32)
      db "Total price"
      I'd like to mention here that slashcode reformatted my ecode text.
      63% of my assignment wasted because I didn't comment text... That pissed me the fuck off. So I started being a dickhead and CTRL+V'ing "This is a printline" for every line like that. What's sad is that it actually placated him. The long and short of the rest of this story is that he threw my papers at me and I no longer attend that university (by my own will, I didn't fail out, but I will not pay money to deal with shit like that). Lesson learned: College is simply an expensive highschool, unless you get good professors.
      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    95. Re:Even more annoying... by Anonymous Coward · · Score: 0

      'cb' or 'indent' to the rescue.....

    96. Re:Even more annoying... by Kinthelt · · Score: 1

      Yes, I once had my code revised and was reprimanded severely for using a "clever trick" that my supervisor thought nobody else would understand.

      The trick in question: binary search.

      --

      "Evil will always triumph over good, because good is dumb." - Dark Helmet (Spaceballs)

    97. Re:Even more annoying... by AviLazar · · Score: 1

      LOL! I did that once for a teacher. He gave me extra credit, and gave me three days to do the assigment correctly (it was a three day project anyhow). He was one of the better teachers.

      --

      I mod down so you can mod up. Your welcome.
    98. Re:Even more annoying... by Anonymous Coward · · Score: 0
      I found comments like the following get professors to shut up about such things:
      // Pointless comment to appease people who can't read C++ follows:
      //
      // Return the maximum of two numbers.
      template &lt;typename T&gt; const T& max(const T& a, const T& b) { return (a>b)?a:b; }
      My comments have always been irreverant and annoying when superfluous. Then again, I've also written class header comments along the lines of "pointless class whose only method calls standard library function--stupid implementation requirement" when professors didn't know what they were talking about.
    99. Re:Even more annoying... by lockup69 · · Score: 1

      In my experience, it helps to write extensive comments for each function, rather than each line.

      I write a comment block to explain what the function does and how its going to do it, before I write the code. Sometimes the very act of trying to explain what it is I'm going to do makes me re-evaluate the design of the function.

    100. Re:Even more annoying... by AviLazar · · Score: 1

      Still, you have to admit - someone who teaches themself a language, even BASIC, who can get it to work properly for 20 years is pretty good.

      --

      I mod down so you can mod up. Your welcome.
    101. Re:Even more annoying... by Anonymous Coward · · Score: 1, Interesting

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

      Maybe. My introduction to programming class I had to take at university used this approach (except with shorter programs). Things like "make this say 'hello world' instead of 'hello people'", and "add another button that does the same thing as all the others".

      The end result was that most people simply couldn't write a program from scratch if their life depended upon it.

      Maybe as a component for people who can already write thousand line programs it would be effective. But people that far along should already know how to write comments anyway.

    102. Re:Even more annoying... by dubious9 · · Score: 1

      WhitespaceCanbeJustasuseful.

      --
      Why, o why must the sky fall when I've learned to fly?
    103. Re:Even more annoying... by Ctrl-Z · · Score: 1

      Or maybe he just uses indent(1).

      --
      www.timcoleman.com is a total waste of your time. Never go there.
    104. Re:Even more annoying... by russotto · · Score: 1

      Better still to be the manager, but that's not the way a lot of people's skills and interests lie. Client side? That's people stuff, and what (stereotypical) geek wants to deal with people? The idea that you can take a set of requirements, and send them to a bunch of interchangable code monkeys (whether in Dubuque or Dubai) to be coded is widespread among managers but mostly false, for projects of any complexity. Anyone who has tried to fix the code generated by that process knows this. And, to remain on topic, comments in code made that way will of course be nonexistent or written in Hinglish.

    105. Re:Even more annoying... by Anonymous Coward · · Score: 0

      dude, i have SEEN code written by a physicist, and believe me, it is NOT a pretty sight. My job for the last 4 years (on and off) has been to fix up code written by a physicist so that other people can actually use it. It's gone from fixing to completely re-writing.

      Now I'm not trying to generalize here, but I will make this horribly generalized statement: Physicists and yes, (non-software) engineers, write shitty code.

    106. Re:Even more annoying... by Trillan · · Score: 1

      I went through a course like that in high school, actually. The book we used was called Just Enough Pascal.

      I went looking for it and found this old description from MacTech.

      If you want just enough Pascal to get you started, Symantec has a product that has been out since the introduction of THINK Pascal version 2.0 a few years ago. The product "Just Enough Pascal" (JEP) is a self paced course introducing you to programming with THINK Pascal and the Macintosh ROM routines. Although the product is still version 1.0, a 13 page manual is included to explain how to use JEP with THINK Pascal 3.0. Most of the differences are cosmetic since Pascal 3.0 changed a few of the menus around.

      JEP consists of a desk accessory and source code for the tutorial. It is designed so that you can open your Pascal application and JEP at the same time. The JEP DA then takes you through the development of a Macintosh application. Each "lesson" is divided into 20 stages of the development. You can start out at any stage (the source code for each stage is provided). Each stage teaches a new concept in Pascal programming and at the same time gets you familiar with using Macintosh ROM Calls.

      During a stage of the development of the sample project, you are directed to modify the source code from previous stages to add more functionality. You can copy and paste the new code directly from the JEP DA into your open source code. An explanation is provided and suggestions for "Tinkering" around with the code. The tinkering is where you have a chance to try things out and just see what happens. JEP is a great way to get started at your own pace.

      It would definitely be of limited value now, but some of the other students were proof that it was a good way to learn to program.

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

    108. Re:Even more annoying... by Anonymous Coward · · Score: 0

      annoying is trying to parse comments like the above in a dozen or so languages. Fun is taking the resulting HTML and tacking it to the nearest bulletin board so that everyone can poke fun at RG

      Awkward to read, your post is.

    109. Re:Even more annoying... by CDarklock · · Score: 1

      > Ive come to the conclusion that introductory
      > programming courses are taught all wrong.

      I've always thought the best way to teach such a course would be to group your class into three or four teams, and give them a REAL APPLICATION to write, with a bonus of some sort for the best program.

      Then, two days before finals, cancel the project and give them a test on something unrelated to it. Don't grade it, just start everyone with an A and deduct points for whining...

      --
      Microsoft cheerleader, blue flag waving, you got a problem with that?
    110. 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."

    111. Re:Even more annoying... by T-Ranger · · Score: 1

      Try guru.com or rentacoder.com .. The former is "high end" requiring some serious creds for the more interesting projects, the later has a increadably horrible interface, but has far far more projects.

    112. Re:Even more annoying... by Coryoth · · Score: 1

      It's probably worth noting that even specs written in formal languages like CASL or Z typically include a certain amount of expository natural language to help the reader understand what's going on.

      Certainly you still need comments and exposition. The point is that the bulk of this can reside in the documentation of requirements and specifications which is the logical place for it.

      The code itself will still benefit from comments as well, but it will require a lot less because the important points will be properly documented by the specification already - you will only need comments to help elucidate soe of the more complex tangles in the implementation.

      Jedidiah.

    113. Re:Even more annoying... by MenTaLguY · · Score: 1

      You know, that brings back memories of the way I learned to program. I used to copy programs from the listings in 3-2-1 Contact and Compute's Gazette, and then eventually I got curious and started tweaking them. Eventually I got to the point where I could write my own programs from scratch.

      Now, I think a little bit of learning 5-line fragments would still have been helpful, IMO. But I think you're on to something. It's a bit like learning natural language by immersion.

      --

      DNA just wants to be free...
    114. Re:Even more annoying... by Danga · · Score: 1

      Wow, you didn't go to NIU did you? I had a professor at NIU for the exact same class you are speaking of and he wanted EVERY line commented too. One of the first assignments I commented every line except the END line (I don't remember the assembly command but I know it was something that a non-coder would recognize as the end of the program because it was an ASSIST command.) He took off 40% for a perfectly working program that didn't have that last line commented.

      He also took off 60% on another program that worked perfectly except I didn't make the one part of it that outputted the calculations a separate subroutine (I misread the specs). 60% for not moving like 5 lines of code! This was a class that started with about 30 students and only about 8 were left for finals b/c the other 22 dropped the class. That professor was a dick.

      --
      Hey, there is only one Return and it's not of the King, it's of the Jedi.
    115. Re:Even more annoying... by Anonymous Coward · · Score: 0

      Even better.. indent it correctly to begin with. Then you don't need to read vim's man pages. :)

      Personally i like nvi and xcode while coding in C. :)

      (nvi when i'm using freebsd)

      As for indenting never working, try intellij idea as a java IDE. It has a great code formatting feature.

    116. Re:Even more annoying... by dascandy · · Score: 1

      or setting the post mode to "plain old text" as opposed to html stuff.

    117. Re:Even more annoying... by dup_account · · Score: 1

      It has the added benefit of reducing complexity in your code... I can tell my manager "I removed 500 lines from this file when I fixed it"

    118. Re:Even more annoying... by ben_fucking_franklin · · Score: 1

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

      It's the classical chicken and egg problem, man. Back when I was in college, we had huge introductory classes where most people mysteriously disappeared as the semester progressed.

      How can you write comments and documentation at all when you don't know what code can do and how it can do it? Few people are so strongly theoretically inclined that they can follow an abstract discourse on methodology without having had hands-on experience with the subject matter at hand.

      The problem is that there are a few barriers to be broken while learning to develop good software. Good team work is often one of them, as it takes experience and not just imagination to collaborate effectively.

      Btw, I'm surprised nobody has pounced at the "guy that figures out how to solve the challenge presented". In my experience, a lot of bad code I've produced has been the result of drinking too much coffee and confabulating on the abilities of my program. Meanwhile, time moves on, and suddenly that A+ "how the hell did you do that?"-design has crumbled and left an "is this guy a genius or a bullshitter"-pile of source.

      Chickens and eggs, man. Just gotta dig in.

    119. Re:Even more annoying... by John+Courtland · · Score: 1

      Robert H Rannie Ph. D.

      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    120. Re:Even more annoying... by fbjon · · Score: 1

      I'm pretty sure, after that person has done that for a few years, then magically discovers the return key... he's guaranteed to faint, then throw himself out the window.

      --
      True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
    121. Re:Even more annoying... by Brandybuck · · Score: 1

      I'm proud to say I've NEVER taken a Java class! But I do use JavaDoc style comments where appropriate (usually using Doxygen). But that's not documenting the internals of the code, I still use normal comments for that. Nobody reading the API documentation cares if I /* check to see if the bus has settled down */, but that's very important to know in the code itself.

      --
      Don't blame me, I didn't vote for either of them!
    122. Re:Even more annoying... by coaxial · · Score: 1

      You're right. He was using vi. Still, why would he intentiaonally make his code unreadable? I honestly couldn't find the end of the functions, let alone determine the nesting level of any statement without counting braces.

    123. Re:Even more annoying... by coaxial · · Score: 1

      I don't mean to sound like "slashdot hole" but why were you using the tab key to indent that person's code?

      Because it was only one function, and it was fast. Once I reached the line I was looking for, I stopped indenting.

    124. Re:Even more annoying... by Danga · · Score: 1

      Yep, Rannie is who I had too and it was sad the amount of people who dropped out of Computer Science as a major just b/c of his antics. Somehow I made it through but it was definately rough and I made sure to NEVER take a class he taught again.

      --
      Hey, there is only one Return and it's not of the King, it's of the Jedi.
    125. Re:Even more annoying... by John+Courtland · · Score: 1

      I witnessed a girl run out of his office crying. Tenure is really a bad system, it virtually promotes being a dickhead.

      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    126. Re:Even more annoying... by DCheesi · · Score: 1

      The point of Hello World programs is to familiarize the student with the development environment and what it takes to get a program to compile. If you don't know that, then you're limited to cut&paste hacks when you want to create something new. OTOH, I do agree that students should be exposed to other people's code early on, including having to modify it, etc.

    127. Re:Even more annoying... by TERdON · · Score: 1
      Reminds me of my first job. Part of it was programming PLC:s, using ladder programming (for non-PLC-geeks: somewhere in between of electrical schedules and assembler)...

      I was one of two people maintaining the code. Unfortunately, the editor had at several occasions "eaten" the saved code, forcing an upload from the PLC (which didn't contain neither comments nor variable names - i.e. just hardware adresses). The only help I had was an incomplete excel file over DMs (ONE of the ~5-10 memory areas in the system). It had also "died" at some occasion, so it was incomplete too. I got some help from the other coder too (even though he was CEO of the (small) company too, so it was limited... (of course, hardly any design documentation at all)

      This is a REALLY good training for reading code. It's also a really good way for getting annoyed. I took me around a year (not full time programming though, and the programming I did was on other software too). This for a program base of ~5k lines (more comparable to assembler lines then HLL:s, but still a lot easier to understand than pure assembler thanks to the IDE:s).

      I don't really have to say, the program contained A LOT more comments when I left the company...

      --
      I have a really elegant proof for Fermat's last theorem. If this sig was only a bit longer...
    128. Re:Even more annoying... by roky99 · · Score: 1
      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.

      This sort of attitude is based, I believe, on a false analogy that is made with 'real engineering'. It treats the design as a detailed 'blueprint' which can be handed over to some semi-skilled 'coder' who can just turn a handle to churn out the final product.

      A better analogy is that the code itself is the blueprint - it is the only place that contains the full detail of the architecture. The product is the executable that the compiler generates from the code.

      Design is something that happens on many different levels and at different times - including while the code is being written. I'm not saying that documents and and suchlike aren't important - they are! - but ultimately they can only offer a simplified view of the real thing.

    129. Re:Even more annoying... by Tim+Browse · · Score: 1

      This is the correct answer - I once worked with a C programmer who sucked a fair bit, and got confused by things like header files.

      He'd ask me to come and work out why his "includes weren't working", so I'd track down what was going wrong where. I'd usually give a running commentary on how I was debugging and fixing the problem, so he could learn. Usually about halfway through watching me, he'd get bored and wander off, maybe to get a coffee, or just talk to someone at the other end of the office. If he didn't reappear within a minute, I'd just leave him to it and get on with my work instead.

      He never learned to fix stuff, but he did stop asking me for help, so it was a win for me.

    130. Re:Even more annoying... by Tim+Browse · · Score: 1
      No indentation. Sometimes two or three statements on a line. Random line spacing. No Comments. No use strict. No use warnings. No variable declarations whatsoever. Variable names like $a, $b, etc. Moreover, he'd turned what is about a 10 line Perl script into a good solid 50+ lines of code. Augh!!

      But...but...TMTOWTDI! :-)

    131. Re:Even more annoying... by Thuktun · · Score: 1

      CASL

      Being an old PC dialup user, I thought that was Crosstalk Application Scripting Language.

    132. Re:Even more annoying... by dooglio · · Score: 1
      This would be especially useful for ridding a file of all tabs but preserving the formatting (i.e. :set expandtab and the gg=G from the top of file).

      Thanks for the tip!

    133. Re:Even more annoying... by TG1 · · Score: 0

      After asking how the GP was indenting code? I don't think so.

    134. Re:Even more annoying... by kwoff · · Score: 1

      Change programming (which you claim is well below your level) to Chinese and see how your philosophy works. It's an introductory course. Introducing people to something they don't know about. I had too many physics and math teachers who taught like you said, and it's just absurd. If you don't have something on which to "stick" certain things in your mind, then it doesn't stick.

      When I first learned programming, it was about making stick figures do jumping jacks with print statements. You want to do something quick and simple and see how the results relate to what you did.

    135. Re:Even more annoying... by danaris · · Score: 1

      And just how long have you been waiting for an excuse to mention the "Bang and Bracket pub"? (It's brilliant, by the way ;-) )

      Dan Aris

      --
      Fun. Free. Online. RPG. BattleMaster.
    136. Re:Even more annoying... by pyser · · Score: 1

      One of my CS profs used to say "A comment per line means you're doing just fine."

    137. Re:Even more annoying... by Anonymous Coward · · Score: 0

      That's the way it is/was? taught at MIT, I read in the classic "Structure and Interpretation of Computer Programs".

    138. Re:Even more annoying... by ashultz · · Score: 1

      Um, since about .2 seconds before I needed somewhere behind which code smugglers would hang out.

  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 LogicX · · Score: 1

      I don't see why people still cry about large indents -- If you're serious about your job, get a 21" monitor, and run 1600x1200 or higher; more on the screen, who cares about a now tiny indent.

      --
      May this post be indexed by spiders, and archived for all to see as my Internet epitaph.
    4. 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
    5. 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.
    6. Re:Gotta document that code... by FuzzyBad-Mofo · · Score: 1

      My preferred solution:

      set ts=4
    7. 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~
    8. 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
    9. 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

    10. Re:Gotta document that code... by numbware · · Score: 1
      I know what you mean, I've seen programs with Line 1 reading:

      // Start Code here

      ...and the last line reading...

      // End of code

      Pure pointless.

      --
      I'm going to go create my own technology news site, with blackjack and hookers. You know what? Forget the news site.
    11. 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.

    12. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      hardcopy? whats that? is that sorta like copyonread or something?

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

    14. Re:Gotta document that code... by Anonymous Coward · · Score: 0, Troll
      Of course you don't understand it. You don't know the language. That you chose to pick on the ?: operator and pointer arithmetic proves that you're a C novice. If you somehow manage to keep your job for more than three months then you'll probably have picked up enough to stay on... And in a year or two when you know the language then some cocksure little piece of shit who thinks he knows everything because he just got out of college having carried a 2.6gpa (and never did his coursework) is going to whine at you about these things being too hard to understand. And you'll pick up your copy of K&R smack him across the forehead hard enough to leave a bleeding gash, and then in two years he'll pick up his copy and smite his own n00b and the cycle will continue.

      Seriously? Get a fucking clue. Get yourself a copy of K&R. Read it. Understand it. Once you think you understand it get yourself a copy of "Enough rope to shoot yourself in the foot" and prove it to yourself by reading it without whining about people using the language the way it is supposed to be used. There is no reason an entire development team should give itself a lobotomy just so a jew junior programmers and interns can understand parts of the codebase they should realisticaly not be touching anyways.

      As a fun side project get yourself a microcontroller and write some assembly programs for it so you understand why C works the way it does. Good luck. I hope you make the grade.

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

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

    17. Re:Gotta document that code... by Anonymous Coward · · Score: 1, Funny

      I made the code up on the spot, dumbshit, and didn't even finish it. I can't believe you stopped jerking off for the five minutes it must have taken to write that.

      Posting AC to stay at your level.

    18. 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)
    19. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      I take it that hit a bit close to home? Study up. It's not too late.

    20. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      We all need to take a break sometime.... :P

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

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

    23. 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.
    24. Re:Gotta document that code... by skraps · · Score: 1

      LOL. Yea you got us on that one... the ole' F90 compiler croaks on tabs.
      Guys, get this out on the wire ASAP!!!! No more tabs, the F90 compiler insists!!! Pass it on!

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    25. Re:Gotta document that code... by Anonymous Coward · · Score: 1, Interesting

      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.

      You are correct but now it's not an issue of if it's correctly commented or not, it becomes an issue of programming principles. Cohesion and coupling come to mind right off the top of my head.

      I'm sure that for the code block you're refering to some of those loops should be able to broken up into each of their own methods. For example, maybe one scans linked list for a certain data item. So create a method called searchLinkedList and place a call to that within the other loop. Bam, you just moved a whole mess of code to its own method so now you can explain that method in more detail.

      Of course there are reasons for not doing so (allocating more memory for another thread on top of the call stack) but it can be ok most of the time.

    26. Re:Gotta document that code... by Fjornir · · Score: 1
      That's the only coherent argument I've heard on this subject, and I'm rather sick of hearing it. Well, alow me to retort. Does Marsellus Wallace look like a bitch??

      *cough* If you're gonna have yourself an "indentation convention" you can just as easily have yourself a "tab width convention". If you want to use an eightspace display for a tab then fine. If you want four, fine. But the code reviewer should load it up in "whatever our standard tab width" is, and review it like that. You see a convention of "tab width is four spaces" is better than "indentation is four spaces" because then for 99% of the code 99% of the time someone can adjust their width based on what their eyes need. Additionally my editor can make sense of a tab and use a smaller font/different font/greener font/whatever based on the number of preceeding tabs.

      Yes, hellish things can happen if you're not careful. Which is why we have scripts to perform certain actions on checkin -- like checking your indentation, compiling your code, running (at least part of) the BVT suite, ...

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

      All generalisms are wrong.

      Isn't that a paradox? :)

    28. Re:Gotta document that code... by Meetch · · Score: 1
      I'm sure everybody's dealt with this sort of thing before, but yes we certainly do get rushed for time, at times, and of course it will be documentation that suffers.

      However, no matter what it is, and how rushed you are, at the very least I find the minimal documentation should at least outline the functional methodology, and accompany it with purpose - ie even something simple like this can save ages figuring out why a code fragment is where it is:

      /* Now we've finished the insert, free up the kludgy locks for siblings to fight over */
      delete(foo);
      delete(bar);

      If the code itself is also self-documenting then you're nearly there. I don't often have problems going back to years-old code where I've done this, but of course it could be easier! Having said that, there's still no substitute for textbook documentation to save time and money.

    29. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      perhaps he does actually know C, but is also aware that pointer arithmatic is bad for portability reasons, and that

      if( condition ) {

      } else {

      }

      is far easier to read than the stupid ? : notation.

      throw in the meaningless variable, constant and function names in use there and you have some lovely messy unreadable code.

      knowing a language can't do a thing for you if it is written in a bad way.

    30. 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
    31. Re:Gotta document that code... by Abcd1234 · · Score: 1

      For starters, here's typically how much I comment my code

      Yeah, too much. Here's an example:

      if (sound_cache[index].sound != NULL) // Only free the memory pointed to by 'sound' if it isn't NULL
      Mix_FreeChunk(sound_cache[index].sound);

      No offense, dude, but that's beyond excessive. I mean, it goes without saying that commenting is very valuable, particularly for sections of tricky code, but really, there is a balance point to be reached, and I think you've passed it.

    32. 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'

    33. Re:Gotta document that code... by Anonymous Coward · · Score: 0
      Don't worry. If you think really hard and maybe read K&R you might (just might, but I doubt it 'cause you're being such a fucktard) understand how an if(){}else{} is not the same as ?:.

      And people who don't understand portability issues or pointer arithmetic never seem to understand why pointer arithmetic is not necessarily bad for portability. Go figure.

    34. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      Bullshit.

      You are correct that the 'cheap way out' is never good. However, writing unreadable code and then sticking in a few comments to help it be understood *IS* the cheap way out.

      Learn how to write code that doesn't need comments.

    35. Re:Gotta document that code... by snorklewacker · · Score: 1

      One of my favorites, yes.

      --
      I am no longer wasting my time with slashdot
    36. Re:Gotta document that code... by bleeware · · Score: 1

      A tab width convention for a programming editor is all well and good but... How do you convince all the other tools (that one might use to view source code) that tab == 4? Sometimes, you have to view source in a debugger that thinks tabs are 8 spaces. Ever had to view an html or js file in Notepad?

      --
      HaHa: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
    37. Re:Gotta document that code... by NanoGator · · Score: 1

      "Good documentation gives you context and insight into the motivation of a past developer..."

      Heck, it gives you good insight into a past version of yourself. I recently wrote a really complex script for Lightwave. I only started learning how to do this sort of scripting a few months ago. Just yesterday I had to wander back into some of the earliest bits of the code to fix a little problem. I do stuff a LOT differently today than I did back then, but I commented the heck out of it because I was just learning the language. I was able to really quickly figure out what I was up to and make the fix following the same spirit of the code. (i.e. the WHY part of your post.)

      I'm the only person writing scripts where I work. Nobody else is viewing the code. It's unlikely (though not impossible) that anybody else will maintain the code. Despite that, I wouldn't dream of not indenting, not commenting, or not using descriptive variable names. Heck, I even go a step further and keep a log in the code of changes I made and when I made them.

      I'm not a programmer by trade, but I just can't imagine that people actually debate about commenting code.

      --
      "Derp de derp."
    38. Re:Gotta document that code... by jbellis · · Score: 1

      Very true. Grandparent is almost a textbook example of how overcommenting is a distraction (and imposing overcommenting on others is a shooting offense).

    39. Re:Gotta document that code... by eraserewind · · Score: 1

      Tabstop on many inflexible devices and applications is 8. Indenting to the width of 8 spaces is obviously not a great thing to do. That's why people indent with spaces.

      In Vim ggVG= solves all your problems anyway :)

    40. 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)
    41. Re:Gotta document that code... by Rasta+Prefect · · Score: 1
      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.

      Well written code will explain what it is your doing at a fairly basic level. It will not explain _why you're doing it_. And thus, comments are necessary. Things like edge cases are also not always obvious.

      --
      Why?
    42. 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.
    43. Re:Gotta document that code... by penglust · · Score: 1

      Maybe and maybe not. I do know of a couple of companies that have gotten burned pretty badly by "off shoring" a significant portion of their development. They got a good price for the quoted head count but the quantity produced suffered with very little quality to make up for it. Bad programming is bad programming and will fail.

      Good software is a product of using good methodolgy. There should be some guide to where the project is going up front, software engineers that actually care a bit about what they are doing in the middle and adaquat testing at the end.

      During the whole process API documentation and general info on how the product is used needs to be created. Keep in mind I think a "product" is the sum of lots of little products. Each library is a product (and should stand on its own). Each driver and application is a product. Treating sub segments of an application as seperate products leads to library use APIs that can be reused, etc.

      All the documentation needs to evolve with the source code and be kept current. In my group engineers that do not do this get their fingers whacked.

    44. Re:Gotta document that code... by Rasta+Prefect · · Score: 1
      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:

      Great for comments about what the code does. It totally ignores another important aspect of commentable stuff which is why the hell you're doing something in the first place.

      --
      Why?
    45. Re:Gotta document that code... by Thangodin · · Score: 1

      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.

      You've never worked in game development. This is not an option... not if you want something that runs at a workeable framerate. Simple code tends to be brute force and slow.

      And you think "trial by fire" is the best way to get newcomers aquainted with the code?!?? Document complex concepts in... guess what... documents.

      Efficient code for mathematical algorithms usually requires that the mathematical formula be broken down into a form that bears almost no resemblance to the original formula. Documentation of the formula will tell you nothing about the code.

      Reading the code may tell you what it does, but not why. You have to know the why or you may end up cutting a bunch of code that you think is extraneous but is actually plugging up a hole in some third party library and preventing the whole project from crashing. And you don't want that in the documentation, you want it right there with the code where someone who is working on it can see it, so that your next version doesn't go out with a bomb in it.

      A lot of code consists of workarounds, efficiency tweaks, and bizarre arrangements required by circumstances out of the coder's control. If you don't know what those circumstances are, you're going to break things.

    46. Re:Gotta document that code... by skraps · · Score: 1

      In the last paragraph of the post you replied to, I have already addressed your point. High-level "why" documentation should go in documents, not the code. Unless you meant something other than "why" and "how". Please clarify.

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    47. Re:Gotta document that code... by Frans+Faase · · Score: 1
      prev_update = last_update;
      last_update = SDL_GetTicks();
      fps_timer += last_update - prev_update;

      fps_counter++;
    48. Re:Gotta document that code... by alanic · · Score: 1

      That is so true. And that is why I hate people write their code on the command line. In vi, If you want to use a long variable name, you have to type it over and over and over again. Then you'll get bored and start using the i = j + k nightmare. Two words: code completion. Wheres in IDEs such as Visual Studio and KDevelop(loveable), there is code completion that spares your time from typing everything down. + and it is done.

    49. Re:Gotta document that code... by rokzy · · Score: 1

      >Warning 4 at (315:boundary.f90) : Tab characters are an extension to standard Fortran 95

      you were saying?

      (I said warnings, not "croak", but way to build a straw man you leet haxor you)

    50. Re:Gotta document that code... by skraps · · Score: 1
      You've never worked in game development. This is not an option... not if you want something that runs at a workeable framerate. Simple code tends to be brute force and slow.
      No, I have never worked in game development. But I have worked on plenty of performance-critical programs. Simple code can be fast. Stupid simple code often isn't, but that is a different matter completely. Things like 1) functions, and 2) variables will get optimized away by your compiler anyway, so you might as well use them to express the intent of your code.
      Efficient code for mathematical algorithms usually requires that the mathematical formula be broken down into a form that bears almost no resemblance to the original formula. Documentation of the formula will tell you nothing about the code.
      You have used the terms "algorithm" and "formula" interchangably here, I don't know which you mean. The whole point of an algorithm is to express some process in a simple step-by-step form. Programs are typically written in step-by-step form. I don't see any blinding incompatibilities there, so I'll assume you meant to use the words "mathematical expression". In that case, you are right - writing the expression down doesn't help someone understand how it works. For that, you need lots of background information, in a document, or a book if it is that hard. When you write code to evaluate complex expressions, you are typically just following the same steps you would if you were evaluating the expression on paper. If someone can't understand it on paper, then they can't understand it in code.
      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    51. Re:Gotta document that code... by skraps · · Score: 1
      ++x+=x+++x++;

      Yes, this code compiles. That is 8 plusses, three of them consecutive. Be afraid.

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    52. 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

    53. 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.
    54. Re:Gotta document that code... by Lally+Singh · · Score: 1

      I'm pretty anal about this, but my own policy is this: tabs for indents, spaces for everything else. So, I end up with lines like this:
      void foo () {
      (tab)line 1;
      (tab)line that (
      (tab)____continues onwards
      (tab)____for a few lines);
      }

      The _s are spaces here. That way, the text looks good no matter what the indent level is (unless it's ridiculously small, like 1 space).

      Which only really works when your editor lets you see tab characters and easily manipulate them (e.g. BBEdit).

      --
      Care about electronic freedom? Consider donating to the EFF!
    55. 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!
    56. Re:Gotta document that code... by skraps · · Score: 0, Flamebait
      1. It wasn't a straw man. Learn those vocabulary words before trying to use them!
      2. Thank you for the compliment, but clearly it is you who are the leet haxor, and you haxor it in Fortran 90 no less.
      3. My point was that your concerns over a 15-year-old compiler for a POS language should have no bearing on this discussion.
      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    57. Re:Gotta document that code... by Teddy+Beartuzzi · · Score: 1
      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.

      Yup. When I force myself to do it this way, I end up with way better code. (Sadly, I lapse into my old "hammer it out" ways sometimes).

      That section of the book alone was worth the price. Incredible book for anyone, even hobbyists such as myself. Can't recommend it enough.

    58. Re:Gotta document that code... by syzler · · Score: 1

      Tabs are all fine and dandy. However when modifying scripts and simple programs on remote servers using SSH and vi, not all terminals will copy Tabs as Tabs. As a result when you copy and paste between terminal you may end up with a mixture of tabs and spaces by accident. In my experience spaces always copy as spaces which makes them easier to use.

    59. Re:Gotta document that code... by Random832 · · Score: 1

      is that
      ++x += x++ + x++
      or
      ++x += x + ++(x++)?
      or perhaps
      ++x += x + (++x)++?

      --
      We've secretly replaced Slashdot with new Folgers Crystals - let's see if it notices.
    60. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      In one project I was in, one guy always produced bad code. Everytime there was a bug, they sent me in, in order to figure out what the bug was, because, it seemed that I was the only one on the team who was able to read the guy's code. The others learned to comment code to make debugging theirs easier. When this guy eventually was fired, I rewrote all the code he had done the last year in less than two weeks. With lots of comments. The project went very well after that.

    61. Re:Gotta document that code... by CoolGopher · · Score: 1
      speak for yourself. I know my 4-space indents will be the same regardless of whatever editor and/or settings are used.

      Amen. Though I'm a 2-space person myself - I hate wasting perfectly good line space at the start of the line. The more usable space on each line, the longer and more descriptive variable names I can use.

    62. Re:Gotta document that code... by ArcadeNut · · Score: 1
      My take on comments is pretty simple.

      They need to describe WHAT you are doing, and possibly WHY you are doing it. Not HOW to do it. The Code tells you HOW you are doing it. If the comments tell you WHAT you are trying to do and WHY you are trying to do it, then you can look at the code and see if it really IS doing that.

      // Calculate the elapsed time as this will be needed to determine if we need to <do something>.

      endTime = GetTick() - startTime;

      if (endTime >= 10000)
      {
      // DO stuff :-)
      }

      It's not a perfect example of a comment, but it should get the point across.

      --
      Visit the Arcade Restoration Workshop @ http://www.arcaderestoration.com
    63. Re:Gotta document that code... by Frizzle+Fry · · Score: 1
      Well, alow me to retort. Does Marsellus Wallace look like a bitch??

      What?

      If you want to use an eightspace display for a tab then fine

      Using eight spaces is most certainly not fine.
      --
      I'd rather be lucky than good.
    64. Re:Gotta document that code... by Golden_Eternity · · Score: 1

      Yep, 2 spaces per indent here, too. With the number of times I'll find a line indented, if I tab I'll end up with a bunch of single words crammed up against the right margin.

    65. Re:Gotta document that code... by Anonymous Coward · · Score: 1, Insightful

      Actually, it's a very usefull comment. The comment is not incorrect, the code is, and when you're later trying to make the code correct, the comment shows exactly what the code should have been.

      If only all mistakes were that well commented :-)

    66. Re:Gotta document that code... by rokzy · · Score: 1

      I do numerical simulations. calling fortran a POS language just reveals your retardness. maybe to you programming just means writing a gui for some file sharing protocol in the latest language but some of us have performance and a well-established code base to consider.

    67. Re:Gotta document that code... by idries · · Score: 1

      Visual Assist will (amongst other things) refomat all your code into the "correct" tab/space arrangement. Just select the text (or Ctrl-A for the whole file) and then (Alt-F8). Done. It'll do all your intenting for if's, loops etc. and make sure that everything is tabbed (instead of spaced).

      Of course, you have to be using Visual Studio and writing C++ (or maybe C#, basically anything with {'s should work).

    68. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      1. LOL! What's a "vocabulary word" and how does it differ from a regular word?

      2. Whatever.

      3. Every sentence needs a new number doesn't it. That's what Powerpoint taught me!

    69. Re:Gotta document that code... by Anonymous Coward · · Score: 0
      x = x++; // add one to x

      is obviously not useful.
      It's also completely undefined behaviour by the C language.
    70. Re:Gotta document that code... by ElDooderino · · Score: 1

      Every line indented to some screwy level? I have four things to say about that (since you seem to be a vi user)...

      1G=G

      ;) It has quirks but usually works quite well! Just don't expect it to work if you have perl programs that use 'print <EOT;' and the like.

    71. Re:Gotta document that code... by Anonymous Coward · · Score: 0
      x = x++; // add one to x
      is obviously not useful.


      Yeah, it should be,
      x = x++; // Add one to x on GCC -O2, don't add on -O1 or msvc. Crash on SGI.
    72. Re:Gotta document that code... by Anonymous Coward · · Score: 0
      Anyone who makes decisions based on general principles does so for lack of a brain.

      The reason you have yet to see your principle disproved is because you only notice the times where you have to 'pay back twice over on the back end'. You don't notice the other corners that get cut because !shock! you don't end up paying for them.

      The reality is, there is no right answer to the question. Documentation is easy to write but is also the first thing to become unmaintained once changes are made and bugs are found. I'd rather have no documentation than comments that lie to me...

    73. Re:Gotta document that code... by speedplane · · Score: 1

      What about the other guy who write code with a tab equaling three spaces instead of four,... or five, or whatever. You are the bane of our existance

      But seriously, I don't understand why tabs have become such an issue. Any modern editor should be able to look at code and figure out the tabbing scheme and adapt it to the user settings. It could do a simple parse and look at what is at the begining of each new line. After looking at a few lines, it wouldn't be too difficult to figure out what the tab-convention is.

      --
      Fast Federal Court and I.T.C. updates
    74. Re:Gotta document that code... by Wavicle · · Score: 1

      The correlary is: "The problem with quick and dirty is that dirty remains long after quick is forgotten."

      I've often wondered how this relates to prototypes that are generally by their nature quick and dirty, but frequently necessary. Unless you are some uber-coder who can write quick and clean.

      At a place I used to work, one of the hats I wore was part time sales engineer. In between getting real work done I'd have an event happen something like this on a friday night:

      Boss: Hey, we have a potential customer half way around the country who would like to use our software, but only if it supports CORBA.

      Me: But we don't support CORBA

      Boss: Yeah, we need you to prototype a CORBA container to fit with the rest of our product and fly out there Tuesday with the sales team and show them.

      Me: But I don't know CORBA.

      Boss: Well, Bob over there knows some, just ask him if you have any questions.

      Me: Ummm, okay I'll see what I can do.
      ...3 days later...

      Me: Okay, I've managed to develop a prototype CORBA service for the product. It's in an unusual spot and will not scale well in production, but it's the best that could be done in 3 days. It works for small numbers of clients.

      Boss: Perfect!
      ...3 months later...

      Boss: The guys in services are having problems getting the CORBA service you wrote to handle even moderate loads. What is happening?

      Me: I told you it was a quick prototype - a proof of concept. Of course it doesn't scale. Part of the service contract was supposed to be money to pay someone to properly add in CORBA!!

      Boss: Why didn't you mention this when you reviewed the requirements document?

      Me: I did not get the requirements document! Nobody outside of services did!

      Boss: You need to fix this.

      Me: Grrrrrr....

      --
      Education is a better safeguard of liberty than a standing army.
      Edward Everett (1794 - 1865)
    75. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      Eh? I'm not sure where you work, but we just tell everybody who is new what their editor should use. Frankly if they refuse/can't set their editor to the correct tab size they need to be fired. What kind of ****tard can't take a simple instruction of "use 4 space indents that insert spaces"? That kind of person isn't the kind of person you want to work with.

    76. Re:Gotta document that code... by maxwell+demon · · Score: 1
      Or maybe:
      now = SDL_GetTicks();
      fps_timer += now - last_update;
      last_update = now;
      ++fps_counter;
      --
      The Tao of math: The numbers you can count are not the real numbers.
    77. Re:Gotta document that code... by markandrew · · Score: 1

      x = x++; // add one to x
      is obviously not useful.

      there's something else obvious about that, too...
    78. Re:Gotta document that code... by maxwell+demon · · Score: 1
      All generalisms are wrong.

      Isn't that a paradox? :)

      No, it's just wrong.

      Proof: Assuming it were right, it must of course be wrong (because it's a generalism itself). But assuming it's wrong doesn't give a contradiction (because the negation of it is just "not all generalisms are wrong", from which you cannot complude that especially this one has to be right). Therefore it's wrong.
      --
      The Tao of math: The numbers you can count are not the real numbers.
    79. Re:Gotta document that code... by maxwell+demon · · Score: 1

      The first one. Lexing is greedy; it only stops when the result wouldn't be a valid token any more.

      So at "+++", adding the second "+" to the first still gives a valid token (namely "++"), so it's done. Then there's only one + left for the next token. Of course, unless it's using C++ overloaded operators, it's still undefined behaviour.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    80. Re:Gotta document that code... by conradp · · Score: 1

      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


      Programmers only have so many hours in a day, and over-emphasizing the importance of documenting a developer's code can lead to less time spent improving the code. I would rather stress writing code that is easy to understand without comments, and only require comments in those relatively rare places where the situation justified a non-straightforward implementation.

      The above example shows way too much commenting, but in fact the excessive commenting hides the fact that (a) the code uses poor variable names, and (b) the algorithm is overly complicated.

      As for (a) the variable names don't include units and the variable "tmp" is both an awful name and is used to mean two different things. A better version would be:
      start_update_ticks = last_update_ticks;
      last_update_ticks = SDL_GetTicks();
      elapsed_milliseconds = last_update_ticks - start_update_ticks;
      fps_timer_milliseconds += elapsed_milliseconds;
      fps_frame_count++;

      As for (b), quick analysis shows that every time this section of code is called, you'll simply subtract out the last_update_ticks that you added the last time and replace it with the current value. So a better version of the algorithm would be:
      save_update_ticks = SDL_GetTicks();
      fps_frame_count++;

      That's all you need. Assuming the goal was to calculate frames per second, when you need it you calculate:
      fps = fps_frame_count/(save_update_ticks - save_update_ticks_0);

      If these three lines using clear variable names are wrapped inside of a short and clearly-named function like
      double getFramesPerSecond()
      then it's all obvious and clear enough that it doesn't need a single comment.
      --
      "To be absolutely certain about something, one must know everything or nothing about it." -- Olin Miller
    81. Re:Gotta document that code... by kiwibird · · Score: 1

      M-
      C-M-\

      Tabs normalized.

    82. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      I don't know what it does compile on, but at least in C ++x is not an lvalue.

    83. Re:Gotta document that code... by IIH · · Score: 1
      All generalisms are wrong.

      Isn't that a paradox? :)

      Nope, not at all. First assume the [generalised] statement is true. This implies that all generalisms (including itself) are wrong, causing a contradiction. Ergo, statement cannot be true.

      Now assume statement is false. The opposite of the above statement is "At least one generalisms is correct" not "All generalisms are correct". Ergo, this statement is incorrect, but its incorrectness has no implications on its own correctness.

      --
      Exigo spamos et dona ferentes
    84. Re:Gotta document that code... by PDAllen · · Score: 1

      Documenting code's not that hard.

      First you work out what you're going to do, and draw it out on a bit of paper. Then you start coding. When you have a function/class/whatever finished, then you write down what it's meant to do in a separate document. Then you comment the function from what you've written. Comments every line is crap, commenting only the start of the function is crap unless the function is both short and simple.

      Then when you finish you should have code that makes sense. When you need to change a function, remove all the comments from that function, re-code, rewrite comments doc, recomment.

      As far as function and variable names go - try to make names descriptive when possible mod not having to type twenty letters for a variable you use once every three lines or so through the whole code. On the other hand, if you write a function which you'll use maybe four times in your whole code, then there is no reason why the function name shouldn't be twenty letters or more if that helps.

      With indent styles - someone has to start the project, if there is a clash of indent styles, then stick a README in the directory stating that the following style... will be used. If anyone then plays games, they will get bollocked by the boss. If the boss doesn't like it, of course, then you should have used his approved indent style.

      You often will find that you have a piece of code which does something clever in a non-obvious way, and you can't see any way to reduce it to code which you can easily document as above. In which case, either write a good description of what is happening and put the whole lot as a comment immediately before the clever bit, or preferably leave it as a text file Desc_FlibFn_FooClass.txt and put a reference to that file in the code comments.

    85. Re:Gotta document that code... by CyrusSukhia · · Score: 1

      One solution is to have a pretty printer run through any file that's being commited to version control. This way formatting is constant...

    86. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      I have a slightly different aproach, let the coders use whatever coding style they like, including number of spaces, where to put curly braces etc, but have automatic code formating into a single, common standard as part of the build process. Sure, it means your source control system ahs lots of false deltas, but it means you instantly put an end to all the 'four spaces instead of a tab' arguments

    87. Re:Gotta document that code... by Trinition · · Score: 1

      I agree. Giving your variables descriptive names is a good practice, but it's not nearly enough "commenting".

      Ah, variable names. This blog entry always comes to mind:

      • I remember having a heated discussion many years ago over the use of hungarian notation. Their argument went something like:
        • ...If I don't call it pLAmount, how do I know it's a long?
        To which I replied:
        • You don't have to know if you create a Money class!
    88. Re:Gotta document that code... by Trinition · · Score: 1
      And you could even use some better variable names. This can prevent people from asking the questions they'd have to ask and go searching through the code to find the answers. It also can make the code re-usable. Sometimes, it can counter optimization (such as the code below is not reusing the 'tmp' variable for two purposes now).
      //---
      // TODO: gracefully handle wrap-around of SDL_GetTicks()
      // not implemented yet because it only happens every 40 years
      //---
      prev_last_update_millis = last_update_millis;
      last_update_millis = SDL_GetTicks();
      delta_millis = last_update_millis - prev_last_update_millis;
      fps_millis_timer += delta_millis;
      fps_counter++;
    89. Re:Gotta document that code... by jdowland · · Score: 1

      I agree. Giving your variables descriptive names is a good practice

      I'll play devil's advocate here. Imagine looking at an algorithm that happens to be incorrect. Variable names could trick you into thinking it works when it doesn't.

      It's hard to explain what I mean without concocting an example, but if you abstract away all the intended logic, as captured in comments and variable naming, you are left with the actual logic, which will prove different if the algorithm is incorrect.

    90. Re:Gotta document that code... by RootsLINUX · · Score: 1

      Thank you for your comments everyone. I believe you are all right, I do comment too excessively in some parts of my code. (But then again, I think commenting too much is better than commenting too little). I'll keep this in mind for future code I write. :)

      --
      Hero of Allacrost, a FOSS RPG for *NIX/*BSD/OS X/Win
    91. Re:Gotta document that code... by Chris_Jefferson · · Score: 1
      He was a genius programmer

      After a few years of programming, I've come to realise a few things

      1) Debugging code is much harder than writing code. Therefore except when you have no choice you should never write code at the edge of what you can understand, as then it will be too complex to debug.

      2) Probably less than half of the purpose of coding is to write a program that works now. The rest is writing a program which can be debugged and extended later, probably be someone else.

      So called "genius programmers" usually fail both these targers, and also often fail to generate code that is faster (and in more than one case I've found their "clever tricks" could have been deduced by the optimiser of the compiler, and also confused it, so their code ends up slower), and code is useless to anyone else. I don't work with such programmers anymore.

      --
      Combination - fun iPhone puzzling
    92. Re:Gotta document that code... by Soul-Burn666 · · Score: 1

      Every medium or better compiler will optimize that kind of redundancy anyways.

      --
      ^_^
    93. Re:Gotta document that code... by Soul-Burn666 · · Score: 1

      Forget an indenting convention. Just make high quality auto-indenting software. When you recieve a source file, run it thru this program and view the file the way you want to look at it.

      Hell, even make the underlying code be some kind of XML structure, and every "editor" uses a custom "stylesheet" to view it however it want.

      An editor can be a simple text editor of some sort, or a graphic monster showing your program structure using a fisher-price like interface.

      Bottom line: regardless how the code appears NOW, your viewer can automatically re-indent to your liking.

      --
      ^_^
    94. Re:Gotta document that code... by Huogo · · Score: 1

      The point is you use a tab char, and then set your editor to show a tab as 8 spaces. So person A's tab is 4 spaces and person B's tab is 8 spaces, its just a tab for each and shows for each person how they want it.

    95. Re:Gotta document that code... by jesup · · Score: 1

      Not naming names...

      Said "genius" programmer was in fact really really good at producing working, bug-free, very fast code, and doing complex projects others had totally failed at. But (as you mention) you wouldn't want anyone less skilled than he was working on it. And that person had better be an expert at deciphering undocumented code.

      He was also the author of a very good book on x86 assembly optimization, which might explain something.

      And yes, the x = x++; was a typo.

    96. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      That's the worst reason I've ever seen!

      Edit locally, problem solved.

    97. Re:Gotta document that code... by jesup · · Score: 1
      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.
      There are actually a few reasons it's the way it is. First, the payload might not be aligned and so (given the compiler and CPU) using structure for access could fail to access the correct bit - even though it's a bitfield in a byte, the compiler will use a longword access to extract the bit no matter what you do (at least as far as I was willing to care about trying variation).

      Not to say that some of what you say isn't reasonable. However, in this code, I don't want to hide what we're doing with the bits of the structure - this is an external (wire) interface, so at this level of the code I want to be explicitly concerned with the handling of the specific bits defined in the protocol. And the event loop is at a higher level; this is part of the equivalent to IsCompleteMessageAvailable().

    98. Re:Gotta document that code... by Anonymous Coward · · Score: 0
      endTime = GetTick() - startTime;

      Perhaps elapsedTime would be a better name than endTime.

    99. 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 ;-)
    100. Re:Gotta document that code... by Dracolytch · · Score: 1

      I disagree with your comments about the API. In this example SDL_GetTicks() is not a very clear function name. A well placed comment saying what the function is really doing will let me know if I need to go to the documentation or not.

      For example:

      last_update = SDL_GetTicks(); // time in milisec

      Tells me enough about what the function does, and what kind of data it returns, that I don't have to go all the way to the API documentation.

      ~D

      --
      This sig has been enciphered with a one-time pad. It could say almost anything.
    101. Re:Gotta document that code... by Flyboy+Connor · · Score: 1
      He was a genius programmer - but wrote code that almost no one else could ever maintain.

      If he writes code no one else can maintain, he is NOT a genius programmer. He may be a genius spaghetti-writer or a genius obfuscator. But making your code understandable for others is one of the essential characteristics of a professional programmer, and a genius programmer is not exempted.

      When you look at the code of a genius programmer, you should say, "This is brilliant -- I could have never thought that up, but it clearly solves the problem in an elegant way." You should not say, "This must be brilliant because I can't understand it at all."

    102. Re:Gotta document that code... by computational+super · · Score: 1
      I've actually seen this in code: [snip]

      Hell, I can count on one hand the times I've ever seen anything else.

      --
      Proud neuron in the Slashdot hivemind since 2002.
    103. Re:Gotta document that code... by Phisbut · · Score: 1
      The best quote I've ever seen on the topic comes from Chapter 5 of the book Database: Principles, Programming and Performance by O'Neil and O'Neil:

      Tim Collin's Laws of Software Maintenance:
      First Law : Other people's code tends to look like undecipherable junk.
      Second Law : Your own code will look like someone else's code after six months.

      It's unfortunately so true... :-(

      --
      After 3 days without programming, life becomes meaningless
      - The Tao of Programming
    104. Re:Gotta document that code... by ckaminski · · Score: 1

      Someone here on slashdot once posted:

      There's never enough time to do the job right in the first place, but there's always enough time to come back and do it right the second time. Which means there's always enough time to do the job right in the first place.

      He said it much better, and it's now a wall plaque hanging on my office wall.

    105. 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.
    106. Re:Gotta document that code... by dcam · · Score: 1

      Like you, I have also had to work on code I have previously written. In fact I work on a code base that has been either originally written by me or since recoded by me. Some of the code goes back 4 years.

      This is an interesting experience. First of all I am a much better programmer now than I was then. I also know the languages better now than I did them. More importantly I now know how to code legibly in the languages I use. The code base reflects all this progressions.

      Anyway I digress. Others have pointed to Code Complete as containing good instructions on the use of comments. I'd like to echo these.

      Comments should describe why you are doing something, not what you are doing. If your code is so convoluted that it needs explanation on what you are doing, you have other problems.

      Secondly, code it is a good idea to map out sub-routines before you code them. eg // TODO: grab user list from database // begin loop through users // if user has property foo // TODO: Write user // end if // end loop

      This skeleton can be used as a basis for the comments in your code.

      Also every single subroutine should have a comment describing what it does.

      Finally there should be a lot of subroutines. Really a lot. If you have a subroutine that is longer than 100 lines of code, you should be getting twitchy.

      Above all, it is worth recognising that learning to code legibly is an iterative process. Be always looking at what you are writing and trying to find more ways to improve the way you code in that langauage. And it is important to understand that what is legible in one language might not be as legible in another.

      --
      meh
    107. Re:Gotta document that code... by sootman · · Score: 1

      All generalisms are wrong.

      And all extremists should be shot.

      --
      Dear Slashdot: next time you want to mess with the site, add a rich-text editor for comments.
    108. Re:Gotta document that code... by skraps · · Score: 1

      Your existing codebase doesn't change Fortran's POS status. Numerical calculations are typically pretty speedy in Fortran, yes. But it is still a POS. There are more modern languages that achieve the same or better level of performance, while incorporating some other cool things we have learned in the last 15 years. Sisal is a good example - a functional language that was designed for numerical computations.

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    109. Re:Gotta document that code... by dcam · · Score: 1

      I'm not a programmer by trade, but I just can't imagine that people actually debate about commenting code.

      Why not?

      This is something we do a lot of. If you are passionate about your job, and I think a lot of programmers are, then this is something you want to get right.

      I think also that a lot of programmers consider that their work is creative and that they are artists.

      As a programmer, you are also not the only person who is going to work on the code. Comments are one of the major ways of communicating information between different programmers.

      It is also something that can be done many different ways. I guess that putting those things together and you have lots of room for discussion.

      --
      meh
    110. Re:Gotta document that code... by danharan · · Score: 1
      x = x++; // add one to x
      is not the same as:
      x+=x++;
      If I understood it properly, one increments and the other doubles.
      --
      Information: "I want to be anthropomorphized"
    111. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      "He was a genius programmer - but wrote code that almost no one else could ever maintain."

      That's a contradiction. A genius writes code that is easy to maintain. That's one of the criteria for good code.

    112. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      If I don't call it pLAmount, how do I know it's a long?
      If you can't look at the declaration and remember the data type, how do you remember what any of the program logic does?

    113. Re:Gotta document that code... by Chemisor · · Score: 1

      > people who want to indent with spaces need their heads examined

      And so do people who change the tab size to anything other than 8. Tabs are sacred people! The computer is not a typewriter.

    114. Re:Gotta document that code... by gregmac · · Score: 1

      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.

      I should have been more clear on this. I agree exactly with someone else that replied to this.. in this example, SDL_GetTicks() is not a clear name. If it was SDL_GetCurrentTicks() or something along those lines, fine. But since it's unclear, my "// now" hint is enough that I don't have to spend a few minutes looking for and searching through documentation or code to find a simple answer.

      6) NEVER put actual values in comments. For example:

      Normally I'd agree with this, but one thing I sometimes do is put translations.

      update_interval = 50400; // 14 hours

      This just saves me later wondering what "50400" is.

      --
      Speak before you think
    115. Re:Gotta document that code... by Otto · · Score: 1

      If I understood it properly, one increments and the other doubles.

      While you're correct that the link he posted talks about x += x++, the given line of code in the post does not increment. x++ returns the value of x before x is incremented.

      So y = x++ would do two things: It would set y = x, and it would increment x by 1. In the end, x would be greater than y by one.

      In the case of x = x++, x would get incremented, and then it would get set back to its value before it was incremented. So x would actually remain unchanged, it would just go up one and then down one momentarily. :)

      --
      - Give a man a fire and he's warm for a day, but set him on fire and he's warm for the rest of his life.
    116. Re:Gotta document that code... by jesup · · Score: 1

      "Genius" is not synonymous with "Best"...

      ("Genius" tends to be used for people who can do things others can't, or can figure out things others are stumped by. In fact, it tends by definition to be linked to things that others will have trouble following even if they do try to document. I used the term very deliberately...)

    117. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      ... or compiler errors from Python

    118. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      Around 1980 a professor told me "Write the comments first, then fill in the code that implements them." It was the single best bit of programming instruction I ever received, and the CS professors still don't seem to have learned it (he was an EE professor).

    119. Re:Gotta document that code... by zakharin · · Score: 0

      Or you could say 14*3600 (or if the developers are dumb, 14*60*60).

    120. Re:Gotta document that code... by coaxial · · Score: 1

      The problem with mandating a tabwidth that's not the default, (i.e. move to the next column that is divisible by 8), is that a lot, and I mean a lot, of people don't know how to set their tab stobs, or even know that they can set their tabstops. On some editors, like vi and emacs, setting tabstops isn't very obvious. You can read more about it if you want.

      Yes, hellish things can happen if you're not careful. Which is why we have scripts to perform certain actions on checkin -- like checking your indentation, compiling your code, running (at least part of) the BVT suite, ...

      You're right. If you're going to enforce an indention standard, as you should as part of a general coding standard, then it needs to be done automatically as part of the build process, just like lint.

    121. Re:Gotta document that code... by Yunzil · · Score: 1

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

      I always use spaces. :)

      When I started my job out of college, the project I worked on had an indent style I would characterize as "chaotic" or "nonexistent". Some people had used hard tabs (with various space equivalents), some had used tabs + spaces, some had just used spaces. Everyone did whatever looked OK in whatever editor they happened to be using that day.

      So I decided to always use spaces, since that would always look the way I intended it

      And since my way of indenting is OBVIOUSLY the only correct way of doing it...

    122. Re:Gotta document that code... by coaxial · · Score: 1

      Every line indented to some screwy level? I have four things to say about that (since you seem to be a vi user)...

      Actually, I tend to use xemacs for coding, and vi for dashing off notes.

      1G=G ;) It has quirks but usually works quite well! Just don't expect it to work if you have perl programs that use 'print

      Now the code is fucked for the next guy. It's still a losing proposition all the way around.

    123. Re:Gotta document that code... by Yunzil · · Score: 1

      Who do you work for?

      In the real world, you get handed 100,000-line Fortran 77 apps (if you are lucky), and have to make them work. You don't get an abitrary amount of time just so you can rewrite them in whatever the current non-POS language is (which is a moving goalpost anyway). And even if you have the time to rewrite it, sometimes you can't, because the program produces some mathematical results that have only been certified for a specific set of Fortran code.

      I deal with heaps of crappy Fortran on an almost daily basis, but rewriting it is simply not an option.

    124. Re:Gotta document that code... by Yunzil · · Score: 1

      In the case of x = x++, x would get incremented, and then it would get set back to its value before it was incremented.

      Not necessarily. It's *undefined*. Meaning, the compiler can do whatever it wants to with it. For instance, I just compiled it with gcc 3.2.2 and starting with x = 3, x=x++ gave 4.

    125. Re:Gotta document that code... by Yunzil · · Score: 1

      Oh, and x += x++, starting with x = 3, return 7. :)

    126. Re:Gotta document that code... by coaxial · · Score: 1

      Those false deltas is a BIG problem, especially during merges and code inspections. Say goodbye ever being able to determine what was actually changed in the code.

    127. Re:Gotta document that code... by coaxial · · Score: 1

      No one is going to write code in XML. Hell no one likes to write XML period.

    128. Re:Gotta document that code... by AuMatar · · Score: 1

      You shouldn't be using that as a magic number anyway. Something like this would be better:

      #define SECONDS_PER_HOUR 3600

      update_interval=14*SECONDS_PER_HOUR;

      Now its obvious that its 14 hours.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    129. Re:Gotta document that code... by Soul-Burn666 · · Score: 1

      You don't write it in XML, you write it in whatever way your "editor" presents it to you.
      Just like you don't write write OpenOffice files bit by bit, but rather using a graphic user friendly interface.
      You "editor" in text mode, could show you the code in a standard programming language syntax where all your actions will be reflected in the "XML file" or whatever data structure.

      --
      ^_^
    130. Re:Gotta document that code... by fbjon · · Score: 1
      What kind of terminal gives tab!=tab ??

      And on that note, what's up with the delete becomes backspace becomes delete crap. I mean, the keyboard has looked the same for decades now.

      --
      True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
    131. Re:Gotta document that code... by anomalous+cohort · · Score: 1
      refomat all your code into the "correct" tab/space arrangement

      The problem with this approach is that when you do a diff with the previously checked in version, you will find that every line has changed which doesn't help you quickly identify the two or three lines that the previous coder really changed.

    132. Re:Gotta document that code... by Anonymous Coward · · Score: 0

      #!/usr/bin/bash
      OLD=$1
      NEW=$2
      OLD_I="$1.indente d.$$"
      NEW_I="$1.indented.$$"
      cat $OLD | indent > $OLD_I
      cat $NEW | indent > $NEW_I
      diff -ubw $OLD_I $NEW_I
      #rm $OLD_I
      #rm $NEW_I

    133. Re:Gotta document that code... by syzler · · Score: 1

      For instance I use Terminal.app on OS X to connect to my development boxes. I then use vi to edit the files scripts and source files. The terminal.app displays the "tabs" as spaces (not as the actual tab character). So when using the GUI to highligh, copy, and paste, the tabs are replaced with X spaces per tab. Note that when copying text from a local editor to the terminal, tabs are copied and pasted.

      This is not just limited to Terminal.app, Eterm under Linux and Putty under Windows do the same thing.

    134. Re:Gotta document that code... by syzler · · Score: 1

      This is not always convient or efficient. As an example, let's say I write a C program on my OS X workstation or Windows workstation that will ultimately be run on my companies Solaris servers. Every time I want to verify that the program will compile and run as expected on the Solaris server (which is about every time I finish a routine or loop statement that is significant to the routine), I have to copy the file to the remote server. Although doable, it is much easier to just develope the program on the Solaris server using SSH to connect to the shell and using cmd line editors such as vi to edit the source. With two terminals I can be editing and testing withou having to loose my place in the code. Having the copy and then compile to debug the code would be a real irritation. So spaces really do not seem all that bad. In I prefer vi to GUI editors, so even if I am writing the program on my OS X workstation, I use Terminal.app and vi to write the source. So I would still have problems with the terminal copying tabs as spaces. BTW, when I say the terminal copies tabs as spaces, I am referring to the terminal displaying the tabs as spaces which the GUI part of the OS then copies. So it's not so much that I am writing the code remotely, but viewing existing code remotely.

    135. Re:Gotta document that code... by syzler · · Score: 1

      On second thought, part of the problem may be the editor I am using to view existing code. Vi may be displaying the "tab" as 8 spaces, which is why the Terminal (IE terminal.app, Eterm, Putty) would copy and paste 8 spaces.

    136. Re:Gotta document that code... by Boronx · · Score: 1

      I'm going to bring Democracy to Brazil. Anyone who stands in my way will be crushed.

    137. Re:Gotta document that code... by idries · · Score: 1

      There are plenty of diff programs that can 'ignore white space'. IIRC even the default Source Safe diff program can do this!

  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 agm · · Score: 1

      I always prefer long variable names over short or abbreviated ones. The only exception is "i" and "j" for loop counters.

      They may take longer to type, but I'd much rather tap away at a few more keys that wonder what the variable is for. And that's when reading my own code, the problem is worse when it's someone elses code. The same applies for class properties and method names.

    2. Re:Use long variable names by The+Snowman · · Score: 1

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

      I think variable names should answer "what," not "how." As in, what does this variable represent? Comments describe how it is used. Using concise (not necessarily short) variable names make sure you can look at a variable and say "hey, that's a window handle, that other one is a user's login, etc." Variables may have more complex usage, but usually those will be classes and have their own documentation anyway.

      --
      24 beers in a case, 24 hours in a day. Coincidence? I think not!
    3. Re:Use long variable names by techno-vampire · · Score: 1

      Short or long isn't the issue. Make them descriptive. If you're calculating the rent on an office, calling it "rent" should be enough. If you have to calculate three different rents and total them, "office_rent," "computer_rent," and "copier_rent" will help you keep track of which is which. Put in as much as you need to help the next programmer know what's going on, but making them long just because you can doesn't help.

      --
      Good, inexpensive web hosting
    4. 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....
    5. Re:Use long variable names by Anonymous+Brave+Guy · · Score: 1, Informative
      I always prefer long variable names over short or abbreviated ones. The only exception is "i" and "j" for loop counters.

      I take it you don't write much maths code, then? ;-)

      There's a reason mathematicians don't write this:

      coord2 = gradient * coord1 + offset

      and they write this instead:

      y = mx + c

      The same reasoning is just as applicable when writing code.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    6. Re:Use long variable names by calebtucker · · Score: 1

      i, j, k, l, m, n, and o for me. I find i'm always writing innner-inner-inner-inner-inner-inner loops.

      --
      My sig can beat up your sig.
    7. Re:Use long variable names by bigjocker · · Score: 1

      Hey, where do you leave k???

      --
      Life isn't like a box of chocolates. It's more like a jar of jalapenos. What you do today, might burn your ass tomorrow.
    8. 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.

    9. 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.
    10. Re:Use long variable names by GileadGreene · · Score: 1

      Mathematicians, scientists, engineers, and anyone else who uses terse notation like that also spend a lot of time defining exactly what their notation means. The same reasoning is just as applicable when writing code.

    11. Re:Use long variable names by ickpoo · · Score: 1

      One thing that is very very important. Don't abbreviate variable names. Example: we have code that has a variable called ade. I don't personally know what an ade is (adjacent done edge?) and I am fairly sure that the original coder doesn't either.

      Typing a long variable is no effort, simply type the first few letters and then Alt-/.

      --
      I am not a script! .Sig?
    12. Re:Use long variable names by Fjornir · · Score: 1
      That reason might have something to do with the fact that "mx" is the implicit multiplication m*x. Wouldn't offset end up being osetf^2 ?

      Another reason might be something about how there's a long history of 'x' representing the horizontal axis, and 'm' being the slope...

      --
      I want a new world. I think this one is broken.
    13. Re:Use long variable names by Anonymous Coward · · Score: 0

      I guess that explains why I never understand their equations. They don't even bother to put comments either.

    14. Re:Use long variable names by Anonymous Coward · · Score: 0

      I sure am glad you were modded up. But I have no idea _why_ you were modded up. For me, in your example, the longer variable names are clearly the correct answer.

      You state that there's a reason why someone might do this. I'm not currently able to infer what it might be. Why don't you state it so I can have a go at shooting it down?

      If it has something to do with using 'well known' symbols in your code, I would argue that that is still metadata, and while in the mathematics context you might not be as likely to forget them, it remains bad form not to document them.

    15. 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.
    16. Re:Use long variable names by professorfalcon · · Score: 1
      There's a reason mathematicians don't write this: coord2 = gradient * coord1 + offset

      But mathematicians don't have search-and-replace, and programmers don't scribble production code into the margins of books.

    17. Re:Use long variable names by mark-t · · Score: 1
      Actually, in my experience it's alright to do this *AS LONG AS* what the abbreviation stands for is spelled out explicitly in the variable declation via commenting.

      I mean, having a variable like 'activeEdgeTable' is quite clear, but if you are using that variable everywhere, it's a lot easier to just call it aet, with a very verbose description of the variable where it is declared (not to mention being proportionally much less prone to typographical mistakes in the variable name, slowing down development time quite a bit).

    18. Re:Use long variable names by Ibiwan · · Score: 1

      There's also a reason a lot of people don't like math... any given equation looks to them about as complex as an arbitrary perl puke^H^H^H^Hscript looks to us.

      --
      -- //no comment
    19. Re:Use long variable names by Coryoth · · Score: 1

      You don't write muc mathematics then huh?

      Mathematicians will spend an inordinate amount of time and space defining what all the compact symbols they use mean. Grab any decent math paper and note how much of it involves phrases like "Where G is finite group of prime power order", or "Given two vectors in R^3 v_1, and v_2, we can...". Yes the equations are dense. That's acfter a lot of effort has been put in (usually immediately before, but occasionally immediately after) to carefully explicitly define what the symbols used mean.

      Jedidiah.

    20. Re:Use long variable names by Anonymous Coward · · Score: 0

      Even text editors have variable name completion these days, not using meaningful variable names is just stupid.

    21. Re:Use long variable names by Anonymous+Brave+Guy · · Score: 1
      Mathematicians will spend an inordinate amount of time and space defining what all the compact symbols they use mean. [...] Yes the equations are dense. That's acfter a lot of effort has been put in (usually immediately before, but occasionally immediately after) to carefully explicitly define what the symbols used mean.

      Absolutely. And if you're programming maths, then you'd better hope there's some decent reference documentation that does that detailed defintion, because no variable naming scheme is likely to be sufficient in isolation: if a function maintained by several people has 30 different variables being used in complex calculations without that, then it won't matter one iota whether they're called "firstQuantity" and "secondQuantity" or "a" and "b". All you'll get is indecipherable gibberish and a lot of bugs either way. Hence the longer variable names add no value, and just serve to make the code verbose and therefore harder to scan once you have read the docs.

      By the way, not aimed at this parent post particularly but just to head off any more knee-jerk responses, I write heavily mathematical code for a living. My work colleagues and I have heavy academic backgrounds, mostly PhDs, and our company has written and maintained well-regarded maths libraries for more than a decade. So, we do know a little about how to code math effectively. If you showed some of the AC replies around the office, you'd have to install sound-proofing to contain the combination of laughter and "Well, duh"s. :-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    22. Re:Use long variable names by Anonymous+Brave+Guy · · Score: 1
      But ... programmers don't scribble production code into the margins of books.

      Ironically, we do quite often scribble over program listings, as we try to convert the "helpful" long variable names used by some "clever" programmer a few years ago into a recognisable form using the same standard and concise notation that everyone else uses. It's amazing how many errors become obvious when you convert the implementation of a well-known equation into a recognisable form on one or two carefully laid out lines of code, rather than either writing a six-line monster full of cumbersome long names, or creating numerous temporary variables that introduce new symbols into the mix.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    23. Re:Use long variable names by p3d0 · · Score: 1

      Agreed. There are some circumstances where abbreviations are ok, but in general, for any given name, there are a huge number of possible abbreviations, and vice-versa, so it's bound to cause confusion.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    24. Re:Use long variable names by p3d0 · · Score: 1
      Well, legibility is the primary concern. For instance, I work on a just-in-time compiler, and to use the name justInTimeCompiler everywhere, instead of "jit", would make the code harder to understand at a glance.

      Abbreviations are good if and only if they make the code easier to read.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    25. Re:Use long variable names by Boronx · · Score: 1
      A variable name can only tell you what the variable is, not why you chose to make it that way.

      What do you mean? Most modern languages support pretty long variables. I'd venture to say that almost every variable definition comment could be turned into a varibale name.

      for instance:
      struct something * this_buffer_is_used_to_temporary_hold_pointer_valu es_when_swapping_elements_of_the_array;
    26. Re:Use long variable names by agm · · Score: 1

      Are you sure that's not related to how little can be written on blackboards? :-p

    27. Re:Use long variable names by p3d0 · · Score: 1
      Your example is not only patently absurd; it also misses the point. Your variable name doesn't say why you chose to write the code that way.

      Can we agree that the following variable name would be unwise?

      struct something *buffer_used_to_temporarily_hold_pointer_value_whe n_swapping_elements_of_the_array_chosen_because_al though_the_triple_xor_technique_saves_a_register_w e_have_found_that_xor_instructions_are_slow_on_som e_platforms;
      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    28. Re:Use long variable names by mark-t · · Score: 1
      I don't know about you, but my typing speed is far in excess of that of any spellchecker I've ever seen to keep up. If I had to wait for a spellchecker to finish my variables for me every time, it would slow down my typing speed by an order of magnitude.

      They are a useful tool, to be sure... especially when you can't recall the exact name of a particular identifier, but it's absured to expect to depend on it for regular coding.

  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.
    1. Re:Comments more important? by syousef · · Score: 1

      /***
      This program is intended to be the world's first fully functional artificially intelligent life form.
      When marking my assignment please realize that comments are more important than code.
      ***/

      /***
      main - Standard C main program entry point
      int argc - Standard C argument count
      char** argv - Standard C command line arguments
      ***/
      void main(int argc, char **argv) {
      /* TODO: Actually write the thing. Unfortunately I don't know how to do that, or I'd have my nobel prize. */
      return;
      }

      --
      These posts express my own personal views, not those of my employer
    2. Re:Comments more important? by thrash242 · · Score: 1

      This is completely off-topic, but your sig is freaking hilarious.

    3. Re:Comments more important? by Anonymous Coward · · Score: 0

      Score: F - main returns an int, 0 on success.

  5. huh, just like /. by eobanb · · Score: 4, Funny

    ...where comments are more important than articles.

    --

    Take off every sig. For great justice.

    1. Re:huh, just like /. by smellygeek · · Score: 1

      What articles?

    2. Re:huh, just like /. by maxwell+demon · · Score: 1

      "the" and "a"/"an".

      --
      The Tao of math: The numbers you can count are not the real numbers.
  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.
    1. Re:Perl POD Documentation by Roguelazer · · Score: 1

      Is that like RubyDoc? RubyDoc basically goes over your source code and extracts classes, functions, etc, then parses nearby comments (if present) and auto-generates nice documentation.

    2. Re:Perl POD Documentation by kuom · · Score: 1

      While there is nothing wrong with POD, I personally prefer the language-independent documentation, such as Robodoc: http://www.xs4all.nl/~rfsber/Robo/robodoc.html

      I am trying to have everyone at my office use this instead of writing a different style of comment for each language.

  7. Documentation encourages complacency of thought by Anonymous Coward · · Score: 0

    Comments can be misleading, misinterpreted, out of date, or just plain awful.

    Code is self-documenting.

    1. 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.
    2. Re:Documentation encourages complacency of thought by electricsheep7 · · Score: 1

      I second this. Provided that classes and method contracts are adequately documented, the actual code in them should be sufficiently expressive. Too much documentation tends to hide what the code actually does ;)

      Of course, I'm generally liberal with the FIXME and BUGBUG markers.

      --

      ~# su -
      fluffybunPassword:
    3. Re:Documentation encourages complacency of thought by CreateWindowEx · · Score: 1
      In fact just today I saw one sort of classic case where there was a comment indicating a problem that had lingered even though the actual problem had been fixed.

      Except for the use of comments for marking "document structure" as well as brief "overview" for more complicated modules, I view comments inline with code as being required only if something is tricky, questionable, or some other hackery. Usually the time spent commenting the actual code would better be spent refactoring it and cleaning it up.

      I think someone has a quote about code being primarily intended to be read by humans and secondarily by compilers, although surely phrased in some more clever and pithier way...

  8. obg... by Anonymous Coward · · Score: 0

    I spent a minute looking at my own code by accident.
    I was thinking "What the hell is this guy doing?"

    with thanks to bash

    1. Re:obg... by Anonymous Coward · · Score: 0

      http://www.bash.org/?6824http://www.bash.org/?6824

      apperently something went wrong with that post...

  9. 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!

    1. Re:Comment. by Fjornir · · Score: 1
      I know you qualified it with "simple BAT" and presumably by extension "simple shell script" -- so please don't think I am arguing with you... I would say however that the non-simple BAT/non-simple shell scripts need comments more than the average piece of C code, for instance.

      C is very expressive, has a number of well-known idioms, and so on... Shell scripts are generally quite terse and often more in need of commenting.

      --
      I want a new world. I think this one is broken.
    2. Re:Comment. by tsm_sf · · Score: 1

      How about this? Just keep in mind that no matter what you're writing, it's always for an audience. Like you're writing a novel, where you need to be concerned with both the structure of the story and the flow of the words.

      --
      Literalism isn't a form of humor, it's you being irritating.
    3. Re:Comment. by skraps · · Score: 1

      No offense, but could it be that your preference for comments just reflects your skill level with the language. To the programmer who wrote the program, it would seem silly to provide a lot of comments - much like it would seem unnecessary for you to comment a shell script you write.

      --
      Karma: -2147483648 (Mostly affected by integer overflow)
    4. Re:Comment. by Brandybuck · · Score: 1

      The only people here arguing against commenting are those living in their parents basement wondering why Linus won't accept their code into the kernel.

      --
      Don't blame me, I didn't vote for either of them!
    5. Re:Comment. by Malc · · Score: 1

      Personally I write my comments first, then add the code to do what they say. It's much easier to plan out an algorithm without worry about the implementation details. It's a matter of drilling down in a structured way.

    6. Re:Comment. by stealth.c · · Score: 1

      I'll certainly concede that. But when I was working on my own projects in my early CS classes, my negligence to use comments only caused me unnecessary headaches later. Comments are helpful and they don't take really any extra effort to employ. So why not? In fact, another poster said it helps outline the project right before coding it.

    7. Re:Comment. by marcosdumay · · Score: 1

      You don't use to read shell scripts, do you? Shell scripts surely need comments.

    8. Re:Comment. by Boronx · · Score: 1

      It's funny you should say that. I've dabbled a very little in "literate programming", which is actually more comment than code, and while I don't find it useful for applications, it's pretty handy for short scripts, especially if it's in an obscure language that you don't use anywhere else.

  10. Opinion... by duhasteifersucht · · Score: 1

    I think having comments in your code is a matter of preference. I find it nice to have as few comments as possible so i can read the code better.

    Obviously thats my preference, but i feel comments are optional (unless dealing with really complicated code)

    --
    cha-ching. money baby... money
    1. Re:Opinion... by LoztInSpace · · Score: 1

      I agree. Code should be pretty obvious and the use of decent names, structure etc make it so. Of course there will be some gnarly bits that need special treatment, but I tend to stick with that
      I think a more interesting discussion would be the equivalent of comments & documentation for and from non-coders such as BAs & DBAs, project managers etc.
      For example:

      UML/Class diagrams
      Data models
      Business rules
      Functional manual
      Lexicon

      All more interesting.

    2. Re:Opinion... by duhasteifersucht · · Score: 1

      i have no trouble commenting if i am coding for someone else, but im not going to have more comment then code, as people have requested in clarification of code i write. thats just really annoying to be quite honest

      --
      cha-ching. money baby... money
    3. Re:Opinion... by Anonymous Coward · · Score: 0
      ...right... Because obviously you've got some magic super power which lets you re-insert comments that were never added in addition to the "hide comments" filter that any half-competent coder could make with a regular expression in, say, 10 minutes (or two of googling).

      Fucktard.

    4. Re:Opinion... by duhasteifersucht · · Score: 0, Troll

      Or you could just be smart enough to know what the code does without the comments? tool

      --
      cha-ching. money baby... money
    5. Re:Opinion... by GileadGreene · · Score: 1

      The question is, "is the code doing the right thing?". Code alone won't answer that question. It does what it does. Comments will (or at least should) tell you what the intended effect of the code is.

    6. Re:Opinion... by BasilBrush · · Score: 1

      Where the comments and the code disagree, you don't know which represents the intention. It've very often the code that's correct and the comment that's stale. Avoid comments except for file and function header comments - the purpose of a file or function rarely changes, even if the details of the code does.

    7. Re:Opinion... by GileadGreene · · Score: 1
      Where the comments and the code disagree, you don't know which represents the intention. It've very often the code that's correct and the comment that's stale.

      Which is an example of poor code maintenance. However, at least it flags the fact that there is a problem. Is it the comment that's wrong? Or the code? While it may be that code is more often right than comments, you really don't know what the answer is in any specific instance. Automatically assuming that it's the code that's right can bite you quite badly. Better to do some research to find out, and then fix whichever is wrong. Eliminating comments won't make the problem go away. It just makes it harder to detect incorrect code.

    8. Re:Opinion... by BasilBrush · · Score: 1
      It's not poor code maintainance any more than a program with bugs in is an example of poor coding. As the saying goes no non-trivial program has ever been written without bugs in it. So why should anyone think they can write defect free comments? Comments are more likely to be wrong than code, because they are not unit tested, and comment mistakes will not will not be reported by testers. As a rule of thumb, comments are always stale, always contain errors.

      What of comments that are right, but the code is wrong? It all depends why you are asking the question. If code reviewing, the comment can lull the reader into a false sense of security that the code actually does what the comment says it does. If searching for a defect, better to look at what the code does than what the comment says it does. If reading to understand how the code works, then the use of function header comments, and functions of sensible length provide all that is needed.

      My advice to all and sundry is: Don't use comments embedded in code except in very exceptional circumstances. Describe what a function is for and it's inputs and outputs, then just write solid uncommented code with meaningful identifiers to implement it. This cuts out all the worst problems with comments whilst retaining all their advantages.

    9. Re:Opinion... by GileadGreene · · Score: 1

      Don't get me wrong. I'm not advocating commenting anything and everything. I'm just saying that there is value in comments that express intent. Apparently we agree on that much, since you are in favor of function header comments. I'm merely suggesting that there may be times where adding some comments on intent inside a function may be helpful too. All of this in response to the OP's assertion that code alone is sufficient.

    10. Re:Opinion... by EEBaum · · Score: 1

      Tinker with your syntax hilighting. You can probably make the comments in a color that is still legible, but obviously not code. This way, you can look at the program at a glance and know what it does, and have the comments there when you need them.

      --
      -- I prefer the term "karma escort."
  11. Switch from C by python_kiss · · Score: 1

    Use Visual Basic! More Comments and zero code.

    --
    Science without religion is lame. /. without me is lamer
    1. Re:Switch from C by Professor_UNIX · · Score: 1
      Use Visual Basic! More Comments and zero code.

      I know it's not cool to the Slashdot crowd, but does anyone know of a nice IDE to build GUI applications on Linux or MacOS X that's similar to VB.Net? I've found I can throw together a decent Windows interface in 15 minutes and then code all the backend functions to handle click events and such rather easily, but when I tried GUI programming under Linux you had to actually know how to call all the complicated library routines and set stuff up. I'm not a programmer by trade so no flames please, but there are times I'd like to throw a basic GUI interface on a simple program I've written without sacrificing a dead chicken. ;-)

    2. Re:Switch from C by The+Master+Control+P · · Score: 1

      I haven't used them much myself, but if you write C++ then try Qt3 Designer for the GUI and KDevelop for the code if you're using KDE for development.

      If you want to write a 3-d graphics program without having to deal with X/glx/sdl for windowing, try GLUT.

  12. development process by phloydphreak · · Score: 1

    A good development process with commented function names and function purpose as the framework for the project will assist in the coding as well as provide more than adequate commenting on a project (shouldnt code the how, only the purpose). Its workes for me in college (sr. UIUC), lets hope it continues in the business world...

    --
    "this is the gloaming"
    radiohead
    1. 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.

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

    3. Re:development process by shic · · Score: 1

      Your argument that future developers "don't even have to read the function for the code (unless they suspect the function is the source of a bug)" is fallacious for exactly that reason. Typically maintenance of code involves fixing bugs and making subtle changes... Particularly when trying to establish the cause of bugs, especially for substantial programs, the challenge is rarely to establish a fault or issue, but rather to establish the most appropriate way to rectify the problem. Your comment doesn't help me at all - it re-states in a different informal syntax, roughly what the function name implies. I wouldn't be interested in what the function "does" - that is pretty straightforward to establish from the code. I want to know _why_ this approach is taken; _how_ the feature is intended to be used by the solution as well as the pre-conditions and post-conditions (as formally as possible)
      Commenting is a religious issue. Literate programmers have a good idea - when the design is right and the structure of solution permits a linear narrative. OO refactoring proponents have a great idea when the problem can be clearly decomposed by types in such a way as to provide a natural expression of the implementation in type and method names without requiring comments.
      My own feeling is that comments are dangerous... There is nothing worse than a complex program with extensive commenting where the comments are self-contradictory. When code is self contradictory automated type-checking provides an invaluable strategy - I'm get to see any automation of this for natural language.
      My own philosophy is that mandating style independent of context is a reliable indication of cretinism. What matters is to express the solution as clearly and concisely as possible. I think it should be safe to assume detailed familiarity with the syntax and semantics of any standardized programming language - thereafter it is a matter of artistic merit. While I feel that the idea of writing code entangled with prose is an idea with extremely limited applicability - I see a far stronger correlation between the kinds of best practice for writing good prose and writing good code. For example, I see many similarities between the advice in the Economist Style Guide [http://www.economist.com/research/StyleGuide/] for writing in natural language and my own ideal for code.

    4. Re:development process by renehollan · · Score: 1
      Finally, someone that has a clue.

      The worst problem with a documentation and coding style that meets someone's arbitrary standard of completeness is that (a) the code and docs invariably mismatch and (b) the docs can very often obscure the code!

      There is nothing worse than five sets of twenty lines of code each preceeded with 10 lines of comments about what the code does!. Geez, you've now made me see 33% less code in my editor window at a time -- like that's going to make it easier to follow what it does.

      Document the why's, and, if they're particularly tricky, the hows, but otherwise butt out. In this vein Hungarian notation must have been dreamed up by Basic weanies used to seeing the type of a variable implicit in its name. Why the heck should I care about the structural implementation detail of an object? If I don't understand the object's type, I shouldn't be messing with it! (An exception can be made in cases where one works with foo, pointer to foo, pointer to array of pointers to foo, and pointer to pointer to array of pointers to foo all in close proximity, I supposed, but that usually implies that details of the data structure should be exposed at that point.

      Far too often, and this includes JavaDoc and Doxygen documentation, the documentation covers the trees and completely misses the forest.

      As for breaking up large functions... sometimes. Other times it just pollutes the function level namespace with things that are called once. It really is a judgement call.

      Document the things that aren't obvius to one skilled in the implementation language.

      For example, I recently had to deal with an object that made use of a "helper" object that was a concrete derived class of an abstract interface. Heh. Turns out the semantics and signature of that abstract interface was a close match to the top-level concrete class. Can you say Proxy? I saw what was being attempted: abstraction of some lower-level functionality used by a higher-level object, except the sole current implementation of that lower level functionality followed a model that was so useful it was reflected in the upper level object using the helper class. Kinda makes you think that the "real" lower level functionality should have been simpler-still (since it wasn't really a Proxy that was desired).

      Clearly, someone in the dim past had a good idea about abstracting multiple implementations away under a common interface, but the best interface they could imagine in the short time they had was actually that to which their existing first implementation conformed.

      From a maintenance standpoint, it meant that Berkely socket semantics (particularly extablishment and termination) extended higher into the application that initially expected. It would have been nice if that was noted somewhere. As it stood, it took a few minutes to grok that from the code alone.

      Now, I know from experience, what the original programmer was trying to accomplish, and found, to his or her dismay, that there was no time to sever the application's idea of communication establishment and termination from that of the actual first implementation at hand, and so used the latter as the model for the former. Not quite the flexibility one was hoping for... and crucual to anyone who wants to provide an alternate session establishment protocol at the lowest level: "whaddever ya do, it should map to socket semantics".

      Arguably, there was no benefit to be had from the attempt to separate application connection semantics from the primary implementation at hand, and the implied suggestion that there was, because of the abstract class involved was potentially confusing.

      A professional programmer modifying a piece of code has to deal with perhaps a dozen such questions in a day -- sometimes more, sometimes less. Sometimes, good ideas end up partially backed in code.

      That's the kind of stuff that needs to get documented, not the fact that i is a loop index, in scope for five lines of code, and should be more properly called fooArrayIndex. All those long variable names with short scopes make the program lines longer, wrap more lines, and increase program size. Sometimes the "spreading out" of the code that results does more harm than good.

      --
      You could've hired me.
  13. Fine with some comments, Don't over do it by bigbinc · · Score: 0

    I work with java, with javadocs. There is nothing more frustrating than reading a 500 line program and having the actual represent 20 lines with 480 of the lines filled up with comments. Just don't over do it. Another thing, in school they teach you, "You should comment every line". That is silly, not every line needs comments. I believe in a black box approach to your programs, if you can comment outside of the function and describe what is going on inside of the different blocks. I can't easily reuse that function if it is properly commented. I don't want to know what is going on, but if I know the arguments, the return-type, I am ok.

    --
    ---- Berlin Brown http://www.newspiritcompany.
    1. Re:Fine with some comments, Don't over do it by Anonymous Coward · · Score: 0

      I work with java, with javadocs.
      You say that first, as if it should lend you some credence.

      There is nothing more frustrating than reading a 500 line program and having the actual represent 20 lines with 480 of the lines filled up with comments.

      Here's a tip:

      egrep -v "^#" file | less

      If you don't use # for comments, adjust the cmd line.

    2. Re:Fine with some comments, Don't over do it by bigbinc · · Score: 0
      I work with java, with javadocs. You say that first, as if it should lend you some credence.

      Of course not, I can get by with the comments, I just think, we are overdoing it, when, the code base is 10 lines long, but the comments make up several 100 lines. And, I see that more with java than other languages. Python seems to be the most self documenting.

      --
      ---- Berlin Brown http://www.newspiritcompany.
  14. Comments are valuable, but good code essential by Eternally+optimistic · · Score: 1

    When you write bad code, good comments won't save you. The other way can sometimes work. Spending all your time on comments seems like only talking about solving an engineering problem, not actually doing it.

    --
    What keeps me going is my inertia.
  15. And this, my friends, is why offshore outsourcing by melted · · Score: 1, Troll

    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.

  16. 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 Anonymous Coward · · Score: 0

      I've often tried to go through my code and attempt to remember what I was thinking.
      I find though, that it really just depends on the strength/type of pot I was smoking at the time. Certains types of pot cause me to code different ways.
      Just an FYI, is all.

    2. 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!
    3. Re:Write code like someone else will maintain it by Anonymous Coward · · Score: 0

      My marijuana habit led me to become a Perl hacker for reasons like you describe. OO + sToNeD is teh fu/\/.

    4. Re:Write code like someone else will maintain it by JeffFurry · · Score: 1

      And remember, that someone else will likely be you!

      Six months from now, you'll be a different person, and likely won't remember squat about what you were thinking when you wrote a particular piece of code. Comments are useful, but they're only a part of the overall goal of clarity.

    5. Re:Write code like someone else will maintain it by DaveAtFraud · · Score: 1

      *EVERY* developer should be sentenced to maintaining someone else's code early in their career so they will understand why commenting is important.

      I have a "knack" for undertsanding other people's code. I can generally read code and understand what it does. This doesn't help me at all when I'm trying to determine what the original author was *thinking* when he or she wrote the code. Generally, the hardest bugs to figure out are those that involve broken abstractions. The code, per se, is correct but it being used in a way that breaks the developer's abstraction. I can diagnose the problem a lot faster if I have comments to help me understand what that abstraction is and what its limitations are.

      It seems like the only way people develop an appreciation for how important this level of commenting is is by being forced to try to fix someone else's sparsely commented code. They especially appreciate the irony of:

      x++; /* Increment x */

      as the lone comment in a pile of spaghetti code.

      --
      They that can give up essential liberty to obtain a little temporary safety deserve neither safety nor liberty.
      Ben
    6. Re:Write code like someone else will maintain it by rakeswell · · Score: 1

      Amen to that.

      I typically am working on at least three different projects at any time, and once I realized that I was spending a fair bit of time re-reading the code and trying to remember what I was doing and where I left off last time, I got kinda religious about writing good comments that explained, for instance, what the method does, but also the assumptions and failure states, etc.

      Since then, I've found that the modest amount of time it takes to write good comments pays off with dividends next time I pick up the code again. I also think that verbalizing what you are doing in code forces you to think about it in a different way and not infrequently, the resultant code benefits.

      --
      All one has to do is hit the right keys at the right time and the instrument plays itself. - Johann Sebastian Bach
    7. Re:Write code like someone else will maintain it by Jeremi · · Score: 1
      But if you write code you're getting paid for, or code for an organization, anything but personal stuff, write good comments.


      What, and make it easy for my employer to replace me with someone else? No thanks -- as long as I'm the only one who can possibly understand the code their business depends on, they are at my mercy...

      ;^)

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    8. Re:Write code like someone else will maintain it by Anonymous Coward · · Score: 0

      Write code like the someone else who will maintain it is a violent psychopath who knows where you live.

    9. Re:Write code like someone else will maintain it by Anonymous Coward · · Score: 0

      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.

      When I noticed that I had to do this from time to time, I started just writing what I was thinking at the time into the comments.

      So I write comments as signposts (so I can more easily skim to find the piece I'm looking for) and explanation of what thinking brought about the code. Explaining the code itself is more of a side effect of that.

      I also have syntax highlighting set so comments have a different background color, so they really stand out. 'cuz when I look at a piece of code, the comments are usually the first thing I read. And I need to be able to find those signposts easily. ;)

  17. No such thing as too many comments... by Anonymous Coward · · Score: 0

    Good organization and descriptive variable names are no substitute to actually noting what the heck you're looking for or trying to accomplish. Checking a bit flag with a nice name (such as "input_recvd") is not nearly as useful to the maintenance programmer as a comment which says "test bit flag set by keyboard input routine - "1" value indicates input complete"

    1. 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
    2. 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.

  18. Riiiiight... by Etherwalk · · Score: 1

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

    Yeah, it should be enough, so long as you're writing a very well known algorithm. Like, say, heapsort. Small functions with no side effects, good variable names and scopes as limited as is reasonable for each variable. I mean, technically, the code tells you exactly what the code does.

    Sheesh. Comments important. How important they are varies with the algorithms you're implementing. But they're important. Clear code with less commenting may be more valuable than complex code with more commenting. That's hard to call. But in the end, you have to know what code says. And if it's clear enough from the code, fine, then the code IS your comment. But that's not a safe habit to fall into, because then you have the mentality that code is always enough for a comment. This gets you into trouble. (Big trouble.) See any piece of complex C code. =)

    1. Re:Riiiiight... by Malc · · Score: 1

      A comment for every 5-10 lines of code means I don't have to read the code to understand it. My eye just scans from green line of text to green line of text. I get the gist of it very quickly. I only need to read the code if I'm looking for a bug or it doesn't seem to be behaving the way I expect.

  19. 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 Anonymous Coward · · Score: 1, Informative
      From Knuth's page:

      The main idea is to regard a program as a communication to human beings rather than as a set of instructions to a computer. Your program is also viewed as a hypertext document, rather like the World Wide Web. (Indeed, Knuth used the word WEB for this purpose long before CERN grabbed it!)

      CWEB is a version of WEB for documenting C, C++, and Java programs. WEB was adapted to C by Silvio Levy in 1987, and since then both Knuth and Levy have revised and enhanced the system in many ways, notably to support C++ and ANSI C. Thus CWEB combines TeX with today's most widely used professional programming languages.

      look it up people...

    2. Re:Not necessarily comments... by chromatic · · Score: 2, Informative
    3. Re:Not necessarily comments... by Anonymous Coward · · Score: 0

      Couldn't disagree more. Every single book I've come across (I own 3 of them I believe) that uses CWEB or something similar is total shit (okay, not total shit, but very, very annoying). I wish they would just put the whole block of code there instead of doing some sort of "hyperlink" to some other page in the book. Or maybe it's just me, I rarely ever write comments and I can a =40 line chunk of code just by looking at it.

  20. 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.
    1. Re:Something i notice by John+Courtland · · Score: 1

      Agree 100%. If you can properly modularize a program, and the function/variable names you select are self-documenting, then your only real hassle is documenting the prototype (in C at least), or perhaps a REALLY in-depth control structure that can't be broken down (and I can really only think of one example of one, and it was specifically crafted that way for speed. If anyone remembers, it was a switch statement that some guy coded at ILM that was used to OUT bytes to a custom device, and he had to craft it a specific way to make it fast enough to work, it is really sorta neat and ingenious).

      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    2. Re:Something i notice by Anonymous Coward · · Score: 0

      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.

      See, to me, that's a sign that the function is too long and should be refactored into smaller pieces.

      A comment like that per module would be more appropriate. If you have to explain your general approach for functions, then chances are you are lumping everything into a few giant functions rather than splitting the code into logical pieces.

      Once you take a more fine-grained approach to functions, you find that you have less need for comments because the function calls (appropriately named, and with appropriately named variables being passed in and returned out) are perfectly readable and state their intentions clearly.

      Obviously you still need comments here and there (like your zerg example), but your program structure should already be clear enough without you having to explain it.

    3. Re:Something i notice by ragnar · · Score: 1

      GetCustomerFromDatabase(foo)

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


      A small nit-pick... Because the data store should (in theory) be something that changes, it may not be wise to expose that in a method name. A database is fairly stable, but I've seen enough code called things like "readFromFile" that eventually read from another data source, but the name remained. It causes unnecessary confusion.

      --
      -- Solaris Central - http://w
    4. Re:Something i notice by Anonymous Coward · · Score: 0

      You're thinking of Duff's device.

      http://www.jargon.net/jargonfile/d/Duffsdevice.htm l

      It's filthy job security code. Ingenious maybe. Inappropriate certainly.

    5. Re:Something i notice by Dav3K · · Score: 1

      Amen. I test this shit, and believe me - comments have the potential to be good, if the coder takes the time to write something meaningful. Comments for the sake of commenting are a painful distraction in most cases

    6. Re:Something i notice by rgmoore · · Score: 1
      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"

      I find that this is particularly important when making bug fixes and dealing with corner cases. Those are things that you didn't consider when first coding, so somebody who looks at the code for the first time and is thinking only of the obvious cases is likely to think that they're superfluous. If you don't include a comment explaining the strange case you're dealing with, some future maintainer is a lot more likely to tear out your carefully crafted bug fix because he doesn't see the point of it.

      Comments are especially helpful when you're parsing a complicated piece of data, like text files that are supposed to be human readable. That kind of work can be essentially all special cases, so it needs more documentation. I like to include example data in my comments because it makes the code much easier to follow.

      --

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

    7. Re:Something i notice by gnuman99 · · Score: 0
      i do a lot of code reviews at work and nothing makes me happier than good comments.

      I'm sure you also noticed how the comments usually contain upper case letters at the beginning of sentences, and things like I, not i? :)

    8. Re:Something i notice by Kjella · · Score: 1

      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.

      Well, on the first point I think that's extremely unlikely. More often than not, I find that most of my non-trivial functions call on utility functions like Convert::fooToXML( foo ), Settings::readEntry( "foobarsetting" ), Search::Match( search , foo.attribute ) and so on. Basicly, unless you know which utilities functions to use, the code will be long, stupid and buggy.

      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"

      Just to nitpick: i.e. = id est = that is, e.g. = exempli gratia = for example. I don't think your coworkers would be too happy if you literally put "we have to do this because zergs are sensitive" before every inobvious code segment ;)

      Kjella

      --
      Live today, because you never know what tomorrow brings
    9. Re:Something i notice by John+Courtland · · Score: 1

      I don't think it's bad. You have to remember that he wrote that a long time ago, he didn't have tons of processor time to blow on making pretty code. Some of the crazy ass tricks programmers had to use to get the most out of their 4MHz machines would make most current programmers flee in terror. Pussies :p

      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    10. Re:Something i notice by Anonymous Coward · · Score: 0

      I also notice something. You capitalize only function names :)

  21. Doxygen by Umbral+Blot · · Score: 1

    The last word in documenting your code is doxygen. Especially the @author tag so you know who to yell at. I find that keeping individual functions short and then documenting what each one is supposed to do / take as parameters / return is better than comments within large blocks of code. What I hate though are large blocks of commented code. I guess sometimes the developers is too timid to remove old code, but seeing them always makes me wonder if the new code really works, and if so why is the old code still there.

    1. Re:Doxygen by p3d0 · · Score: 1
      What I hate though are large blocks of commented code.
      I hope you meant commented-out code. If so, I agree. The code is no place for archaeology. That's what revision control is for.
      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    2. Re:Doxygen by 2short · · Score: 1


      I can't stand Doxygen. Every single time I've dealt with someones Doxygen documented code, the resulting docs have been quite extensive, to be sure. But they don't contain any more information than a header file, and it's in a less useful format. I realize it is probably possible to use it right and have it be wonderful, and maybe that's what you do, but I've yet to see it happen.

  22. News? by Anonymous Coward · · Score: 0

    Maybe in 1970, but nowadays commenting is so ingrained in the coding process that code review and similar activites don't even start unless the code has sufficient commenting. This article is really only relevent now for start-ups were coders are not necessarily answering to any company guidelines, but any decent start-up knows they need a decently commented code-base (look at any of the successful open source projects out there).

  23. A rule of thumb... by pdbogen · · Score: 1

    But impossible to follow, is this:
    Only comment the things that are hard to understand. The problem here is that you probably understand everything you're writing.

    One way out might be to have a less-talented programmer give it the once over, and point out anything s/he didn't understand, for you to comment upon.

    That, and as Dr. Stroustrup (Bjarne) said in class today, your code constructs should be directly analogous to what they are trying to describe in real life... But I guess this goes down to self-documentation.

    1. Re:A rule of thumb... by winkydink · · Score: 1

      Yes, knowing what to comment is a challenge. When I am actively working on a piece of code I find that I know it almost intuitively and comments are unnecessary. It's only when I go back weeks or months later to work on it again that I find the comments would have been helpful. Once I stumble through it a second time, I usually end up figuring out where the comments are needed. :)

      --

      "I'd rather be a lightning rod than a seismometer." -Ken Kesey

  24. My thoughts.. by LordZardoz · · Score: 1

    I would say that reasonably well written and organized code does not need extensive documentation for you to come back to it later and maintain / extend it.

    I would also say that such code by its self is totally inadequate if someone other then your self needs to come along and maintain / extend that code.

    The real problem is not code in general, but code written under an immediately approaching deadline. I am in the ass end of a crunch that has gone on a bit longer then anyone would have liked it to. Code written this time last year is still pretty good. But code written in the last few months is pretty rough from a long term maintainability standpoint.

    Therefore, I suggest this:

    When writing new code, make it self documenting, and comment at your discretion.

    When fixing bugs frantically in the ass end of the project, Comment extensively.

    END COMMUNICATION

  25. dont be lazy by mrterrysilver · · Score: 1

    people don't comment code for two reasons:

    1. they're in a rush
    2. they're lazy

    if you're being lazy then stop. add some basic comments which will help someone else, or even yourself when you come back to the code in the future. long names help but they aren't enough.

    if you're in a rush then you probably should have started sooner. try to get more time if you can. if you rush thru the code now you're going to be in even more of a rush later with all the time you waste when you come back to your old code and have to painstakingly work your way it.

    --
    -mr silver
    1. Re:dont be lazy by archnerd · · Score: 1

      Commercial programmers should _always_ be in a rush. Time is money, and in software that becomes painstakingly clear. Good programmers are worth much more than you pay for them because they can write clean code quickly. High-level languages like Ruby are a godsend because you can get things done 10 times as quickly, meaning you can get them done 10 times as cheaply.

      General rule: good code is self-documenting. Code which requires comments can probably be rewritten so that it doesn't. If it can't be, think about whether you're going about the problem properly to begin with.

  26. it depends by joel2600 · · Score: 1

    if you're doing projects for work you'll tend to come under fire for taking too long and not meeting deadlines on time because you're taking all the necessary time to spend commenting, but then later on when you have to review your project to make additions or have someone else do the work you come under fire for not having spent enough time commenting
    it's a real catch22 situation. plus since it's for work, having it commented or not really doesn't make much difference... at least to me.

    1. Re:it depends by swimmar132 · · Score: 1

      Comments don't take hardly any time to write. No clue what you're talking about.

  27. Yeah, I love comments in large codebases by Anonymous Coward · · Score: 0
    Especially the ones like
    /*
    * WARNING - TRULY DISGUSTING HACK!!!
    * Remove this ASAP after the show.
    * Sorry, -mike.
    */
    and you determine the checkin date was 1998.
  28. Are you writing COBOL? by jackb_guppy · · Score: 1

    There is a reason for COBOL.
    There is a reason for C.
    There is a reason for ASM.

    Why cross the bound and use the worng one for wrong reason?

    Comments ARE NEEDED to help understand "paragraphs" of code. Like the use of a subroutine or why the program got this point in processing.

    Using variables like comments does not make the code easier to understand unless you are using COBOL.

    Writing code like a(i++) =+ b(--j); does not make understanding easier. Nor always makes code run faster.

    Writing comments like MOV AX,BX ; move AX to BX
    makes the program more self documenting.

    So in the end. You are mostly right. Adding comments where they are needed and ARE MEANINGFUL make future maintenance easier.

    Now if only the next guy that fixes the code will actually REMOVE unneeded code and COMMENTS and place new correct ones in thier place.

    1. Re:Are you writing COBOL? by Anonymous Coward · · Score: 0

      Your first example is hideous and deserves no documentation. It should be torn apart and possibly commented.

      The second, though... why would you comment something that simple? Maybe comment a block that contains that statement but not the statement alone. Individual comments should be reserved for lines that need explanation or that may noto be self-apparent. Still, comments for chunks of code, or even functions, should dominate because without a general understanding of the approach being taken the reader has much less chance of understanding the whole chunk.

      Write so that things are self-evident, or that are a special case where a formula or statement can be used by itself. Document chunks of code from large to small so that the reader understands how you are tackling the problem (assumptions are important). As you document smaller chunks of code ask yourself if you could write it so that it would take less mental effort to understand, while still working correctly. Only coimment individual lines when absolutely necessary and when doing so make sure that you're not trading off comments for raw readability.

      Having said that, not a single program I've coded has even come close to fulfiling the above suggestions so it's probably all bullshit :)

  29. 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 Anonymous Coward · · Score: 0

      Only as the size of the program approaches infinity.

      I agree that the original poster was probably serious. The longer a variable is in scope, the more precise it's name needs to be.

      If you really have a gigantic program, any global variables should have pretty damn long names, both to avoid name conflicts, and to explain what the hell they are since they're not going to make sense in context without a completely clear name.

      Ideally, you wouldn't have very many globals.

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

      You're partially right.

    5. Re:Nah by mazarin5 · · Score: 2, Funny
      int main()
      {
      unsigned char ucGlobalVariableNamesShouldBeReallyLongEspeciallyI fTheyAreImportantAndYouNeedToKnowExactlyWhatTheyDo AndYouDontReallyFeelLikeUsingProperCommentsAndJust RetypingAReallyLongNameLikeThisIsSoMuchMoreConveni entAndGodForbidYouShouldMakeASpellingErrorLetMeTel lYouHowFrustratingThatCanBeAnywaysImRamblingBackTo ThePointWhichIsThatSuperLongButDescriptiveVariable Names = false;
      return 0;
      }
      --
      Fnord.
    6. 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."

    7. Re:Nah by Anonymous Coward · · Score: 1, Interesting

      #include <stdlib.h>

      /* global variables */
      int ix;

      void some_small_function() {
      char slartibartfast;

      ...
      }

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

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

    9. Re:Nah by Odocoileus · · Score: 1

      One can also use a thesaurus to give fancier names to variables with larger scope.

      --
      ...
    10. Re:Nah by Anonymous Coward · · Score: 0

      Shouldn't that be void f()?

  30. Middle ground anyone? by Transcendent · · Score: 1

    How about, comments for some, no comments for others!

    But seriously, only comment what's complicated... anything easy (to other programmers, not just you) doesn't need to be.

    I knew a guy who did pre-comments, where he would write out the steps for the loops, showing nesting and such before actually writing the code. It worked pretty good because you had an overall idea before you started digging through code.

  31. 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."
    1. Re:Joel on Software by Schwarzchild · · Score: 1
      "It's harder to read code than to write it."

      Yeah, exactly. That's why every frick'n programmer in the world *thinks* that other people's code is crap. It may be true some of the time but it's not true all of the time.

      --

      "sweet dreams are made of this..."

    2. Re:Joel on Software by DerelictMan · · Score: 1

      I know what you mean. I have a coworker who looks at my code and always whines like "Waaaa, this is too complicated!" and "Ho ho ho, what is this crazy stuff, I can't follow what you're doing here..." and so forth. He's much more of a straight ahead procedural guy and I tend towards the OO style. He agrees that my approach is probably more maintainable as requirements are later added to our programs (we work in a company where our initial specs are often scribbled on a cocktail napkin, if they exist at all), but he thinks it's a problem that my code isn't immediately transparent to him the first time he looks at it. To which I always respond "Reading code is hard!"

      I think it's also a skill you can improve, somewhat separately from writing good code (although they do go hand in hand). I started out mainly by modifying and supporting existing code written by others, and it always takes me a while to wrap my brain around someone else's stuff, but the more I did it the easier it became. But even still, it always requires effort. I guess that's why they call it "work". :)

    3. Re:Joel on Software by Anonymous Coward · · Score: 0

      Yes, to read code is harder, that's why i comment every line of code with a line comment, in an narrative style, that way people ignoring the problem or even the language can understand what's going on at every step.
      It's not easy, as you have basically to 'rewrite' the code trying to explain to another one what you are doing, and have a high maintenance cost, but code lasts understandable for a long time.

    4. Re:Joel on Software by Anonymous Coward · · Score: 0

      You do realize if I got your code I would probably throw it away - the cost of time to review all your comments and keep up your coding style would be more than to rewrite the code you created. Especially since a comment-per-line style will usually slow someone down to a glacial pace; chances are the amount of code will be insignificant.

    5. Re:Joel on Software by Symbiot · · Score: 1

      It's harder to read code than to write it. That depends entirely on the code itself. Well written code is much easier to read than to write. The real reason that people rewrite other people's code is that it's much more gratifying to write code than it is to read it

  32. 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?

    1. Re:What are programming languages for? by TigerNut · · Score: 1
      Comments in the code are for explaining WHY you did something, not for repeating what you did. If I choose to use a quicksort for some task, and there is a technical reason not to be using a heap sort even though on the surface it would appear to be better that way, then I can put that in comments and five years down the road I or my peers won't make a dumb mistake by swapping out the sort mechanism on a whim.

      The other reason for putting in 'why' comments is that doing so might spark some critical thinking in your or your peers' brains down the road (even the next morning), and as a result you'll fix what you did before the product gets to the customers.

      --

      Less is more.

    2. Re:What are programming languages for? by mabinogi · · Score: 1

      > Why on earth do we even have commenting?
      Because sometimes it's more important to see what we're thinking, than what we're doing.

      Authors make notes, word processing documents, spreadsheets, etc. have annotations - pretty much any situation in which the project you're working on will need to be revisited or looked at by someone else is one in which comments or annotations that do not affect or appear in the final product are useful.

      --
      Advanced users are users too!
    3. Re:What are programming languages for? by Laser+Lou · · Score: 1
      Why on earth do we even have commenting?

      weNeedToCommentOurCodeToExplainWhatItDoesJustLik eWeNeedToExplainToOthersWhatWeSayOrWriteWhenItsNot SimpleAndClear = true;

      --
      No data, no cry
    4. Re:What are programming languages for? by Junior+J.+Junior+III · · Score: 1
      The instructions to the computer may well be human-readable, but they don't necessarily explain the WHY of the instructions. Sometimes a little meta-information can provide necessary background.

      If you don't believe me, consider the following two sets of non-computer instructions, one commented and one not:

      Without comments:
      Move two steps to the right.


      With comments:
      #You are standing on railroad tracks, and a train is coming.
      Move two steps to the right.


      You might think the first instruction is not all that important, and might well ignore it. If you've got the comment, you'll know better than to take that line out!
      --
      You see? You see? Your stupid minds! Stupid! Stupid!
    5. Re:What are programming languages for? by russellh · · Score: 1

      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.

      This is true. Ideally, you're right. The answer to your question is that we use general-purpose programming languages. Special purpose programming languages let you use the minimum amount of code for the task, like, for instance, in applescript: tell application photoshop to print "my document". There ya go. Write that in C and you'll need a whole lotta comments. One of the ideas behind OO (from smalltalk) is that the protocol (interface) to an object, defined by its class, acts as a kind of lanugage to try and get your program statements closer to the actual problem. So write your code with that in mind. But still, it's far away. IN THE FUTURE... there may be easy ways to combine a hundred little special purpose languages that minimize the amount of management code, code that is not exactly for the problem at hand. This is no monumental failure of C or high level languages. It's just that they're general purpose.

      A quote that has been attributed to steven wright: I went into a general store and they wouldn't let me buy anything specific.

      --
      must... stay... awake...
    6. Re:What are programming languages for? by eraserewind · · Score: 1
      the language and its syntax should make it obvious what needs to be done.
      Comments are part of the language syntax last time I looked.
    7. Re:What are programming languages for? by allanc · · Score: 1

      "Combine a hundred little special purpose languages"?

      Sounds like Perl.

      Didn't work.

    8. Re:What are programming languages for? by russellh · · Score: 1

      Sounds like Perl.

      Didn't work.


      Perl inherited the splendor of sed, awk, etc. That's what it is. If you want to do anything besides text processing, you're going to write lots more perl than you would with a language that's created specifically for your task. In an ideal world.... the use of perl would be limited to exactly what it's great for - then it would have no need to become a beast and offer every feature under the sun. Same goes for every language... and in an ideal world, they could easily be combined. languages would not be monolithic entities, but one would work with task-specific features and syntax, yet sharing heap data and stack frames, etc.

      I agree that it doesn't work in perl.

      --
      must... stay... awake...
  33. You're Right by B4D+BE4T · · Score: 1

    As one of many, many people coding a very large software project, I have come to realize just how important comments are. My job is to test various pieces of code. Often the code is very poorly documented and I may end up spending days just trying to figure out how the code works. Even longer tracking down the bug(s) in it. If the person who wrote the code in the first place had bothered to comment it, I would spend A LOT less time (maybe no time) trying to figure out how the code works. But, since they skimped on comments (saving them a few hours), I'm left spending days working on the code, which costs the company a lot more in the end.

  34. I don't typically comment code... by i.r.id10t · · Score: 1

    .. but then I'm the only person that does anything with it really. But, I think these guys have the solution if you have a boss wanting the comments for true.c :

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

    --
    Don't blame me, I voted for Kodos
  35. 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 iplayfast · · Score: 1

      Now that sounds like the voice of experience. :)

    2. Re:New Techniques and Better Programmers. by steve_vmwx · · Score: 1

      Right on X.

      Give me a comment that says *why* you're doing it... not *what* you're doing.

      S

      --
      Forget the truth. Science is fact.
    3. Re:New Techniques and Better Programmers. by GileadGreene · · Score: 1
      "Intent Oriented Programming"

      Now that's a programming fad I can wholeheartedly support! And a buzz-phrase I'll be busy propagating in the near future. :)

    4. 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.
    5. Re:New Techniques and Better Programmers. by Coryoth · · Score: 1

      This is why I like Design by Contract so much. If you've got a set of axioms describing exactly what the function is supposed to achieve - well the body is less important, any implementation that does an efficient jo is good enough. If contratcs are well written (like they ought to be during the requirements and specification phases) but the code is a mess then it can be rewritten, and as long as the new fulfills its contracts it doesn't matter.

      There's lots of ways to to DbC. Eiffel is one of the more well known ones (more well known for doing DbC) but there's DbC add-ons for Java, and Python, D supports it, as does SPARK (SPARK pretty much relies on it).

      Jedidiah.

    6. Re:New Techniques and Better Programmers. by EEBaum · · Score: 1

      As the person who usually comes along later and spends hours cataloging variables in a 500-line function with oodles of legacy code, just to find out what the function does, I wholeheartedly agree!

      --
      -- I prefer the term "karma escort."
    7. Re:New Techniques and Better Programmers. by Rick+and+Roll · · Score: 1
      ...or how about

      Intent-Driven Programming

  36. It depends on who is reading it by peldrake · · Score: 1

    The amount of commenting necessary depends on the level of experience of those who will be modifying the code later. Experienced programmers will be able to figure most of the flow of the program (and therefore the pieces) fairly quickly, whereas junior programmers will require explaination.

    1. Re:It depends on who is reading it by CharlesEGrant · · Score: 1
      I disagree. The 'flow' of the program should be made clear by clean, consistently formatted code. However, the 'why' of the program can remain obscure no matter how experienced the programmer or how well formatted the code. That (in my opinion) is what the comments are for.

      As an example, two or three times now I've come back to code I'd written years ago, and found some incredibly lame paragraph of code that seemed to do things in a very roundabout way. The structure of the code was clear, so I promptly re-wrote it to be more straightforward and efficient. Things immediately went to hell, and after hours of struggling, I re-discovered what had prompted me to write the lame code in the first place: a bug in an API call. If I had just inlcuded a comment that said (at the least)
      // Warning - this code works around a known bug in the
      // FooBar() call
      I could have saved myself several hours. I actually had put comments in the code, but they were the useless sort like: "loop over all instances" or "test for valid pointer".
  37. 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

  38. Context by spamspamspamspam · · Score: 1
    Comments give variables / methods / objects context.

    intYear
    is a reasonable choice of name for an integer variable denoting a year, but the year of what???

    When code is first being written, the context is in the coder's head and everything is crystal clear and obvious. However, remove that immediate knowledge of the code, and the name intYear becomes far less descriptive.

    Short of using 80 character variable names and destroying readability, you need comments to provide context so that the meaning of the value stored in the variable requires no interpretation. The same applies to methods, objects, etc.
  39. Do what I do by kushboy · · Score: 0

    Just write your whole program in comments.

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

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

    UsngShrtCmtsIsOftNotEnghAsOneMyNdToReWrtShtInTheFt r.

    1. Re:Uhh... by Soul-Burn666 · · Score: 1

      And that's why I hate hungarian notation ^_^

      (yes yes I know that's not what he was trying to achieve)

      --
      ^_^
  42. 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 claar · · Score: 1

      Write short, orthogonal functions and you'll see your need for heavy commenting go away along with the need for long variable names.

      How do you learn to do this? What makes a function orthogonal? I see a lot of professional code with very logical, small functions; but I always end up with many longer functions in my code.. I guess there's no substitute for experience..

      --
      I'd give my right arm to be ambidextrous...
    2. 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.

    3. Re:The problem isn't lack of comments by yagu · · Score: 1

      I'm willing to bet if you had a room full of 100 programmers and told them they needed to write orthogonal functions you'd get a bunch of blank stares, and some snickering too. WTF is an orthogonal function?, and, should they be orthogonal AND normalized? LOL, when programmers start acquiring mathematical hubris we're in trouble. (I've orthogonalized and normalized n-space vectors, and systems, but the abstraction for functions seems odd, and high-browed.)

    4. 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
    5. Re:The problem isn't lack of comments by cjwl · · Score: 1

      Well said, glad I'm not the only one.

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

    7. Re:The problem isn't lack of comments by Anonymous Coward · · Score: 1, Insightful

      This is something that I learned how to do from Forth. Break your problems into little itty bitty bite-sized pieces and you'd be amazed at how much you don't have to comment. With good function names, their behaviors often become self-explanatory. Another tip: use few (and ideally no) variables besides the inputs to the function, and nest your function calls. This works best when you are not using a language with atrocious syntax like C or C++, but I digress :-)

    8. Re:The problem isn't lack of comments by Anonymous Coward · · Score: 1, Informative

      Orthogonal functions are those that do not overlap in functionality. Then all your operations on data sets will be composed of distinct function calls that won't require rewriting when you need to do something different to the data. Writing a "Sum accounts and sort by name" function is bad, writing a sum function and a sort function and using them in the right order is the correct way to do things.

    9. Re:The problem isn't lack of comments by starwed · · Score: 1

      What makes a function orthogonal? They're orthogonal when their inner product is zero.

    10. 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.
    11. 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
    12. 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
    13. Re:The problem isn't lack of comments by beavis88 · · Score: 1

      Sorry, remove the trailing slash for correct wikipedia link...

    14. Re:The problem isn't lack of comments by edwdig · · Score: 1

      Looking at your examples, I'd say the PHP example is the easiest to understand, followed by the Java.

      All of these examples require being familiar with the storage manager to understand, but ignoring that, you can pretty much just read out loud the PHP version of the code and it'll make sense. The Java would be almost as clear, with the main difference being the for loop syntax isn't as clear (is it even valid? I've never seen loops like that in Java).

      But for the Smalltalk version, honestly, I can't make any sense out of it. Even though I know what it's supposed to do, I don't have a clue why it does it.

    15. Re:The problem isn't lack of comments by emurphy42 · · Score: 1

      Okay, that produces a working link, but it's discussing "orthogonal functions" in the mathematical sense rather than the programming sense.

    16. Re:The problem isn't lack of comments by gomoX · · Score: 1
      Smalltalk looks really concise, but not clear at all to me (not being familiar with the language). PHP is as crappy as it gets, Java is a bit too verbose for me.
      Python:

      def sumResults(id,managerName):
      sum = 0
      results = Managers.getManager(managerName).getStorageMethod( ).getResultsById(id)
      for each in results:
      sum = sum + results
      return sum

      --
      My english is sow-sow. Sowhat?
    17. Re:The problem isn't lack of comments by kigrwik · · Score: 1

      Actually, it is common enough that "sum" is a function that does exactly that.

      So you would just write "return sum(results)" and be done with it.

      Python rules !

      (Note that I believe it works with other types of sequences (even pure iterators) and on types with overloaded "+". Python definitely rules...)

      HTH,
      kig

      --
      -- don't discount flying pigs until you have good air defense
  43. Comments are only as good as its writer by Anonymous Coward · · Score: 0

    A story I heard from a coworker; some years back he worked as a coder for a school district in the state of New York.

    He had a cow-orker who despite not knowing dittly squat about coding managed to got himself hired as a coder.

    Knowing the said cow-orker is incapable of writing a single line of code, he and his OTHER coworkers had this git write the comments for their code instead.

    Some time later the cow-orker left on his own accord and his replacement arrived. Their advice to this newbie was "Don't worry about the comments, they're all wrong."

    Moral of the story, the comment is only as useful as the person that wrote it.

  44. Comments are for feebs! by Anonymous Coward · · Score: 0

    If it was hard to write, it should be hard to understand!

  45. Comment first, code later by Knetzar · · Score: 1

    One way I've found to write well documented code, is to first write very general pseudo code, then for each block of pseudo code write really code (or a function).

    So my code starts like: //initialize the variables //Execute the operation 1000 times //generate output //clean up //return

    And each of those lines can either become a function, with more documentation within, or a small block of code.

    This not only helps to force me to document (which I hate to do) but it allows me time to think of the algorithm that I wish to use, instead of the nitty gritty code.

    Also, don't forget to liberally use whitespace. Separating blocks of code with newlines is an easy way to help people read your code.

  46. Remove Comments by mfh · · Score: 1

    Now if only the next guy that fixes the code will actually REMOVE unneeded code and COMMENTS and place new correct ones in thier place.

    I've found old comments in my PHP codebase before and sometimes they throw me off. To make a habit of deleting them when you're deleting old code can be tough. There is no way to distinguigh between old comments and new ones either... because all comments look the same.

    Maybe it's time for XML to save us all?

    --
    The dangers of knowledge trigger emotional distress in human beings.
    1. Re:Remove Comments by 2short · · Score: 1

      I'm not actually a lots-of-comments fan in general. I like comments when code is not easily understandable without them, but that should be rare. But anyway, I was replying to mention something relevant to your old/new comments issue:
      I learned a truly awesome habit from my boss a my first programming job. Anytime I'm starting out in a new programming environment, one of the first things I do is set up a macro so that with one keystroke I can generate the start of a one-line comment, my initials, and the date. I may not go in for a lot of comments when writing new code, but when I modify old code, for each change I hit that macro and type in a quick explanation. So at least you'll know it was me that broke your code, when I did it, and what the hell I was thinking.

    2. Re:Remove Comments by mfh · · Score: 1

      Anytime I'm starting out in a new programming environment, one of the first things I do is set up a macro so that with one keystroke I can generate the start of a one-line comment, my initials, and the date.

      This is a great policy. I like it. :-)

      But doesn't it get a little dirty with all the revision comments? Sometimes I think code should be self explanatory... other times your approach would help.

      Crimson Editor lets you change comment colour. I just changed mine to the same colour of the background (white) and now I don't have to look at them. Problem solved. When I need to read comments, I'll switch the colour back to a nice shade of green!

      --
      The dangers of knowledge trigger emotional distress in human beings.
    3. Re:Remove Comments by 2short · · Score: 1


      It can get a little dirty, but this is just for changes after code is "done" the first time, so mostly bugfixes. If the number of these is going to get terribly dense in any particular section, it's more likely I'll have ripped the whole thing out and rewritten it (while swearing).

      Actually though, we've recently switched to using Subversion. The Tortise SVN "Blame" report shows the who and when for every line in the source (or charachter for that matter). So the importance of these comments is somewhat diminished. I still use them when apropriate, to provide the "why", and because sometimes it's nice to be told that some code is an after the original writing modification even if you don't think to wonder. So I still use them anytime I think to myself "Nobody could have really wanted the original behavior, so it won't break anything to change this"

  47. Quality of comments by SamMichaels · · Score: 1
    Sure, commenting is really important...especially for team projects. But you might as well make them quality comments. For example:
    sam@dexter linux $ uname -a
    Linux dexter 2.6.11-gentoo-r6 #1 Tue Apr 19 15:54:33 EDT 2005 i686 AMD Athlon(tm) Processor AuthenticAMD GNU/Linux
    sam@dexter linux $ grep -ir " shit" . | wc -l
    44
    sam@dexter linux $ grep -ir " fuck" . | wc -l
    57
    sam@dexter linux $ grep -ir " sco " . | wc -l
    82
    sam@dexter linux $ grep -ir " microsoft" . | wc -l
    168
    1. Re:Quality of comments by Anonymous Coward · · Score: 0

      From the Linux kernel: /* Fuck. The f-word is here so you can grep for it :-) */

    2. Re:Quality of comments by TCM · · Score: 1

      How mature, really. Let's try for the NetBSD source: Some occurences of " fuck" in games/fortune/datfiles/, understandable since these are quotes and not code comments. Some are in share/misc/acronyms/, again not code comments.

      In fact, the only occurences of " fuck" that are actually comments on code are in the gnu/dist/ subtree. Surprised? Me?

      Grepping for " shit" reveals files in mostly the same locations as above, except for the following:

      crypto/dist/openssl/CHANGES: *) Deal with irritating shit to do with dependencies, in YAAHW (Yet Another
      dist/ntp/ntpd/refclock_msfees.c: /* Oh shit. Just close and return. */
      dist/tcpdump/print-isoclns.c: max_area = 3; /* silly shit */
      dist/tcpdump/print-isoclns.c: id_length = 6; /* silly shit again */
      doc/CHANGES.prev: ethernet: fixed the amazingly shitty ethernet performance with cheap
      sys/netiso/if_cons.c: case 0x47: /* CUG shit */
      sys/netiso/if_cons.c: case 0x41: /* bilateral CUG shit */

      Looks like there's much more frustration going on when coding for Linux *snicker*

      --
      Of course it runs NetBSD. BTC: 1NT7QvbetmANwaMzhpVL6
  48. Short, descriptive variable names Vs... by iKaz · · Score: 1

    Short, descriptive variable names Vs well commented code are good to keep your employer dependent on your services since someone else that is forced to work on it will probably just wind up re-writing your code in the end to save time.

  49. The Trouble with Comments... by Who+Man · · Score: 1

    Is that they often end up not matching the code.

    I admit that I'm lazy and that's probably the biggest driving force behind not doing a lot of comments.

    But, I find that fellow developers who do comment heavily end up doing this: they write some great code along with some great comments. Then the code is refactored about 20 times, and the comments end up completely out of sync.

    And I find this code far more frustrating than uncommented code with meaningful variable names and small functions with meaningful names.

  50. He's right by fallendove · · Score: 1

    I agree. Thefor documentation.

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

    1. Re:Raskin by Profane+MuthaFucka · · Score: 1

      Mr. Raskin's last words were: "If I ever meet L. Ron Hubbard, I'm going to KICK HIS ASS!" Good to see that he's making headway on that goal.

      --
      Fascism trolls keeping me up every night. When I starts a preachin', he HITS ME WITH HIS REICH!
    2. Re:Raskin by Anonymous Coward · · Score: 0

      I heard Stephen King recently passed away too...

    3. Re:Raskin by bjb · · Score: 1

      Bad commenting on the publisher's part, eh?

      --
      Never hit your grandmother with a shovel, for it leaves a bad impression on her mind...
  52. Comments as entertainment by syynnapse · · Score: 1

    Somtimes its just plain old fun to read what people wrote in comments because you actually can get some insight into what was going on... its less formal than output.

    seeing other's code-in-progress is always reassuring when there are things like:

    /*good lord do i hate this effing function!
    please god just make it wooooooork!*/

    makes me feel not so alone.

    as for variable names, when I was in my first comp sci class, I used to name variables obscene things (I was in highschool), which I thought was dandy until I realised that I'd have to go back and change everything so I could submit it to the instructor.
    sigh..

    --

    System.out.println(syynnapse.getSig());

  53. Dude... by Anonymous Coward · · Score: 0

    "comment should be the default, with a way to signal the occasional lines of code."

    Where do you work?

  54. Jef Raskin by veg_all · · Score: 1

    A swan song by one of the designers of the original macintosh, sadly deceased.

    RIP

    --
    grammar-lesson free since 1999. (rescinded - 2005)
  55. 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.
    1. Re:Indeed by el-spectre · · Score: 1

      I'm forced to maintain some old ASP stuff, and occasionally I have to do just hideous things to make the crap 'language' that is VBScript work... so my code often contains comments like:

      'hack, hackity, hack...

      'ugly, I know

      'sorry, I didn't write the damned language...

      --
      "Faith: Belief without evidence in what is told by one who speaks without knowledge, of things without parallel." - A.B.
    2. Re:Indeed by Anonymous Coward · · Score: 0

      Ditto that, except
      s/ASP/PHP/

    3. Re:Indeed by Anonymous Coward · · Score: 0

      Reminds me of a spaghetti-JSP with a pile of pages-long if-elses and try-catches. At the start of it was a

      try {

      at the end

      } catch(NullPointerException e) { %>
      Something was null
      % }

      I suspect the original coder was not having a good day.

    4. Re:Indeed by Soul-Burn666 · · Score: 1

      Refer to a classic

      --
      ^_^
  56. code first, then comment by KalvinB · · Score: 1

    If you need comments to understand your own code, then your code is sloppy and you should fix that problem first. Writting sloppy code is like having bad handwritting. Fix your handwritting. Comments get out of date and are a topic all their own. Someone who writes sloppy code will probably write sloppy worthless comments as well.

    You should also code first because you know what a function is supposed to do. When it does exactly what it's supposed to do then comment it. Otherwise your comments will be more along the lines of wishful thinking and lead to more confusion.

    You should understand the language well enough that you can keep in your head everything the code is doing and if not, understand the language well enough to be able to read the code to see what it's doing. Comments are not going to help you debug a function. You need to be able to read the code itself to be an effective debugger. Only once it is debugged can you confidently place in comments that say what the function does. Otherwise, it's just wishful thinking.

    The most commenting I do before writing a function is a rough outline of the steps the function needs to go through. Only after the function is done and does exactly what it's supposed to do, do I comment it.

    I've gone back to code (thousands of lines) I wrote in BASIC 10 years ago and can understand exactly what's going on despite there being no comments. Same with stuff I've written in C/C++. Comments are not essentional if you can read code like a book. Which, a professional programmer should be able to do.

    www.wolf5k.com has an obfuscated version of Wolf3D written in Javascript. I went through and deobfuscated the code, figured out exactly what it does and then commented it. I then took the deobfuscated version and translated it to C++. I did the same with the Gavare ioccc ray tracer although the results havn't been posted on-line yet.

    Deobfuscated Wolf5K

    If you want practice reading "bad" code, deobfuscating programs is great practice.

    Ben

    1. Re:code first, then comment by Anonymous Coward · · Score: 0

      If you want practice reading "bad" code, deobfuscating programs is great practice.

      If you want practive reading "bad" code, work for a defense contractor on a project more then 15 years old.

    2. Re:code first, then comment by GileadGreene · · Score: 1
      You should also code first because you know what a function is supposed to do.

      Or perhaps you could write a quick comment that describes "what the function is supposed to do" (since you already know). That has two advantages:

      1. It tends to clarify your thinking with regard to what you're doing, which makes the code that much easier to write. To quote Richard Guindon "Writing is nature's way of letting you know how sloppy your thinking is."
      2. It makes your intent clear for anyone else who is trying to read your code, so that they can determine whether or not what your function does is what it was actually intended to do.
    3. Re:code first, then comment by EccentricAnomaly · · Score: 1

      But couldn't code be treated more as mathematical notation?

      I don't write notes describing what I'm doing before I work something out... I work it our first and then figure out how to describe it.

      Perhaps with design by contract like in Eiffel, the code itself could make the intent more clear than comments could. Sort of like stating the theorum you're gonna prove beofre you prove it. The code would describe the expected result before it calculates it.

      Comments are a good idea, but maybe not the best idea. Other posters have pointed out that it is hard to keep comments synced with code that's evolving... and I'm bitten by this all of the time. The more detailed my comments are, the _harder_ it is for me to maintain my code. The compiler and unit tests will tell me if my code is correct, but it is very time consuming to make sure the comments are correct.

      My dream is for a language that doesn't need comments... maybe even one that could be explained by an automated tool (like the way Apple's Shark explains the dissasssembly of your code)

      --
      There are 10 types of people in this world, those who can count in binary and those who can't.
    4. Re:code first, then comment by GileadGreene · · Score: 1
      I don't write notes describing what I'm doing before I work something out... I work it our first and then figure out how to describe it.

      You shouldn't have to "figure out how to describe it", since the kind of comments I'm talking about involve intent rather than details of how the intent is achieved - think of it as an informal spec. If you can't articulate the reason for writing a particular function you probably shouldn't be writing it in the forst place.

      Perhaps with design by contract like in Eiffel, the code itself could make the intent more clear than comments could. Sort of like stating the theorum you're gonna prove beofre you prove it. The code would describe the expected result before it calculates it.

      DbC certainly helps. As do other formal expressions of what a function is supposed to be doing. But inevitably you find that there's a need for descriptive text as well - just as a mathematical proof is much easier to read if there's some accompanying exposition.

      Comments are a good idea, but maybe not the best idea.

      Comments, like many other things in life, are best used judiciously and in moderation. Comments shouldn't be written simply for the sake of writing comments. They should be written in order to provide a better communication of design intent.

      Other posters have pointed out that it is hard to keep comments synced with code that's evolving... and I'm bitten by this all of the time.

      Comments are part of the code. If you are changing code without changing comments then you haven't done a complete job of making the change.

      The compiler and unit tests will tell me if my code is correct, but it is very time consuming to make sure the comments are correct.

      The compiler will tell you that your code compiles, and (if the language your are using is statically typed) that it is type-correct. This raises the probability that your code is correct, but certainly doesn't guarantee it. There are plenty of programs that compile, but either don't run or produce garbage. Unit tests help. But how do you know they're testing the right things?

      My dream is for a language that doesn't need comments...

      Sure, that'd be nice. But I wouldn't count on it showing up any time soon. Mathematicians have been messing with formal notation for a while now, and they still ending up writing a lot of natural language exposition to help people understand what the formal stuff is doing.

      maybe even one that could be explained by an automated tool (like the way Apple's Shark explains the dissasssembly of your code)

      But that will simply tell you what the code does. Not what it's supposed to do. There is a distinct difference.

    5. Re:code first, then comment by Coryoth · · Score: 1

      Comments are a good idea, but maybe not the best idea. Other posters have pointed out that it is hard to keep comments synced with code that's evolving... and I'm bitten by this all of the time. The more detailed my comments are, the _harder_ it is for me to maintain my code. The compiler and unit tests will tell me if my code is correct, but it is very time consuming to make sure the comments are correct.

      One of the things I like about doctest for python and contract python is that it helps with this: you function documentation (which is to say comments) can be used to test the code. Sure, it's not perfect, but it is nice to be able to have something resembling debuggable comments.

      Jedidiah

    6. Re:code first, then comment by Binsky · · Score: 0

      But that's not the main issue of course, most folks will be able to read their own code for quite a while after they've written it... But when someone else needs to work on your code, comments start getting useful. I usually comment the function headers, to give a brief outline of what it does, what it needs, and what it returns. (if that's not too obvious already) It just makes it that much easier to find the flow of the program after a year's absence. I have had to debug a multithreaded communication unit that consisted of 144 pages of code, handling communication for all that companies' products. And the only comments contained within those 144 pages were the lines that the designer deemed unneeded! I ended up adding comments myself where I understood what was going on... The way I see it, is that the next software engineer to work on that project will have a far easier time to get started then I had. I usually comment first, to get the flow of a procedure right from the start. But that's needed, as my programming environment isn't one of the quietest around...With phones ringing, and colleagues talking loudly, it's easy to get distracted! So to me, comments have a double function! :p

  57. BS by isny · · Score: 1

    Tell that to the boss when the code is due. You will soon learn what is REALLY important in the real world.
    Without working code, there is no product. Without product, there is no money. Without money, hello unemployment line.

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

    1. Re:It is not math, it is not universally readable by Anonymous Coward · · Score: 0

      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.

      Hundreds LOC in an application? WTF do you write, hello world II?

    2. Re:It is not math, it is not universally readable by Nate4D · · Score: 1

      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.

      Okay, granted, I'm just on the verge of graduation, but having been through my software engineering class, I'm curious:

      Where on earth have you seen a significant real-world application that was only a few hundred lines of code?

      Most of my trivially-small programming class assignments hit 3 - 400 lines (partly due to my obsessive documentation style), and the minesweeper clone I worked on in my software engineering class was around 3000 lines. Minesweeper (even with a self-solving mode) is not exactly a major application.

      I would have thought most major apps are more on the order of tens of thousands of lines of code... Are you counting complex scripts as apps, maybe?

      --
      "Oh, I like geeks way better than I like humans." - Mari Sarris
    3. Re:It is not math, it is not universally readable by Anonymous Coward · · Score: 0

      100s? 1000s? Try hundreds of thousands. Fucktard.

    4. Re:It is not math, it is not universally readable by el-spectre · · Score: 1

      Depends on your programming language and style...

      For example, I've rewritten stuff that originally had hundreds of variables (with all the requisite declarations, error checks, etc.) by putting them in a hash and loading to /reading from the hash in a loop.

      Either technique is acceptable, but 1 is hundreds of lines long (for this particular activity), the other is 6 lines long.

      Also, gui stuff tends to get big quick.

      For an interesting comparison of code size, write the same app in C++ and Perl, then count the lines :)

      --
      "Faith: Belief without evidence in what is told by one who speaks without knowledge, of things without parallel." - A.B.
  59. There is a middle ground. by Some+Random+Username · · Score: 1
    I hate seeing code with no comments, especially when its not immediately obvious what a piece of code is doing. But I hate it just as much to see code full of useless comments explaining what the code is doing, when the code should be explaining it just fine. Stuff like:
    i++; /* increment i */
    makes me want to kill someone. Worse yet, when its:
    i++; /* increment i - Bob Nov 2002 */
    as if comments are an acceptable form of version control. It takes a bit of practice to find the right middle ground, where you make sure your code is easy to understand and doesn't need comments, but the tricky spots that just can't be made easy to understand are commented well.
  60. At least comment the methods... by Anonymous Coward · · Score: 0

    At least that's what someone who comments told me. :)

  61. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    Agreed. I am currently (this very night) going through an assortment (few hundred) of php documents that run a friend's business website.

    He had it done by a company that eventually outsourced it to.. guess.. India.

    Within an hour I've found 3 non-working subroutines in the administrator login menu, 4 unprotected directories on the webserver containing files which hold among other things the SQL database login/password and not ONE stinking bit of the code is commented. There's cut/paste jobs abound, even containing referances to free php-script type sites.

    It's an absolutely horrible job. Although the site graphics/layout is quite excellent. =)

    I have a feeling the company hired produced the color scheme and layout then outsourced the backend.

  62. Variable Names by slobber · · Score: 1

    using short, descriptive variable names 'should' be enough

    Aren't they on the opposite ends? I find it much easier to have descriptive variable names which are relatively long (~25 chars in C++). Not all variable names need to be that long (most local variables don't), but I often find that using long descriptive variable names makes comments unnecessary.

    Also, I don't think there is some magic ratio of comments to source code line (like 1.5 comment lines per 1 line of code). If someone tries to stick to such ratio, it would be a waste of time in some cases and insufficient in the others. The bottom line is that if code is trying to do something "clever" (tricky algortihm or complex logic flow) then be generous with your comments. Otherwise, you can get away with just a few comments and save yourself some time. If you are just starting to program, you won't go wrong putting more comments in. Otherwise, let your intuition and experience be your guide.

    One final observation is that I find comments at the beginning of source file most helpful. A paragraph or two describing what a heck is going on can go a long way to helping me understand some key ideas without having to skim through the entire file.

    --
    "You mortals are so obtuse." -Q
  63. You're both wrong. by ph4s3 · · Score: 1

    Software is the only designed/engineered product that doesn't have accompanying documentation such as a schematic, blueprints, etc.

    Comments would be suruflous if there were a design document that accompanied the final product. By looking at the code one would be able to determine where they are, similar to standing in a house and knowing where in the blueprint you are based on your surroundings. Comments are not sufficient because they can't communicate the context of your position within the code; rather, you must read the comments to see what the code is doing, but you must examine the entire routine(s) to determine the methodology used to solve the particular problem(s). Until software has a blueprint-like document that goes with the code and the delivered binary/executable, comments will be necessary but woefully inadequate.

    1. Re:You're both wrong. by ph4s3 · · Score: 1

      Damn typos.
      suruflous==superfluous

  64. My opinion by karvind · · Score: 1
    Answer to this question may differ from programmer to programmer. But I strongly feel, it helps in Debugging, Reverse Engineering, Re-engineering, Testing and giving the code a neat look. Moreover, it's a step towards standardization of coding methodology.

    An interesting article on ZDNet on Documentation is good, but source code is better

    Good documentation practice from Linux.com.

  65. Well, duh by QuantumG · · Score: 1

    the total lack of formal methods in the software we develop today means we have to use comments to document our intentions and design decisions. This is obvious to anyone who has some experience in the industry. If we had formal specifications a large number of comments would be pushed up from the code into the specification.. but seeing as we're currently incapable of working with more than 2 files at the same time (many people have trouble keeping their header files in sync with their source files unless the compiler complains about something) that's not going to happen any time soon.

    --
    How we know is more important than what we know.
    1. Re:Well, duh by shmlco · · Score: 1
      If we had formal specifications a large number of comments would be pushed up from the code into the specification.

      Unfortunately, if I'm working on code I know where the code is, but the binder containing the documentation may be halfway around the planet. Comment the code and you keep the two together.

      --
      Any sect, cult, or religion will legislate its creed into law if it acquires the political power to do so.
    2. Re:Well, duh by shmlco · · Score: 1

      It's a binary-format-to-binary-format-transposition. The vast majority of the actual data is not altered, e.g. pixel value 0xFE12 is 0xFE12 in both the input raw and the output DNG.

      --
      Any sect, cult, or religion will legislate its creed into law if it acquires the political power to do so.
  66. Comments are important for *clever* code by Anonymous Coward · · Score: 0

    If your code is clever, then you must document it.
    IMHO, writing clever code is a bad design principle.
    From that perspective, good design reduces the amount of comments required. You are correct, but perhaps your coworkers are more so.

  67. Re:And this, my friends, is why offshore outsourci by Eternally+optimistic · · Score: 1
    Two small points of disagreement with your reasoned argument:

    Indian engineers are probably fairly well paid, considering their cost of living,

    If the US doesn't help Mexico achieve a reasonable standard of living (no matter who is at fault for the lack of it), then Mexico will come to the US. Those people have a legitimate reason, you can't stop them.

    --
    What keeps me going is my inertia.
  68. You're both right. by Randolpho · · Score: 1
    Seriously. Comments are important, but don't make the mistake of overcommenting. Comments should, as a rule of thumb, only be used when what you are doing is not particularly clear from the context of the code. Comment functions and methods so that a person reading your code knows what they do. Comment variables and attributes so that a person reading your code knows what they're for or what they represent. Comment key turning points in your code, or perhaps algorithmic sections. Do not comment every damn statement! You don't know how many times I've seen code like

    /* Print "Welcome to the main program!" to the console */
    printf("Welcome to the main program!");
    That's an extremely contrived example, but I *have* seen code where *every* step was commented just like that. That woud be great if it were an explaination of the reasons behind some complex algorithm, but more often it's just a rehash of what's obvious from the statment itself.
    --
    "Times have not become more violent. They have just become more televised."
    -Marilyn Manson
    1. Re:You're both right. by LoztInSpace · · Score: 1
      /* Print "Welcome to the main program!" to the console */
      printf("Greetings from the main system!");
      is more like stuff I've ever seen.
  69. Why is the answer to this one or the other only? by Anonymous Coward · · Score: 0

    Seriously, shouldn't it be a balance between good documentation and good self-documenting code?

  70. 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.
    1. Re:Comments Should Reflect Intent by Anonymous Coward · · Score: 0

      I hate code like this! You can't even SEE the code.. there is too many fucking comments. No wonder jobs are being sent to other countries.

      Only put comments in when you KNOW that there is no way you could remember what the hell it is later (assuming you know what you are doing).

    2. Re:Comments Should Reflect Intent by NitsujTPU · · Score: 0, Redundant

      class Gorilla
      {
      public boolean isMagilla()
      {
      return true;
      }
      };

    3. Re:Comments Should Reflect Intent by Anonymous Coward · · Score: 0

      I'd argue it was more useful like this:

      public boolean meetsMagillaCriteria() {
      return false; // currently, no MyClass meets the magilla criteria.
      }

      Named like that, there's no need to add the comment of "tells wether the instance meets the magilla criteria".

      (I totally agree with you on the 2nd comment in the code, though).

    4. Re:Comments Should Reflect Intent by Brandybuck · · Score: 1, Redundant

      Comments can be good, but a lack of comments is ALWAYS bad.

      --
      Don't blame me, I didn't vote for either of them!
    5. Re:Comments Should Reflect Intent by NitsujTPU · · Score: 0, Redundant

      Redundant again... someone has it out for me.

      Cripes, I stuck a joke in there.

  71. Literate code by GileadGreene · · Score: 1
    From TFA:
    Any language or system that does not allow full flowing and arbitrarily long comments is seriously behind the times. That we use escape characters to "escape" from code to comment is backwards. Ideally, comment should be the default, with a way to signal the occasional lines of code.
    Interestingly enough, this is exactly what literate Haskell files do. Code is, depending on your taste, either indicated by preceding it with > signs e.g.
    Here's some example literate Haskell code:
    > foo :: Int -> Int
    > foo 0 = 1
    > foo n = bar n + foo n-1
    or it's embedded in a LaTeX document, e.g.
    \begin{document}
    Here's some example literate Haskell code embedded in \latex :
    \begin{code}
    foo :: Int -> Int
    foo 0 = 1
    foo n = bar n + foo n-1
    \end{code}
    \end{document}
    The latter approach also has the advantage that you can produce some fairly nice looking documentation as well :)
    1. Re:Literate code by EccentricAnomaly · · Score: 1

      Mathematica's notebooks also has a neat solution to this. Where you imbed the code into a Latex like document. The twist mathematica gives is that you can hide all or some of the code from the document and only show the results. You then click little arrows to expand the detail to show you the code that generated the results. This gives a nice way to slowly descend into deeper and deeper depths of detail.

      --
      There are 10 types of people in this world, those who can count in binary and those who can't.
  72. Comment on intention not implementation by BbMaj7 · · Score: 1

    Too often you know what you are trying to do but make a mistake. Self documenting code is only useful if the code is free of mistakes. IMHO it is better to comment what the code is supposed to do.

    If the intention is clear then it is easier for others to determine if the implementation is correct.

    Intentions also better describe why particular design decisions were made.

    --
    -- Rich
  73. Develop realistic habits by Dominic_Mazzoni · · Score: 1

    Comments are very important, however you need to figure out the right level of detail that provides as much documentation as possible, without taking too much time away from coding (because then you'll be likely to leave the comments out).

    Incorrect comments are worse than no comments at all. In an ideal world, you'd figure out what you want to do, write the documentation for the function, then implement it, documenting any lines that aren't obvious. However, life is never like that. Sometimes you need to modify a function to make it do something else. If your comments are too long and verbose, you'll be tempted to not change them, which is worse than not having them there at all!

    Therefore, you should keep your comments concise. Don't waste your time writing detailed comments for a simple function, or one that is likely to change tomorrow. But when you finish a complicated function and get it to work, definitely make sure it's well-commented, so you don't have to worry about it again.

  74. Code more important than comments. by neurojab · · Score: 1

    Well structured and well written code is obviously more important than having comments. Allow me to give an example. I once ran across a single method that was 10 pages long! The variable names were all completely unhelpful, and the code itself barely worked. It was clearly written by someone that didn't know how to program. It had some comments, but I still couldn't understand what was going on. No amount of commenting would be able to help something so awful.

    Contrast that with well structured code, wherein the methods are relatively small, the methods and variables are well named, and you can have a usable, maintainable program with no comments at all. Comments are nice for the sections where what's happening isn't obvious, but if you need to sit down and comment every line of code you write in order for someone else to understand it, you're writing some very bad code.

  75. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    Will MDA help solve this? The on-site developers create the various models, which serve as high-level documentation, and whatever can't be automatically generated is off-shored. There would still be a lot of code to write, but it would be easier to understand with the PIM/PSM available.

    That probably will only help in large developments off-shored, and likely more of a dream than a reality.

  76. *Unit tests* not comments by Anonymous Coward · · Score: 1, Interesting

    If you're doing OO, invest some time in a good unit testing framework, like xUnit. I'm inclined toward the agile method of test-driven development (flame away), so I would prefer that any code I have to maintain was written *after* the tests were constructed; however, I've seen valuable unit tests which were clearly either automatically generated or manually written after the code under test was completed.

    As long as you commit to maintaining your tests, refactor all you want and rest assured that as long as your tests pass you're in good shape.

  77. Code != Design Document by saddino · · Score: 1

    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.

    First, I just have to get this off my chest: I think this is pure B.S. Coding styles vary so much, that if you can't recognize your own code, then programming is something you barely have a hold on.

    Now, as to answer: code should be readable, especially using mixed type names, a consistent naming style and comments for non-intuitive constructs. But -- and this is a big but:

    If your code is meant to be shared with other programmers and you don't have a design document... ..then you or your employer is an idiot, plain and simple.

    If you have a project that needs support from more than one programmer (i.e. any commercial enterprise save DIY shops), then blaming "lack of comments" is just displacement. Blame the project manager instead.

  78. 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.
    1. Re:Comment interfaces, not implementations by menace3society · · Score: 1

      You *might* be right for high-level languages, but I've seen two *completely different* implementations of libc strlen in powerpc assembly (and wrote a third). Without all the comments, both before the start of the function and inline, I never would have figured out how each one did its job.

    2. Re:Comment interfaces, not implementations by bunratty · · Score: 1

      Did you read the last paragraph of my post about multi-line comments for each line of code in low-level bit-fiddling code? You just might have missed that.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    3. Re:Comment interfaces, not implementations by firewrought · · Score: 1
      void sort(int arr[]); // sort arr, ascending

      Interface comments are also a good place to make behavioral guarantees. In your example, for instance, it would be nice to know whether stability was guaranteed or not. (You get off the hook, of course, since the job of sorting plain ints will always yield the same results whether you are using a stable or unstable algorithm...)

      I could see the following comments for a sort(arr) method:

      // sort arr, ascending, stability guaranteed

      // sort arr, ascending, stability not guaranteed

      // sort arr, ascending, stability not guaranteed
      // WARNING: this version uses a stable sort, but this may change
      // in the future.
      It can be very frustrating when an interface does not specify key behavioral guarantees and you have to guess whether or not it's safe to rely on the apparent behavior.
      --
      -1, Too Many Layers Of Abstraction
    4. Re:Comment interfaces, not implementations by GrahamCox · · Score: 1
      // Set the serial port to big-endian mode
      // See SlurpSCC manual page 3-5
      bitset(slurp->serial, bit(13));


      Here's a great opportunity to make this much more self-documenting:
      enum
      {
      kSlurpSCCBigEndianControlBit = 13
      };
    5. Re:Comment interfaces, not implementations by Anonymous Coward · · Score: 0
      Here's a great opportunity to make this much more self-documenting:

      enum
      {
      kSlurpSCCBigEndianControlBit = 13
      };


      Yes, you could also write:
      enum {
      kSlurpSCCBigEndianControlBitAccordingToManualPage3 To4= 13
      };
    6. Re:Comment interfaces, not implementations by bunratty · · Score: 1
      If I did something like that, I'd use the mnemonic name of the bit given in the manual (probably something like EMC for endian mode control):
      bitset(slurp->serial, kSlurpSerialEMC);
      That improves the readability of the code, but doesn't make the code self-documenting. With that code change, I'd leave the comment unchanged.

      The reason I didn't write code like that was because I would have had to write the enumerations for all of the thousands of bit fields available in the SCC chip I was using. The reason I was able to use mnemonics for the control registers was because Motorola was kind enough to have make a .h file available for download that was a C data structure representation of every register.

      More readable code is usually a good goal, but sometimes isn't worth it, and often doesn't make comments unnecessary.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    7. Re:Comment interfaces, not implementations by GrahamCox · · Score: 1

      Agree 100%. You'll notice I didn't say INSTEAD of a comment - I meant AS WELL AS.

    8. Re:Comment interfaces, not implementations by iabervon · · Score: 1

      With a good inlining compiler, you could actually make this a function in a header file, and eliminate the first comment from the code (in favor of set_serial_big_endian(slurp);) and move the second comment to the inline function body, where it only tells people who really care where you got that implementation.

      It's amazing how nice having a real compiler for your microcontroller is, especially if you can get it to optimize out big conditionals in inlines called on constants, so you can have the compiler look things up in tables for you.

    9. Re:Comment interfaces, not implementations by eraserewind · · Score: 1

      Commenting interfaces is good, but really if you expect someone to maintain or integrate your code you have to comment the code itself also. What pure developers don't seem to understand is that people doing integration or maintenance don't have the time to get an intimate knowledge of each and every function by reading the source. Your component is going to be just one tiny part of a huge system. Understanding by "reading the code" doesn't scale.

  79. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    Way to generalize an entire country over something you clearly know nothing about.

  80. Interfaces by Anonymous Coward · · Score: 0

    I feel like properly commenting interface functions is a good way to go.

    If people can't understand the code after that, then maybe the interface needs to be fleshed out more.

    But I think this stuff is really language specific. Different languages need varying levels of comment-documentation to be understandable.

  81. The Comments is the Code by Anonymous Coward · · Score: 0

    I heard that there was a language in the '70's where the specification document was the program.
    The compiler would actually compile the spec!

  82. More comments... please!! by redsilo · · Score: 1

    I am not a programmer. There was a time in my life when I thought I might become one but that folly has passed. When I was trying to learn to program I remember reading a comment by a veteran programmer: "There is a special hell reserved fro programmers that don't comment enough." From the little I know it would probably be helpful to someone trying to service something down the road to at least label routines by their intended function. Commenting every line is most likely not necessary. kk

  83. As invaluable as good directions by squared99 · · Score: 1

    When getting directions, do you need to have a tree or a traffic light explained to you or do you just need to know what to do at that tree or traffic light?

    The greatest use for comments is mapping out the over all logic of the program. How does one method/function relate to the overall functionality/goal of the application, in what context will it be called, what other methods rely on this function etc.

    Naming your variables is great, but if all it does is identify what that variable represents solely within the local scope of the method or function it's fairly useless when doing a code review a couple years down the road.

    Well written methods with descriptive names are a good idea as well, and do lead to the 'self-commenting' coding type of approach, but speaking from my experience, comments are still the best way to clarify things.

  84. Document at Design Level! by Rew190 · · Score: 1
    I always found that if you're coding OOP, code is generally simpler to understand (assuming methods aren't obnoxiously large). Meaningful variable names and such generally take care of that.


    The problem arises when I have to modify a portion of our business application (about 500 classes or so). On any given screen, we might have fifteen objects working with each other, and so the key to this isn't figuring out what the method and variable stuff does, but what the actual OOP design was. The code itself is usually very readable, but there is a lot of skipping around through various interfaces and helper objects.


    This is why you can't count merely on self-documenting code, especially when you're working with polymorphism and OOP. Document at a design level!

    1. Re:Document at Design Level! by Stalus · · Score: 1

      Get yourself a good instrumentation system, run the code instrumented once (yeah, slow, but..), and you can get a pretty nice idea of what objects are involved, who called what and why, how they interact, etc.

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

  86. Re:And this, my friends, is why offshore outsourci by BlueHands · · Score: 1

    So your theises is that indian programmers can learn enligh and PHP but not how to comment?

    I have know lots of americain programmers say the code documents itself. Many bad programmers think comments are not needed and it has nothing to do with where they are from but how they are taught.

    Outsourcing may or may not be a serious issue, outsourcing may or may not be a danger to americain programmers but commented code, or lack of, isn't going to play a very large part in the outcome.

    --
    I mod everyone down who says "I'll get modded down for this." I hate to disappoint.
  87. The Problem With Comments by Anonymous Coward · · Score: 0

    Comments are great if the programmer takes the time to update them when they update the code.Many times a chunk of code is doing one thing but the comments say another.

  88. Self-documenting code is harder than commenting by SnprBoB86 · · Score: 1

    NOTE: I say "code" referring to function bodies. I strongly believe that every function should be clearly labeled and its behavior clearly defined. Javadocs, doxygen, C#'s XML comments, etc are EXTREMELY VALUABLE, no matter how obvious some descriptions may be sometimes.

    Self-documenting code is THE BEST WAY TO GO, but far harder than commenting.

    If the code is written properly, anyone should be able to glance at it and read it. Not a single comment should be needed at all, but unfortunately that's idealistic and unrealistic.

    Comments exist for clarifying code that is inherently not self documenting. I believe comments should be the minority. If there is a comment, that means the code is confusing and requires clarification. Sometimes confusing code is a must for performance, to completing an implementation on time, or just because it wouldn't work any other way, but it should be avoided as much as possible.

    You should try to build your code in such a way that you can't possibly think of what to write in an inline comment. This means lots of modularity: well documented functions even when they are only ever going to be called from one place.

    You should look at your code and every line should read to you:
    coutxendl; // Outputs x to the console

    --
    http://brandonbloom.name
    1. Re:Self-documenting code is harder than commenting by SnprBoB86 · · Score: 1

      naturally that should be cout<<x<<endl;
      the Google toolbar spell checker has crippled my use of preview ;-)

      Also, I forgot to mention: comments and self documenting code are both completely useless if the documentation becomes out of sync with the source...

      --
      http://brandonbloom.name
  89. Personally by Anonymous Coward · · Score: 0

    I think you can encapsulate comments directly into your code via interface/variable/method naming.

  90. 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 iplayfast · · Score: 1

      for(int i=0;iAgentNameLen;i++)
      should have read
      for(int i=0;i<AgentNameLen;i++)

      (slashdot error)

    2. Re:Debug code not comments by comwiz56 · · Score: 1

      Why not combine the two (descriptive variable names and comments) for the most readable and understandable form. As the code developes, more and more documentation will be required to make the code less and less confusing.

    3. 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!
    4. Re:Debug code not comments by startled · · Score: 1

      Are people really arguing the merits of bad comments versus no comments? Clearly, anyone would rather have no comments than bad comments.

      If you'd put a line up top that stated why the structure contained those elements, or what it was written to be used for, or something else similarly high level, that might have been useful. Certainly, adding a comment that says your struct is, in fact, a structure is not a good thing to do.

    5. Re:Debug code not comments by khallow · · Score: 1

      I interprete this as a variation on the database principle: don't duplicate data. In the case you mention, the code already stores the relevant data. Comments are redundant. Other people describe cases when you do need to comment code in order to store your reasoning and thought processes, but of course, this data can't be stored easily in variable names and the like. I see no contradictions between these two points.

    6. Re:Debug code not comments by drseuss9311 · · Score: 1
      You Said:
      for(int i=0;iAgentNameLen;i++)
      which makes it very clear that you are iterating throught the agent name.
      I had this long smackdown typed out, but then I decided to not proofread it and hope that you were trying to be funny (oh i hope someone mods this funny) My personal opinion on the usage of comments in code is as follows.

      My original comments come from pseudocode. Fill in from there as needed.
      This will usually result in just the right amount of comments as the pseudocode will be higher level ideas of what the code does.
      Anyone else use pseudocode for the basis of their comments?
      --
      ------ no thanks... I've quit
    7. Re:Debug code not comments by amigabill · · Score: 1

      Your example is a good one to show that good variable names with no comments can be better than bad variable names with comments, but it's also very simplistic.

      I wouldn't use obscene amounts of comments, to be sure, information overload can be as annoying or meaningless as insufficient information. But even with good variable and function names, sometimes you simply need a bit more. Look through grahics driver code in Xfree/xorg. It's ugly as heck. It's nigh-impossible to tell WHAT is happening in there, let alone the possibly more important WHY it's being done.

      Yes, variable names should be chosen to minimize explaining what the variable is used for. Same for function names. But you shouldn't stop there.

      Here and there you need to say what is being done. Give a brief summary of how it works. And please don't forget the why it's there. They can all be life-savers later on, where variable or function names may not be enough for someone else to truely understand what's happening and why or how they need to make their changes.

      I was hoping to learn a few things from certain Xfree/xorg driver code a couple years ago. It wasn't at all helpful, and we were left to random experimentation in our own code until "something good happened". That's not the ideal now is it? Our code now describes our situation and explains things as best we can pretend to understand them for our own uses in the future, the xorg driver code continues to be meaningless last I saw.

      It's funny that many users of my obscure OS of choice seem to think that if there is open-source Linux driver code out there, any hardware can be made to work on our platform too. Sorry dudes, but much of the driver sources out there can happily live in the "no documentation exists whatsoever" category.

      Other code out there is quite good. But I'll never agree that the code documents itself, as I've seen to much proof otherwise, including my own code from weeks earlier. I've had a profound comments learning experience since then, and can now much better understand my own old code.

      I even comment basic concepts in my code, even for files only I look into at work. Cadence's VSLI tools have a scripting language I've used to make a parameterized chip core layout. Skill is the ugly bastard-child of C and lisp... Change the parameters and it automatically swaps in different versions of cells, changes cell libraries to use, or resizes the repeating array. Basic concept here, is my program a generator seperate from it's layout output, or is it one and the same thing as the resulting layout? My understanding is they are one and the same, as changes to the code immediately affect the layout view without any recompiling or any other "generating process". It just "is" different in the layout viewer. Other workers have complained when my work on the code has mangled their layout work, with me doing nothing more than vi-ing a file and saving changes to disk. People asked me if I was looking for another job after seeing me commenting this code, as if I was preparing things for the next guy to take over. I was doing it to keep myself sane when I have to work on it again next year or whenever...

    8. Re:Debug code not comments by iplayfast · · Score: 1

      No, I'm arguing the case of self documenting code is better then non-self-documenting code+comments.

      The purpose of a structure can change overtime, which is why it's a good idea to give the structure a meaningful name in the first place. CustomerID should have given a clue. (Although I admit my off-the-top-of-my-head example could have a better name, maybe CustomerAgentRelationShip). If the meaning of a structure changes, then the name change will cause a refactoring to occur which helps keep the code consistant. If the meaning changed, but comment wasn't updated then the comment can become worse then useless. It can be come misleading. Keeping comments in sync with code is difficult to do, especially if a comment describes an algorithm which spans several functions. If one of the deep down functions get's changed, will the maintainer know to update the discriptive comment way up top?

      Certainly, adding a comment that says your struct is, in fact, a structure is not a good thing to do.

      The comment was // CustomerID struct
      the important part was "CustomerID"
      But in general I agree, that the "struct" is redundant.

    9. Re:Debug code not comments by iplayfast · · Score: 1

      Interesting reply.

      I've worked on a number of large projects as well, and I have found that
      1. Like you comments keep me sane.
      2. Self-documenting code keeps me sane.
      3. Code and Comments drift over time, and after several people and time has passed, I don't trust comments. (better to read code, not comments).
      4. Self-documenting code tends to keep in sync with the intention of the code over time and people.

      An example of this is if the function name is:
      List *GetListOfUglyPeople();
      and someone changes it to only get ugly people with big noses they will likely change the name of the function to
      List *GetListOfUglyPeopleWithBigNoses();

      But when they change the name of the function all of a sudden, other functions which call the original one, complain that they can't find it.
      So the programmer then has to update them as well. This has the benefit of
      1. Keeping the understanding of the code intact.
      2. (helping to) insure a code review when the algorithm changes.
      3. This also tends to help weed out programming errors.

      I've done this where I thought a function would be better called GetIndex(), (because that's what it did), and when I did that and then went through all the functions that used it, I noticed that there were many redundant calls, that could be eliminated. The code had drifted from doing several things to doing one thing, but the calling code hadn't followed in all cases. By following the self-documenting rule, I got the code back in sync.

      So I still believe in my 80% self-documenting code and 20% comment rule. The 20% is for those comments that can't be explained easily with code...

    10. Re:Debug code not comments by BenBoy · · Score: 1

      Ooooooo, you hit one of my own pet peeves; "AgentNameLen"???? Who the heck is "Len"? Saving 3 characters vs "AgentNameLength" is false economy ... more generally, don't use non-standard abbrevia's :-)

    11. Re:Debug code not comments by Anonymous Coward · · Score: 0

      strlen is the C string length function.

      So I think len is a normal method of abbreviating length. I know I have heard len many times.

    12. Re:Debug code not comments by Anonymous Coward · · Score: 0

      Another advantage with using those defines, if for some reason you need to change the length of the Agent or Customer, you can change in one spot, instead of searching for the numerical values.

    13. Re:Debug code not comments by slashdot.org · · Score: 1
      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.


      I would be inclined to use sizeof this instead:
      CustomerID cid;
      for( int i = 0 ; i < sizeof( cid.AgentName ) ; i++ )
      cid.AgentName[i] = 0;
      It's debatable for sure, but I'm no fan of using a define or const in places like a for loop to depend on the size. The reason is that it's possible that somewhere else there may be a definition of AgentNameLength. What if you accidentally choose the wrong define (or const). When you use sizeof, there's no question that it's correct.
    14. Re:Debug code not comments by iplayfast · · Score: 1

      Good point, however I've been stung when an array is actually a pointer to an array... (You get the size of a pointer). Not usually the result you are looking for, and hard to debug, since it can end up with trashed pointers. But I suppose that's a matter of careful coding in the first place.

      As far as using #define's or const for defining the array size and using that as a definition of the length of the array when iterating, it seems pretty obvious to me that it's a good method. You can't have two defines with different values, at the least you will get warnings.

    15. Re:Debug code not comments by slashdot.org · · Score: 1
      Good point, however I've been stung when an array is actually a pointer to an array... (You get the size of a pointer).

      Certainly. That is one of the debatable sides of using sizeof in this case. But if the field was a pointer, then you'd also (most likely) not use a define/const in the first place. (since it most likely is a variable length)

      The bigger problem with it is that my code assumes sizeof( char ) is 1. A more proper way of actually writing it would be:
      for( int i = 0 ; i < (sizeof( cid.AgentName ) / sizeof( *cid.AgentName )) ; i++ )
      which I admit, is getting a little crazy. So what I usually have is one macro:
      #define ELEMENTS_IN_STATIC_ARRAY(a) (sizeof(a)/sizeof(*(a)))
      and then you can use:
      for( int i = 0 ; i < ELEMENTS_IN_STATIC_ARRAY( cid.AgentName ) ; i++ )
      The use of which becomes more obvious when you are dealing with arrays of structs.

      Also, when you are writing code, the name is obvious enough that you wouldn't use it on an pointer. When you change the CustomerID.AgentName from a static sized struct to a pointer at some later stage you are most of the time doing it to make the size of AgentName dynamic. This means you have to hunt through the code and see where it's used in either case.

      Your search would be easier, because you'd only have to search on the define.

      As far as using #define's or const for defining the array size and using that as a definition of the length of the array when iterating, it seems pretty obvious to me that it's a good method. You can't have two defines with different values, at the least you will get warnings.

      Sure, but my point was that, unless you use very unique names, and especially when you start pulling in lots of headers, it's entirely possible that you are accidentally using a different define/const than the one you intended.

      I've actually seen people getting confused with their own stuff. Using MAX_STR_LEN and MAX_STRING_LENGTH and MAX_STRING_LEN etc. Then inevitably they end up using the wrong define/const when they need it.

      But I'll give you this, if you are consistent with using namespaces, the best solution may be to use consts. :-)

      Cheers.
    16. Re:Debug code not comments by Anonymous Coward · · Score: 0

      > for(int i=0;iAgentNameLen;i++)
      > which makes it very clear that you are iterating
      > throught the agent name.

      Or you're an Apple Fan...

    17. Re:Debug code not comments by iplayfast · · Score: 1

      I believe we could work with each other's code without too many problems :)

    18. Re:Debug code not comments by Kupek · · Score: 1

      I think it's worth abbreviating names that are used often. Think ls versus list or even listdirectory.

    19. Re:Debug code not comments by ampathee · · Score: 1
      I think I understand what you mean, but your examples seem a little slanted. I prefer the following to both your blocks of code:
      // constants for CustomerID struct
      #define AgentNameLen 41
      #define CustomerNameLen 51

      // define CustomerID struct
      struct CustomerID
      {
      int CustomerID;
      char AgentName[AgentNameLen];
      char CustomerName[CustomerNameLen];
      };
      Using #define statements instead of numeric constants is a must, and not really part of the whole comments vs variable-names issue IMO.

      Okay, the second comment is not really necessary, but you get the idea of what I mean - a comment for each block saying what you're doing.

      Always in these discussions there seem to be people saying "Comment your code well" and others say "No, use good variable names".
      I say, why not use both? My rule is: always use good variable names, and write the code in a clear way in general - ie. indenting, helper functions, etc. This provides a certain basic level of 'documentation' - if the code needs more than that, add comments until it is clear.
    20. Re:Debug code not comments by slashdot.org · · Score: 1

      I believe we could work with each other's code without too many problems :)

      Absolutely mate! :-)

    21. Re:Debug code not comments by iplayfast · · Score: 1

      Well, the first thing I thought of when I saw your comment // constants for CustomerID struct is that it's very limiting. I would normally use something like that as globably as possible, so that everywhere I was using something to do with an Agent Name, it would also have to do with an AgentNameLen. Perhaps that's just my coding style. But I have found that using one define to cover multiple cases is better then using one define for each case. You end up with more consistant code, and the code has fewer unexpected differences. Also I can see that comment getting out of sync with the code in a very short time. (ie the next time someone uses those defines for some other struct which also has an AgentName, or CustomerName in it.)

      The second thing I thought of was the second comment // define CustomerID struct was the redundent type of comment that I hate. Useless since right below it is the definition of the struct. In your discussion, you said much of the samething yourself, and stated a comment for each block saying what your are doing. I think that it's good having a large /*========.... ====*/ to separate sections, it's much more important to comment why you do something rather then what something is.

      The example is definitely slanted. But it was off the top of my head to get a point across.

  91. If I may... by ecko3437 · · Score: 1, Funny

    Why do you think they call it 'code'?

    --
    -Eric Smith
  92. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    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.

    no danger of that happening.

  93. Re:And this, my friends, is why offshore outsourci by daviddennis · · Score: 1

    I don't see how taxing the wealthiest and giving the money to the poor has any connection whatsoever with offshore outsourcing. All taxing the wealthy does is drive economic activity out of the US.

    Offshore outsourcing is about the greatest good for the greatest number. If you have to pay a programmer $60k in the SF Bay Area for him to survive in a more or less bare sustenance lifestyle, and you could pay a programmer $10k in India and let him live like a pasha, which would you rather do?

    The projects I've been involved with have been ones where I can work as a single developer and do everything. In that case, it's most cost-effective to hire an American (namely me) because the overhead of hiring people in India only becomes viable when you need whole teams of people.

    With people avoiding the CS major and computing careers in droves, because of its perceived dead end nature, there is likely to be a shortage of programmers over the next few years. Strange but true.

    But that's then and this is now. In the mean time, I've shifted my career from programming and software design to multimedia development and entrepreneurial ventures. These are areas where it still makes sense to be here in the US.

    I'm pessimistic about US jobs because I know the people in India are good people who need the jobs as much as we do. Slamming the door on them doesn't strike me as the answer. If there is a single answer from the American point of view, I think it's for each of us to become more competitive by working closer to end users and/or changing our careers entirely.

    D

  94. The myth... by Anonymous Coward · · Score: 0

    1. Self-documenting code is a myth. Often spoken of, never clearly defined. In effect, nobody knows what it is although it makes for a nice buzzword.

    2. Name one programmer in the history of mankind who was rewarded for comments. What's that? You can't? Well, now you understand the problem a bit more.

  95. Re:And this, my friends, is why offshore outsourci by Anonymous+Luddite · · Score: 1

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

    You don't need to go to India for code like that... The West has its' share of bad coders. and even its' share of skilled coders who just skip the documentation.

  96. Depends on who is reading by redelm · · Score: 1
    If the only thing to ever read the code is a compiler, then comments are irrelevant. When humans read the code (presumably because they have been assigned the unenviable job of maintaining it -- worst of all their own code!) then comments matter.

    So the importance of comments comes down to the issue of maintainability. Under the pressure to issue v1.0, comments (and even coding style & practices) often get short shrift. Other things are more important at that time, but it becomes "pay me now, or pay me later".

    Personally, I believe in modular coding. Any module that cannot be easily and quickly re-written is too big. Then documentation can be reduced to interfaces -- required inputs, and produced outputs. But nooo ... everybody wants to cram more functionality into the calls.

  97. The most important thing.... by Anonymous Coward · · Score: 0

    is not comments in code. Having spent more than a few years as a maintainer of crap, I have to say that I have gotten to point of not putting a lot of faith in comments.

    Comments come in a few forms.
    1. Correct and useful.
    2. Incorrect and seemingly useful.
    3. Correct and useless.
    4. Incorrect and useless.
    and may favorite
    5. Comments concerning the code that no longer exists.

    Correct and useful comments are in the minority, a very, very small minority.

    Over the course of a project various people will maintain the code, very few seem to maintain the comments.

    Nothing is ever going to be perfect, but through my experience I can say there is one thing that holds true.

    "The simplest way to solve a problem is always the most maintainable."

  98. Hmmm... by ta+bu+shi+da+yu · · Score: 1

    ... speaking of bit masks, anyone seen the source for rpm? The way it handles command line arguments seems a bit silly really.

    --
    XML is like violence. If it doesn't solve the problem, use more.
    1. Re:Hmmm... by Eric604 · · Score: 1
      That should almost never happen except with non trivial algorithms.

      If it's non-intuitive you should focus documenting on why these steps must be done. The code it self should make clear what/how it's done. If it's not clear what the code does, refactor it.

      The grandparent example: "test bit flag set by keyboard input routine - "1" value indicates input complete" is explaining what the code does. A little bit of refactoring and renaming variables makes the comments unnecessary.

      I work like this: In the headers I specify exactly WHAT the function does, like you would document the interface of a library. If there is something non-intuitive going on I also explain why. Within the functions I hardly write comments. Just, read the interface documentation to know what it does and the code explains how it does that. I do summarize blocks of code with a one line comment but most of the time I break it up in functions with descriptive names.

      If you ever write a comment within a function block, try to rewrite the code in a way that it looks like the comment, and remove it. Yes, all this means longer function names, use ctrl-P.

  99. Right on! by romango · · Score: 1

    In relational databasee, you don't want the same piece of information in two different place. One will usually be wrong. Let's get better programming languages that are inherently more readable. It's the wild west out there.

    1. Re:Right on! by MarkusQ · · Score: 1

      In relational databasee, you don't want the same piece of information in two different place. One will usually be wrong.

      Exactly!

      Let's get better programming languages that are inherently more readable. It's the wild west out there.

      I've found that you can write readable code in pretty much any language. And you can write unreadable glop in any of them as well. Heck, suppose we had a language that was as easy to read as English--you could still write dreck like one of my former client's Corporate Vission Statement (I kid you not--they merged their Corprate Vision and their Mission Statement (both of which were bilge) and made something that you don't want to think about).

      IMHO, the problem isn't the languages.

      --MarkusQ

  100. Comments in English are good. by Penguin+Programmer · · Score: 1

    At work a couple of years ago I was assigned to update an MS Access/VBA (ugh) application that had been written by a different programmer a few years previous. Upon delving into the code I discovered two things:

    1) There were no comments.
    2) The mostly descriptively-named variables were all spelled wrong. I found out later that the programmer didn't speak much English.

    It took me forever to figure out what the code was supposed to do, and I ended up just rewriting the application from scratch because it was so bad.

  101. Good Programmers... by Anonymous Coward · · Score: 0

    Good programmers never comment their code; it was hard to write, it should be hard to understand :)

  102. Homegrown by aslsCave · · Score: 1

    As someone who is currently debugging code written for a homegrown database application (no comments, and several languages literally blended together). I vote for lengthy, descriptive, and functional comments.

    Even further the programmer/administrator should not assume the next maintainer is of equal or greater intelligence. KISS the code, KISS the comments.

    --
    I'm just not that quick witted. I'm actually quite lethargic. Example: Sloth;-)
  103. Age old debate by Anonymous Coward · · Score: 0

    This is an old debate. And in my search for truth I've learned this:
    1.) Comments can't help badly organized systems. No matter how elegant your code/comments in a bad system you will spend years extending it.
    2.) Organized systems are comments unto themselves. When you have a system, that's blatantly obvious how it works via function conditions and data types, comments are superfluous.
    3.) Wrong old documentation is the devils ugliest mistress. Something like this:
    char *text_for_something(void); //Pre: //Post: Returns a copy of internal data.
    It ends up implemented like this:
    { return internal_data; }
    4.) Too much commenting makes code unreadable. If you have so many comments that you can see as much comments and code on the screen, it's probably too much. If you can page through and never see a comment, it's possibly too little.
    5.) Write it, sorta forget it; go back and comment. Seriously, 2 days is long enough to make it vague and short enough to make it rememberable. So you can make it make sense for your 2 day seperated self. Maybe your 2 year seperated self will see it too.
    6.) Guides are good. Filenames aren't very descriptive, maybe describe them somewhere so people can find their way around.
    7.) I don't know what I'm talking about.

  104. Re:And this, my friends, is why offshore outsourci by ogleslurp · · Score: 1

    I'm going to weigh in against the long-term viability of the outsourcing scene. I have some hunches that I've yet to see tested, but there are also some that have been proven correct. As a result of my experiences, I believe that outsourcing through the language barrier will in time be proven to have been a fad. The whole thing is a false economy. Certainly, there will always be markets where you can find someone willing to provide a service for less than a local supplier. When the service doesn't seem to be tied to any geographical location in the way that software is practically universal (like english!), there will always be the temptation to chase estimated or hourly savings. The cost of interfacing between languages and remote supervision must be taken into account. Also consider the efficiency and accuracy that you can communicate with in your native language. Just for fun, grab a french-english dictionary and try to comment that code that you wrote this afternoon...but in french. Come back to it in a couple of days and see how well you can understand it. Consider also that currently, a lot of work is being sent to India. There's a reason that workers are willing to accept lower wages. The cost of living is lower. But what will happen if so much work continues to stream into India and it continues to carry with it foreign cash. As some workers increase their assets and income, others around them will demand more as well. So the savings found in India decreases and less work flows there. Bottom line: vigorous outsoucing cannot continue forever because all of the money flowing out of our country shrinks the deltas between world economies. And that will erase the conditions that made outsourcing attractive in the first place. Of course, that's just my opinion. I could be wrong.

  105. Re:And this, my friends, is why offshore outsourci by saltydogdesign · · Score: 1

    What, Indians can't learn to comment their code? And for cheaper than Americans?

    --
    // This is not a sig.
  106. Re:And this, my friends, is why offshore outsourci by MrBigInThePants · · Score: 1, Insightful

    What do you mean "some of them already know english"??

    Most indian graduates already know english, if not almost all of them!?

    I guess it makes us feel safer if we come up with more reasons for another culture's inferiority?

    PS: I am not indian..

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

    1. Re:The What, the Why, and the How by TiggsPanther · · Score: 1

      This is probably the most concise information about this that I've seen. I've seen (both in this discussion and elsewhere) much debate about why Commenting Is More Important or why Clear Code Is More Important, yet very few well-written reponses about why both (along with design docs) are important and in what context.

      Back in Uni when we were being told about why Comments Were Important I really wish it'd been explained this way. Advice is a lot easier to take when there's a good explanation behind it.

      --
      Tiggs
      "120 chars should be enough for everyone..."
  108. Verbosity by man_ls · · Score: 1

    I write PHP modules for various thing, usually following some API or other.

    I always use very precise terminology for what I write.

    For instance, if I'm writing a script to parse music information from an RDF file, I'd call my functions something like

    XMLFetchRssFeed($URL)
    ParseRssIntoArray($rss)
    ExtractLatestSongFromRSS($rss)

    that sort of thing.

    XMLHttpRequest style function and variable naming.

    For code only I will ever view, it's descriptive enough.

  109. The best comment is no comment by Anonymous Coward · · Score: 1, Interesting

    I've been the CTO and system architect for two software companies and have built some big software systems still in use today, after more than a decade of use and development across multiple, large teams.

    I personally hate comments for all but the most complex blocks of logic. Why? Because no one ever updates the comments, and pretty soon you have code that doesn't match the comments, and you end up wondering what's really supposed to happen. Comments end up as little fossilized turds that usually contain color commentary from people working too late into the night.

    What do I like? Use long, descriptive variable names; solve problems with the simplest approach possible; separate the problem into layers; etc., etc.

    And generating code from comments? Please... for that to ever really work, the comment syntact has to be as strict as code!

    1. Re:The best comment is no comment by amigabill · · Score: 1

      OK, you prefer no comment at all. Fine. Now, I ask you, go look up that 5 line DVD decoder written in perl a while ago, and by only reading the perl code, explain to me how it works and what it is doing.

  110. Code Comments by onesadcookie · · Score: 1

    When you need a comment, it's usually a sign that the code is not clear enough. There are very few cases where the code can't be rewritten in such a way that a) the code is better, and b) the comment is unnecessary.

    Most of the cases where that's impossible are commenting things that should not happen. Those comments are valuable.

    Comments that discuss the design are generally better served by separate design documentation in a human-readable format, with diagrams.

  111. 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
  112. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    . India has more engineers than the USA. And these are smart people.

    Smart, but lack the institutional knowledge of why comments are good for you. They'll make the same mistakes that the US has gone through for the past dozen years.

  113. 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 UlfGabe · · Score: 1

      re #5

      people often don't appreciate the Art-eeeestes in any buisiness. Maybe he was working on a super secret ninja implimentation for Sony and was trying to smuggle out trade secrets in the source code...........

      always think on your feet!

      --
      Check journal for info on Anti-TextBook, an idea by me.
    2. Re:Quality not quantity by apk · · Score: 1

      Mod the parent up.

      I've hit every one of these issues in actual embedded telecom code -- sometimes it's scary what you come across. And if that phone call of yours drops, please don't blame me...!

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

      Amen. Had one fellow developer write if-conditional tests with 6+ elements (no sin when it's needed, of course), but the SOB used bit-wise operators (XORs especially) where ever and whenever he could, and trying to figure out just *what* was attempted to be tested for was literally an exercise with pencil and paper. And need I mention that there wasn't an explanatory comment anywhere in sight...? Didn't think so.

      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.


      At least you had the opportunity to confront him. Writing that sort of $hit when you're getting paid for it and knowing that others will have to follow you should earn an immediate bitch-slap. I was literally confronted with such a situation today where misleading (not just obtuse) information caused me and another developer to go down a dead end. Fortunately for the author he's out on vacation, but he'll be back... ;)

      I'd add another suggestion regarding comments that will save you time down the road:

      Don't comment what you're coding, comment why you're doing it.

      The code already tells me what it's doing, but I need to know *why* it's being done here and now, and why that function exists, and why this test is relevant here. The 'why' gets into the bigger picture of what's trying to be accomplished, and keeping that in mind while digging through all the details of [likely someone else's] code is often difficult but important to do. And 6 months from now you'll look at your own code and wonder what you were thinking, guaranteed. Then those few but important "why's" will be worth it 100-fold.

      Andy

    3. Re:Quality not quantity by el-spectre · · Score: 1

      I have made a solemn vow to hunt down and hurt anyone who puts "clever" code in my project.

      When I realize I'm being clever but not clear, I'll rewrite the code, but leave the 'clever' code there, in comments, just to assuage my ego... should I still be running?

      --
      "Faith: Belief without evidence in what is told by one who speaks without knowledge, of things without parallel." - A.B.
    4. Re:Quality not quantity by SpacePunk · · Score: 1

      Well, I'm guilty of #5. Iterative loop variables that do something relatively mindless I name 'Gilligan'. Control variables I name 'Skipper', and clever things I name 'professor'. Of course I do comment what they do and how they do it, but, yeah, guilty as charged.

    5. 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?

    6. Re:Quality not quantity by Anonymous Coward · · Score: 0
      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.
      Dude, you work in the game industry, and you wonder why people like to use little_ninja for their comments? Lots of people who work in the game industry have the mentalities of 12 year olds, at least when it comes to humor. :) I still remember reading about how Maxis could never put out a decent patch for the DOS port of SimCity 2000 (Maxis use to write all their games for Mac first), because the DOS port programmer gave everything weird names like "spootyStruct".
    7. Re:Quality not quantity by syousef · · Score: 1

      1-4 is fine, provided that the programmer is given the time to do the job right. It isn't always that the programmer is lazy - it's that they're given 5 minutes to change the code when the manager/user/customer changes their mind about what they wanted at the 11th hour. I think it's more often a case of time pressure than programmer laziness.

      5. is a sign of immaturity. I've seen "business logic" code that would print out conversations between spock and kirk on a random day if a given function is called, other code that prints "global world domination has failed" if a failure condition occurs, and plenty of code with stupid variable names/puzzles, bits of not so funny nerd humour strewn in. Like a naughty child this programmer needs to be corrected if he refuses to grow up when he's caught out.

      Start by documenting all the code he's done this with, and having a chat with his manager. You need to get that manager on side and have him sat down and told he'll need to fix it and/or never do it again on pain of being fired. If his manager doesn't listen and you can afford to do it, I'd definitely go up the chain until someone has him fix his ways.

      --
      These posts express my own personal views, not those of my employer
    8. Re:Quality not quantity by Anonymous Coward · · Score: 0

      You really should stop this. Your are making someone else life miserable.

    9. Re:Quality not quantity by avandesande · · Score: 1

      Interesting comment. I almost always see junior programmers assigned with refactoring tasks, while refactoring really takes somebody with experience and skill.

      --
      love is just extroverted narcissism
    10. Re:Quality not quantity by MagikSlinger · · Score: 1
      I'll rewrite the code, but leave the 'clever' code there, in comments, just to assuage my ego... should I still be running?

      No. I'll just flick your forehead. :-) At least you know it's wrong.

      --
      The bitter lessons of a veteran coder: http://bitterprogrammer.blogspot.com
    11. Re:Quality not quantity by SpacePunk · · Score: 1

      MaryAnn of course. Pretentious variables get Ginger.

  114. plausible deniability? by __aaitqo8496 · · Score: 1

    Where's plausible deniability when I need it?

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

    2. Re:What do you guys think of the following code? by francisew · · Score: 1

      hehe. Nah, I'm just finishing my Ph.D., and this is a pretty meaningless snippet of data-processing code anyways. He wouldn't care that it's here.

    3. Re:What do you guys think of the following code? by kryptkpr · · Score: 1

      Code like that is why I love Matlab's auto-indent feature..

      --
      DJ kRYPT's Free MP3s!
    4. Re:What do you guys think of the following code? by marcosdumay · · Score: 1

      He probably pasted that from the prompt, since MathLab's prompt doesn't accept line breaks. It also doesn't accept comments, since comments spans to the end of the line and you don't have line breaks.

      MathLab language is not very clear even if you write it right. Also, it doesn't help people writting better programs, since the prompt is so bad. But, yes, your supervisor's code is bad.

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

      Sadly enough, I *know* that he didn't paste it from the prompt. But even if he did, shift-enter allows newlines on the prompt without immediately executing the code. (hence, you can write something like the following snippet right on the command line :)

      % print the fibonacci sequence
      t=[0,1];
      for i=1:10;
      t=[t(2),sum(t)];
      disp(t);
      end

      And yes, I do include comments right on the command line, because matlab keeps a history of commands, and I tend to go back to copy/paste stuff into new segments of code.

    6. Re:What do you guys think of the following code? by francisew · · Score: 1

      Except auto-indent doesn't add the line breaks where necessary to get one command per line.

  116. Reparse comment by ta+bu+shi+da+yu · · Score: 1

    I originally thought you said MDMA... in which case, sure! That solves everything.

    --
    XML is like violence. If it doesn't solve the problem, use more.
    1. Re:Reparse comment by Anonymous Coward · · Score: 0

      lol.. nice.

      MDA = Model-Driven Architecture

      Its being pushed by OMG, although Micrsoft is creating their own version (Model-Based Architecture) in VS. I figure it will be like CORBA, the standard only partially successful but the varients (RMI, Web services) heavily influenced and used.

  117. MOD PARENT DOWN by Anonymous Coward · · Score: 0

    Parent's views are stinking with prejudice and don't deserve any postive mod points.

    Parent is a racial bigot, okay??!!??!

    And BTW, I am American with no direct Asian ancestry... Not sure I want to be proud to call parent American though.

    1. Re:MOD PARENT DOWN by Anonymous Coward · · Score: 0

      You, sir, seem to be unaware of outsourcing software. Its nothing against Indians as a people, it just so happens that Indians are a source of cheap labor. Plus, it seems to me that the OP doesn't really like that situation.

  118. Ideally... by xelph · · Score: 1

    One should start by writing the documentation for classes and interfaces, including for properties and methods. Then, one should write procedural pseudocode in english (or similar language) for the body of each method, as comments. The final step should be to write the corresponding Java code below the pseudocode. The biggest issue with that approach is documentation maintenance, which requires a great deal of discipline. But as they say, garbage in, garbage out.

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

    1. Re:Speak, Memory! by Anonymous Coward · · Score: 0

      you = Man.new(:the)

    2. Re:Speak, Memory! by Narchie+Troll · · Score: 1

      Go to NaN and beyond?

  120. Be wary of missing the point... by Anonymous Coward · · Score: 0

    A lot of people, myself included at one time, rightfully concluded the _particular_ people going on about comments were at best misguided, or at worst looking to fire people.

    That said my own opinions have progressed (regressed?) a bit. I make no claim that any of this will work in the face of grossly incompetent developers, but neither will anything else. Furthermore I'm only talking about comments/documentation for internal consumption, not about API docs or header comments or anything else like that.

    Lots of code is effectively self-documenting. There are a great number of self-explanatory idioms that any competent programmer should immediately recognize. These will vary from place to place, but there are basic ones like iteration and recursion, swapping variables, and so on that just don't need commenting in and of themselves. One exception to this is to make up for a language deficiency. For example when writing java (ugh 1.4) I always put a comment next to a Collection declaration saying what exactly it's a collection of.

    The more interesting and important comments are algorithmic comments. Any time I implement a non-trivial class, I try to write up a full semi-formal description of any non-trivial algorithms implemented. Then I use that as an effective specification for implementing the actual code. The point is at least two-fold, to get myself to really comprehensively think about all the cases that need to be dealt with, and so when in the future I can figure out what the code is supposed to be doing. Obviously some discipline is required. I find it helpful to not think of keeping comments up to date with the code, but rather keeping the code up to date with the comments. Although I am not directly familiar with any literate programming tools, from what I've read it seems like it's a more formalized version of this approach.

    The programming process involves significant meta-data which is not in the actual code. This is what needs to be commented. Code does an excellent job of telling you what is being done and how it's being done, but only comments can tell you why the programmer thought it was a good idea at the time, and what the programmer thought it should be doing.

  121. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    Or the converse: they turn out reams of repetitive documentation, but you still can't make sense of the code. I've seen this first-hand, and it's monstrously frustrating.

  122. 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.
  123. An argument against comments by CrazyJim1 · · Score: 1

    I talked with a programmer who's been in the buisness for a while. He claims, long variable names, and functions that say what they do is more important than comments.

    He goes on to say that as you change the code, and forget to change the comments problems arise. But if you make your code readable, then you almost don't need comments.

  124. Literate Programming ... rejected 1500 to 1 by sidles · · Score: 1

    This guy *loves* Donald Knuth's literate programming. So does our UW Quantum System Engineering (QSE) Group ... we call it "Literate System Engineering".

    However, upon consulting the INSPEC database of academic abstracts, 1955 to 2005, we find:

    Containing the word "Programming": 124252 abstracts
    Containing "Literate Programming": 81 abstracts

    So the harsh truth is, only a tiny fraction (1/1500) of academic software projects mention it.

    How many (if any) SlashDotters use Literate Programming regularly?

  125. Re:And this, my friends, is why offshore outsourci by kgruscho · · Score: 1

    Pretty much any Indian with the education to program spoke english before they programmed.

    Many (i.e. millions) of Indians speak Egnlish natively. English is a global language and just because Indian English does not always soudn the same as American does not mean they cannot speak English.

    I have to admit that often times my Indian peers at school know the language better than I do.

    http://en.wikipedia.org/wiki/Languages_of_India/ http://timesofindia.indiatimes.com/articleshow/558 981.cms/
  126. FastCompany: "They Write the Right Stuff" by Anonymous Coward · · Score: 0

    You've just described how the folks who program the Space Shuttle's computers code. Unfortunately, convincing management of the wisdom of this approach will be difficult.

  127. Other ideas for making code easy to read by Error27 · · Score: 1

    Of course, there are a lot of things that programmers can do to make code easy to read, but I'm quite interested in the things that computers can do to make code easy to read.

    For example lxr.linux.no is great but it would be even better if it was integrated into the editor. They say etags is the same, but I've never been able to make it work.

    Another thing that would be great would be color coding for bugginess. There are a bunch of different static analysis tools that could generate a bugginess value for each line of code. Also really picky indent color coding would be nice.

    Another thing would be better integration with the CVS. Something like this perhaps. It would be handy to know if a bug only affected 2.6 or if it went back to 2.4 as well.

    Those are some ideas. Gotto run.

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

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

  130. I'd say both by Tamerlan · · Score: 1

    For any non-trivial software system you need comments AND meaningful names.

    I found that while meaningful names are useful to describe how program works in terms of a language, comments are needed for a proper mapping to a domain area.

    I found commenting conditionals and switch bracnhes particularly useful - in a comment I explain for which situation in a problem domain that was done.

    I also find very useful to put problem-tracking references (like PR31337) useful, when I need to fix some problem report or implement a small feature. Later, that _will_ help you to understand WTF this kludgy code does. It even may save your butt if you are stupid (or inexperienced) enough not to have unit and regression tests.

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

    1. Re:There will always be losers by Anonymous Coward · · Score: 0

      Just because you can read the tea leaves if someone eats them and shits them back out. Doesn't mean this should be the preferred method of telling the future.

    2. Re:There will always be losers by dgmckay · · Score: 1

      You're right about that. The good sustainers are usually the last ones left in the building, if only because products are usually sold with an agreement to maintain support for X number of years. Even if the product is ultimately a failure in the marketplace, the few customers who bought and deployed it have a contract that says they'll get maintenance releases for X years.

      Unfortunately the higher-ups see that sustaining effort as purely a cost, so it's now one of the first functions they attempt to outsource.

    3. Re:There will always be losers by Anonymous Coward · · Score: 0

      Right on, losers like... Linus Torvalds.
      Sorry, but I think the loser is *you*.

  132. short, descriptive variable names by readin · · Score: 1

    short, descriptive variable names

    Sounds like an oxymoron to me.

    With cut-and-paste and modern editors, there is little reason for short variable names.

    Structure is more important than documentation because you can't document something that doesn't make sense, and even if you could you wouldn't know where to put the comments. In a well structured program each section (not each line - that's overkill) will have a clearly defined purpose and comments will be easy to write.

    --
    I often don't like the choices people make, but I like the fact that people make choices. That's why I'm a conservative.
  133. Why I think it's difficult by Paradise+Pete · · Score: 1
    For me to code well I have to hold in my brain a complex picture of what I'm doing. If I stop along the way to "explain" and translate into English what I'm doing then the picture begins to degrade, and I lose my momentum.

    It's not out of laziness, I just don't have the mental capacity to be able to stop and thoroughly comment and also maintain that mental picture. Ideally I would go back later and comment what I've done, but of course what happens in practice is that I continue on with the project. Yes this causes me to have poorly commented code. And as usually I'm the only audience for my code, I'm the one who suffers for it later. But I don't have a good answer. I'm not making excuses for not commenting well, I'm trying to explain why, for me at least, code tends to be poorly commented.

    1. 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
  134. Re:And this, my friends, is why offshore outsourci by (SM)+Spacemonkey · · Score: 1

    /. needs to cut back on the rampant cultural stereotyping. I fail to see how Indians are innately less intelligent, or would make lesser engineers than their American counterparts, simple because they are Indian. And might I add that a large reason India is so useful for outsourcing is, as a former British Colony, it has sizeable English speaking populous. The Indians I know speak English very well, and their language construction is better than many Westerners. Just try to get used to the accent. Which is somewhat less chanllenging with comments in code...

  135. 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.
    1. Re:Good comments are good by el-spectre · · Score: 1

      I'm glad to see I'm not the only person who comments with "we"... ya think maybe this is a learned from programming classes?

      --
      "Faith: Belief without evidence in what is told by one who speaks without knowledge, of things without parallel." - A.B.
    2. Re:Good comments are good by localman · · Score: 1

      Heh... I would say "no" just because I never took any programming classes! But I do use "we" all the time like that. I don't know why I feel comfortable speaking for the whole team :)

      Cheers.

    3. Re:Good comments are good by Chemisor · · Score: 1
      // 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;
      I wouldn't call it a good comment. I would call it bad design. If you have to explicitly ignore the root node here, you probably have code elsewhere that needs to do the same thing. It's a breeding ground for bugs. Just put the damn node into the database. It's not like you've only got 64k to work with...
    4. Re:Good comments are good by localman · · Score: 1
      Oh come on, I said it was just an example. Maybe I'm dealing with a pre-existing system that depends on this setup. Maybe this code is encapsulated in a module and I won't need to do it anywhere else. The point is that the comment elaborated on code that was already "clear" (how much clearer can you get than incrementing a number) in a way that only a comment can.

      Have you ever worked in the real world? Ever stayed at a company for more than a couple of years? Then you've got to know what I'm talking about. No matter how perfect you try to design your system you will come across points where you have to do something arbitrary like this. When you do, a comment is invaluable. Heck, I could just has easily have made it:
      // the total includes the root node of the tree
      // since there's an entry for it in the DB, but we don't
      // want to include it in the count...
      --total;
      Now what am I supposed to do wiseguy? Maybe sometimes I need it included and sometimes I don't. Good design doesn't make comments any less important.

      Cheers.

      Cheers.
    5. Re:Good comments are good by Chemisor · · Score: 1
      > Have you ever worked in the real world?

      Funny you should ask that. In the real world, I seem to do little but rewrite bad designs into good ones. When I see a situation such as the one you described I don't write a comment; I go to whoever is responsible for it and work with them to rip it out and make the design right instead. If that person no longer exists for some reason, I rip it out myself. I consider this to be a good thing, and my boss usually agrees because he can see how it benefits the product.

      > Now what am I supposed to do wiseguy?

      Ok, so maybe you just don't have time right now to redesign your database. Maybe the product is shipping in a week and there is no way in hell you can implement anything sane in that timeframe. What you should do is write the comment, but in such a way as to make it absolutely clear that what you are doing is a hack. Then, when your crunch time is over, fix it!
      // Explicitly count the root node which is not
      // actually present in the database.
      // \todo Redesign the database to include a dummy root node to replace this hack.
      If you don't do this, it becomes a permanent hack that needs to be documented everywhere. Whenever you add new code you'd have to include comments just like it about how the design sucks and you've got to do it this way. And the generations of programmers who have to maintain your code will forever curse your name for not correcting the design and causing them thousands of hours of pain when one of them is not told that the root node doesn't exist and has to spend a weekend debugging some unexplicable problem.

      > Maybe sometimes I need it included and sometimes I don't.

      Like this one. When I hear a statement like this I instantly know your design is bad. It tells me you have an unnecessary special case that everyone needs to know about. I don't even have to look at your code. I know. In a good design there are no ambiguities. Just put the damn node in the database! I bet it would take you less time than it took you to write all those special case comments I know you have all over the place.
    6. Re:Good comments are good by localman · · Score: 1

      In a good design there are no ambiguities.

      I don't know what planet you are on my friend. I wish I could visit you there :)

      By the way, you didn't seem to read my second example properly. If you need it both ways, (a situation that often arises when the real world meets the virtual world) you're going to have to hack it one way or the other and the hack will stay.

      I don't believe I've ever come across a piece of widely-used code that didn't have at least a few hacks like this ... ones that couldn't be resolved without limiting functionality.

      And there are those who would argue that functionality would be best limited in that case. Personally I feel that the code exists to serve a need, not to be pure and pretty. If you feel differently and can convince those around you of such, more power to you.

      Cheers.

    7. Re:Good comments are good by Chemisor · · Score: 1

      > I don't know what planet you are on my friend.

      We call it Earth, what do you call yours? ;)

      > Personally I feel that the code exists to
      > serve a need, not to be pure and pretty.

      And that is exactly the difference between us. You're an engineer, I'm an architect. You want things to work, I want them to be perfect. You want everything done as soon as possible; I'm willing to wait a few weeks for a better solution. Ultimately, we need each other. Without me, you'd live in a world where everything's a hack. Without you, I'd live in a world with nothing in it :)

      > If you need it both ways, you're going to have to hack it one way

      If you need it both ways, then you're probably confusing the model with its view. The solution is to factor the model into a third way and make the other two ways view it. That way it stops being a hack and becomes a feature. You let data be data and the presentation be a weird special case that happens in only one place. If anyone asks, blame it on the spec. Naturally, for more details you'd have to be more specific.

      At this point I would also point out an exception to this rule, and that is if your application framework forces a hack on you. If you use a third-party application, as most people do, you know that everyone who doesn't work at your company is a complete idiot and couldn't see a good design if he was hit on the head with it ;) In this case, there is often no recourse other than a lengthy comment. I've written a few of them in my time, concerning the Win32 API, if you know what I mean :)

    8. Re:Good comments are good by localman · · Score: 1

      And that is exactly the difference between us. You're an engineer, I'm an architect. ... Ultimately, we need each other. Without me, you'd live in a world where everything's a hack. Without you, I'd live in a world with nothing in it :)

      That's quite a nice way of looking at it. I accept your description.

      One note: I'm an architect at heart -- when I design stuff for myself I want to get it perfect. I've just never been able to maintain that at work.

      Cheers.

  136. What about TDD lessons? by Anonymous Coward · · Score: 0

    Unit tests and small, well-defined classes resulting from TDD have done more for me in understanding very complex systems than comments in poorly conceived or over engineered code.

    1. Re:What about TDD lessons? by aduzik · · Score: 1

      True, but TDD is an agile methodology. And if you're doing agile, that probably means that you're collaborating with other people. The tests go a long way toward explaining what the interfaces are supposed to do, but the implementation might still be non-obvious. I don't think you need nearly as many comments when you do TDD, but they're still great to clarify things that may have become unclear when you you refactoring. Also, I like to use comments like "tabs in a 3-ring binder" -- to separate source files into nice, neat sections.

      --
      If it's not one thing it's your mother.
  137. Who's right? by KidSock · · Score: 1

    Writing clear code in the first place is your best option. If the code is concise and well written it is easy to understand and an joy to work with. Of course there are always instances where something requires a tight loop or you're interfacing with an external API that is not consistent with the calling code. In these cases you need comments. Use your head. Don't comment or not comment as some kind of religion. If the code is hairly comment it. If the code is obvious don't comment it (and not because you don't have to - it's an annoying distraction to read useless comments).

  138. 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 Brandybuck · · Score: 1

      Until you end up trying to fix a bug five or ten years down the line. Those tests don't do you jack if all they do is tell you there's a bug. Duh! Of course there's a bug! That's why I'm knee deep in this uncommented shitfest trying to figure out what the heck Joe Schmoe was smoking when he originally wrote it!

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

      --
      Don't blame me, I didn't vote for either of them!
    2. Re:Tests are more important than comments. by Compay · · Score: 1

      I agree wholeheartedly with the parent. Of course, as anything that's often associated with Java, people will just dump on Test Driven Development as another "buzzword," rather than try it.

      Using well-established design patterns where appropriate is another helpful technique that is also susceptible to rejection by the smug ignorant hordes of people screaming "Java buzzword!"

      I hate reading code written by someone who finds 10 different new ways to solve the same old problem, does not understand the core libraries of the programming language they're using, or invents their own unique terminology for reasonably standard, straightforward things.

      Read lots of other people's code. Read the classic literature of the field. Study all the standard libraries at your disposal. Don't reinvent the wheel. When given the choice between a clever solution or a straightforward one, choose the straightforward one. If you're using an object oriented language, a class-level comment with a couple of sentences explaining what your class does should usually suffice unless your class does something unusual. If you can't sum it up in a few sentences, you probably should break your class into smaller pieces that are easier to explain.

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

    4. Re:Tests are more important than comments. by refactored · · Score: 1
      Contrariwise.

      Tests are themselves a powerful commentary on the code. They explain graphically what the code does, and in what manner and what order.

      However, tests are code too, and are as prone (if not more so) to being as badly written as code.

      Which is why Refactoring and TDD go hand in hand. Refactoring improves the code, especially from the clarity and simplicity point of view. However, to refactor effectively and safely, you need a good framework of tests to preserve the functionality.

      There is a very nice dualism between tests and code. Tests test (and comment) the code, Code tests (and comment) the tests.

      Another good duality is Design by Contract. I use unit tests to constrain the public interface to my code. I use Design by Contract assertions to constrain the private workings of my code. DbC assertions are like coded comments. Think of a comment that asserts that something is true about this code. An assertion turns that comment from a warm fuzzy feeling into a hard fact.

    5. Re:Tests are more important than comments. by dubl-u · · Score: 1

      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.

      Yes! Good tests are documentation that a computer can automatically validate.

    6. Re:Tests are more important than comments. by Anonymous Coward · · Score: 0

      Study all the standard libraries at your disposal.
      Unless you're using Java, in which case study something that actually explains said libraries because whoever first developed the damned things didn't bother to follow any of these recommendations on variable naming, etc.

    7. Re:Tests are more important than comments. by Brandybuck · · Score: 1

      Sounds like you haven't written many unit/functional tests.

      Actually I have. And heretic that I am, I COMMENT the tests I write!

      You seem to be operating under two wrong assumptions. The first error is assuming that tests document the code. They do not, they only test the code. The fact that f(x) succeeds with all possible values of x doesn't help me a damned bit if I'm trying to figure out what the heck f(x) does.

      Your second error is assuming that tests prevent bugs. They do not, they only find a few potential bugs. Thus, when someone five or ten years down the line has to fix a real live genuine bug, he'll need comments to understand the code. Your existing tests won't help him, because your existing tests didn't find the bug. He's going to have to write a new test to cover this case.

      I really don't understand why you don't want people to comment. It isn't an either-or proposition. Comment AND test. Sheesh. If you're having problems writing comments, may I suggest you take a writing class?

      --
      Don't blame me, I didn't vote for either of them!
    8. Re:Tests are more important than comments. by refactored · · Score: 1
      As the poster who started of this thread, can I point out I merely said "tests are more important than comments". ie. Given the choice of only tests xor only comments, I will have tests thank you.

      However, my code always has unit tests, DbC assertions and comments.

      I'm also always nagging folk on the subject of comments. Don't bother with comments that can be trivially deduced from just reading the code. Remember humans are input bandwidth limited. ie. We are limited in understanding reams of code by how fast we can read. Thus trivial comments slow us, rather than help us. Always comment at a higher semantic level. State eternals truths (always call this after that or Bad Things happen) about the code, not chat about the current weather. (Nice parameters we're having today...)

    9. Re:Tests are more important than comments. by rossifer · · Score: 1

      I COMMENT the tests I write!

      Well, I'm all for that. Explaining what conditions the test is exercising is pretty darned important to having a sane test.

      The first error is assuming that tests document the code. They do not, they only test the code.

      Agreed. Though well-written tests can provide information about the intent of module usage (since they're an example of using the module being tested), they are not true documentation.

      Your second error is assuming that tests prevent bugs.

      I don't make that assumption at all. I know for a fact that tests capture a large fraction of coding errors early in the process. This doesn't mean that unit tests can catch all coding errors, nor does it mean that they can prevent future bugs.

      What you can say is, "What has been tested is known to work correctly." Everything else in the system is still a risk and if the tests don't reflect actual usage of the module being tested, they're pretty much worthless.

      I really don't understand why you don't want people to comment. It isn't an either-or proposition. Comment AND test.

      Sounds fine to me. My typical plan for comments is to add them to methods where there are more than three steps or where the names of variables and methods in a block of code are not adequately self-documenting (usually when calling out to third party libraries).

      My posting was an objection to the apparent assertion that unit tests are worthless because they don't help find the bug. The statement is wrong because even a poorly documented test narrows down where the problem lies and the automated test tells you there is a problem early in your development process.

      Regards,
      Ross

    10. Re:Tests are more important than comments. by Brandybuck · · Score: 1

      Correction: "What has been tested is known to work correctly under the assumptions of the test."

      --
      Don't blame me, I didn't vote for either of them!
  139. The Laws of Software Process: by Anonymous Coward · · Score: 0
    http://www.amazon.com/exec/obidos/tg/detail/-/0849 314895/qid%3D1114571928/sr%3D11-1/ref%3Dsr_11_1/10 3-1423434-5408606?v=glance&s=books


    "Within one generation, software has become one of the principal sources of wealth in the world. The development and use of software has grown faster than for any artifact in the history of the world. Probably no topic or subject in history has accelerated in its rate of practice as software has. Software development now needs to mature into a disciplined activity to overcome the difficulties that have traditionally plagued it. Software developers, engineers, and project managers need a reference that describes the evolution of software: where it has been, and where it is going. The Laws of Software Process: A New Model for the Production and Management of Software reveals a novel and compelling structure for development that redefines the very nature and purpose of software. The author explains how, in the modern "knowledge economy," software systems are not "products" in the classical sense, but is the modern medium for the conveyance of information. Literally, software is the currency of the knowledge basis of wealth in today's society.From this definition flows a new assessment of the basics of software development: the purpose of methods and processes; a comparison of programming languages; and an analysis of quality management, cost estimation, and project management and completion. The groundbreaking perspective outlined in this book serves as an expert guide for successful planning and execution of development projects."
  140. 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.

    1. Re:I learned the hard way by mretallack · · Score: 1

      I agree completely, while at collage, comments where something someone else does. It was only when I had so support someone else's code that comments became important. After that experience I always start with the comments and then fill in the code. The second most important thing is always a spell checker that can handle C or CPP code.

  141. Your colleagues by Jesus+2.0 · · Score: 1

    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.

    Your colleagues are idiots.

  142. how to write unmaintainable code by krunk4ever · · Score: 1

    How To Write Unmaintainable Code

    In the interests of creating employment opportunities in the Java programming field, I am passing on these tips from the masters on how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldn't be able to maintain the code!

    You don't want to overdo this. Your code should not look hopelessly unmaintainable, just be that way. Otherwise it stands the risk of being rewritten or refactored.


    i read this article a few years ago and personally found it interesting. as i bolded out, documentation is important even for yourself. it depends on your motive for or for not including good comments for your code. if you're on a team, good comments helps speed up the project. if anyone else will be reading your code and using it, i think it's personally quite important to leave comments especially on what the function does and how to use it.

    on the other hand, as this article states, if you really really want to keep your job... then useful comments are totally unnecessary for that'll only help the guy that's coming along to replace you. ;p

  143. Xtreme Programming by thisisauniqueid · · Score: 1, Flamebait

    Right. When XP-heads tell you not to comment your code because it's not Xtreme, tell them they're wrong.

  144. My Preferred Solution by Principal+Skinner · · Score: 1
    Sugar water.

    Now, how I handle the indent issue (if tabs are involved) is:
    (defun tabwidth (width)
    (interactive"NNew tab width: ")
    (set-variable 'tab-width width))

    (global-set-key "\M-t" 'tabwidth)
    Then, just M-t every time you want to change the tab spacing, so that it matches the indentation of whoever last edited that section of the file.
    --
    one hundred twenty
    is just enough characters
    to write a haiku
  145. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    Your links don't seem to work. (Hint: not all URLs need trailing slashes...)

  146. Objective-C by HitByASquirrel · · Score: 1

    Even in a language that is supposedly "self-documenting" like ObjC just from the naming conventions, I find that it's much easier to work with the code if about 20% of the lines in the codebase are comments (including those in header files).

  147. Code comments by cparisi · · Score: 1

    Many times comments are out of date.
    The code tells me exactly what is going on.

  148. I have to wonder... by NoMoreNicksLeft · · Score: 1

    Why are we keeping source code and comments in the same file? What would be nice, would be a editor that keeps them in 2 different files, say, file.c and file.cmt or such such, but when you want, with a single keystroke toggle, superimposes the comments in your source. The comment file format would need some metadata, to show where it should appear, I'd think.

    1. Re:I have to wonder... by justine_avalanche · · Score: 1

      Some IDE do this for javadoc for example (I know Eclipse does), but I see your point.

    2. Re:I have to wonder... by swordgeek · · Score: 1

      Why? What benefit would this actually serve?

      I'm honestly curious. I can't imagine why this would be a worthwhile thing.

      --

      "People who do stupid things with hazardous materials often die." -- Jim Davidson on alt.folklore.urban
    3. Re:I have to wonder... by NoMoreNicksLeft · · Score: 1

      I'm not sure I'm articulating it correctly. The idea is still rather fuzzy.

    4. Re:I have to wonder... by MikeBabcock · · Score: 1

      I can see the point for certain details that are too detailed to fit into the code; I've seen code with a paragraph of comments in between each statement, to explain why certain options are the way they are (often device drivers).

      That said, I'd prefer an editor that simply shortens such comments to /* This option takes [...] */ and lets me hotkey on the [...] to get the rest.

      --
      - Michael T. Babcock (Yes, I blog)
  149. 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 Rasta+Prefect · · Score: 1
      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?".

      You know, I can't exactly put my finger on why, but for some reason I hear something screaming FORTRAN-77! FORTRAN-77 was big on column numbers being significant. I've had at least one engineering student flat out not believe me when I told him why....

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

      ...Say, have you ever checked out www.thedailywtf.com?

      --
      Why?
    2. Re:semicolons in column 80 by rve · · Score: 1

      FORTRAN only reserves the first 6 columns for comments. This is much worse (and also far more widely used)
      I wouldn't be surprised if a previous job in that caused your coworker's brain damage

    3. Re:semicolons in column 80 by Anonymous Coward · · Score: 0

      ...Say, have you ever checked out www.thedailywtf.com?

      Never been there before, but I was amused to say the least. Thanks for the link. I'll think I'll have to start visiting regularly.

    4. Re:semicolons in column 80 by dmitriy · · Score: 1

      > FORTRAN only reserves the first 6 columns for comments

      I am afraid you are totally wrong. Even if I didn't touch Fortran for at least 15 years, I still remember the Fortran program formatting:

      5 columns for numerical goto labels
      6th column is for continuation mark
      columns 7-72 for program statements
      columns 73-80 are for comment-like sequential numbering, very handy if you need to reassemble a dropped punchcard deck.

      Comments are marked with letter C in the first column and take the whole line.

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

    6. Re:semicolons in column 80 by Anonymous Coward · · Score: 0

      So you're a girlie? Say, what're you doing tonight? Can I ... code with you?

    7. Re:semicolons in column 80 by SComps · · Score: 1

      No, I'm not, but would you be offended if I said yes? *grin*

    8. Re:semicolons in column 80 by rve · · Score: 1

      Worse is, a couple of years of work experience in RPG programming do not count as work experience in ICT.

      It will look about as good on your resume as a couple of years of doing accounting.

  150. Well, lessee.... by CPNABEND · · Score: 1

    Short variables should be enough? Maybe, let's look at some sample code:

    p_var = party
    b_var = beer
    c_var = coolers
    .
    .
    10,000 lines of code later:
    .
    .
    p_var = b_var + c_var

    It will make perfect sense, no?

    --
    My wife doesn't listen to me either...
  151. 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.
  152. 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.

  153. Comments important but not TOO much! by Man+in+Spandex · · Score: 1

    What is worse than a lack of comments? useless/redundant comments!

    final int iPENISSIZE; // store penis size

    well no shit sherlock!

    What I'm getting at is very basic and it's no secret to us. Our goal is to write code that will make a coder understand what the system has to do regardless of who looks at it(programmers obviously.., not martha stewart and when. If that can be achieved, than I think that the programmer who originally wrote the code did his job right.

    My beef with this part of programming is the following. I'm in my 2nd year in computer science and what was common is when the teacher asks for commented code, students would put obvious comments (commenting things that are self-explanatory) because we're naturally lazy (I fucking am) but this is IMO a bad habit because you just read things that aren't helping you and what you want is help/clarification! Something like

    final int iPENISSIZE; // store average martian penis size for later comparison with human penis size

    We just recently started writing GUIs in Java. Because the GUI part makes our program bigger and the code longer, organization within the classes became more important than when we didn't do GUI's so I was thankful that I wrote comments before even started coding as the programs became bigger because it saved me a shitload of time.

    I think the teachers should try to get the students on the right track and make them get "good" habits to later not get b0rked when things become more complex.

  154. The design is the code by rakeswell · · Score: 1

    I recently read the Jack Reeves article What is Software Design?. His thesis, really, is that the code is the design. I didn't really want to accept this at first, but I do see that there are some benefits to looking at it this way. In fact, I think that if one were to take this to heart while coding, the result will be better, more intelligible and maintainable code.

    Quality comments are one aspect of this (and I think that javadoc, for instance is a great tool). But just as the code isn't static, the comments need to also get updated, and it's fairly easy to refactor a method and forget to update/redo the comments.

    Another thing I don't usually see enough is coding to actually check whether input parameters are valid, or otherwise enforcing the "contract" between a class/method and it's caller. Simple, basic stuff, but I know what happens when fatigue set in and people are hurrying to meet deadlines.

    --
    All one has to do is hit the right keys at the right time and the instrument plays itself. - Johann Sebastian Bach
  155. Reviewing for Readability by Bob+Munck · · Score: 1
    Does anyone, anywhere ever review code for readability? We all know that code reading, be it in eXtreme programmer pairs or more formal CMM processes, is as close as we've come to a Silver Bullet for programming. With all that review going on, does anyone have built into their processes a review specifically for how easy or hard the code is to understand?

    I worked for a great little company named SofTech many years ago, where we developed an analysis and design methodology named SADT (aka IDEF-0). One of the important parts of it was a set of steps to make sure that the documents being produced were readable and understandable, under the philosophy that something that was correct but impossible to understand was a lot less useful that something that was wrong and understandable. For the latter, you could tell it was wrong and figure out how to make it correct.

    It's always seemed to me that this is one of the major parts missing from Open Source. Note that this makes moot the question of whether you make it understandable by writing lots of comments or by using a good programming language; either one will pass the test.

  156. 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 Anonymous Coward · · Score: 0

      come on, that's funny as hell

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

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

      hehehe..

    4. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 1, Insightful

      You forgot to mention the restriction that x cannot equal 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, ...

    5. Re:Top Ten Code Comment Do's List by Coryoth · · Score: 1

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

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


      Or you could use a language that has Design by Contract and simply use the function contracts to do all of that for you - better yet you get the resulting effects of inherited contracts and so on.

      Or, to put it another way: That's such a good idea that we ought to be doing it all the time, in the code, and using the documented specification as something that can be compiled in for debugging purposes.

      Jedidiah.

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

    7. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      This reminded me of a time when I as teaching myself programming, I was about 8 years old and was writing a ascii gui based role playing game.

      At the ever end of the game you had to mix the correct two maic potions together, to win the game, i recall writing something similar to the following;

      if (potion_a && potion_b) then wrong_potion;
      if (potion_a && potion_c) then wrong_potion;
      if (potion_a && potion_d) then wrong_potion;
      if (potion_a && potion_e) then wrong_potion;
      if (potion_a && potion_f) then wrong_potion; .... etc etc .... there were like 64 combinations.

      However it didn't strike me until a few weeks later having completed the game that all I needed to do was;

      if (!potion_a && !potion_b) then wrong_potion; .. hahaha those were the days ;)

    8. 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"! :))

    9. 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."
    10. Re:Top Ten Code Comment Do's List by boomfart · · Score: 1

      or you could have 64 different endings. potion_a&&potion_b then blow_up; potion_a&&potion_b then Burn_to_ashes; Never admit to a mistake (bug) just turn it into a (undocumented)feature.

    11. 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)
    12. Re:Top Ten Code Comment Do's List by maxwell+demon · · Score: 1
      Even better:
      /* function: pi
      * calculates pi to an arbitrary number of digits (rounding downwards).
      * parameters:
      * digits: how many digits to calculate. Any unsigned long value is allowed
      * return value:
      * any of "3", "3.1", "3.14", "3.141", "3.1415", "3.14159", "3.1415926",
      * "3.14159265", "3.141592653", "3.1415926535", "3.14159265358",
      (a few days later the editor rejects all further input: Maximal file size reached)
      --
      The Tao of math: The numbers you can count are not the real numbers.
    13. 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.

    14. Re:Top Ten Code Comment Do's List by ColdGrits · · Score: 1

      Absolutely.

      Another advantage of your method is that the documentation for the variable is where it is defined - keeps the whole lot together in one logical place, rather than having the variable type and name in one location and then having to skip elsewhere to find the descriptive comment etc.

      Damned sight easier when actually working through the code rather than just glancing to see if it "looks" documented!

      --
      People should not be afraid of their governments - Governments should be afraid of their people.
    15. Re:Top Ten Code Comment Do's List by FireFury03 · · Score: 0

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

      I _really_ hate ASSERT() in it's usual implementation - it's broken. Yes, asserting that values are what you expect is a good thing, but the usual method for handling assertion failures involves forcably bombing the application. In some cases this is a reasonable idea (since you know something's broken it prevents bad data getting back into data files, etc). But for most cases I believe this is a horrendously bad thing - I would prefer a small amount of bad data to be saved back to my data files (and me informed about it) rather than the common practice of just blowing away all the data incase there's something wrong with it.

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

      (And yes, I know that planes have plenty of backup systems, but I've lost count of the number of times I've lost important data as an application bombs with an ASSERT() failure...)

    16. Re:Top Ten Code Comment Do's List by famebait · · Score: 1

      Here's my simple and easy recipe for ensuring compact intelligent comments, without feeling like extra work, and with the added bonus of helping you think more clearly:

      Write the comments first.

      Use several short, separate comments to sketch out a general plan (think "extremely rough pseudocode" / "table of contents") of how the section or change you're working on should work. Then fill in the actual implemntation code under each comment, leaving the comments in place.

      That way your become a helpful planning and focusing tool, rather than a chore for the benefit of others. And it pretty much ensures you're left with comments that actually say the stuff a reader wants to know (like the purpouse of stuff).

      If that still sounds like extra work, you should probebly start thinking through your code a bit more before you start typing in any case.

      --
      sudo ergo sum
    17. 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.

    18. Re:Top Ten Code Comment Do's List by nuremon · · Score: 1

      I've found that the difference between a bug and a feature is almost always point of view. At least where I work.

    19. Re:Top Ten Code Comment Do's List by bcd · · Score: 1
      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.
      Just use a decent source control system to track all of this. I've worked on projects where the source was cluttered with this kind of information, and it was incredibly distracting. Yes, it is a must have, but no, I don't need to see it all the time.
    20. 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!

    21. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      But then it wouldn't be funny

    22. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      Yeah, the new coding standards weren't a big hit in my project either.

    23. Re:Top Ten Code Comment Do's List by MalaclypseTheYounger · · Score: 1

      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.

      Yes, it makes search/grep/replace harder to do, but when you work on a 200+ DLL system, and eventually come upon a bug that started at XX date, you can easily revert back all your changes without having to read through comments and figure out what you changed. Just simply put back in the line you commented out.

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

      --
      Check out the best P2P sharing website: MEDIACHEST.COM
    24. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      And 2 - 4999 = -4997, which is only one possible return value. You don't need a function if it can only return one value.

    25. Re:Top Ten Code Comment Do's List by Chantay · · Score: 1

      I've been contemplating using the NDot open source utility for documentation. Has anyone here used it? I've heard some good things about it, and it certainly sounds better than using RoboHelp. Thoughts?

    26. Re:Top Ten Code Comment Do's List by Ripplet · · Score: 1

      Oh my, where to begin...

      >1. Comment each function
      Yep.

      > - Function name
      Why, it's there right next to the comment isn't it?

      > - what it does
      Yep

      > - parameters
      > parameter name - what is is for and any restrictions on it (i.e., must not be null)
      No, parameter use should be obvious from the function context and their names. In my experience this covers the majority of cases. For those that aren't so clear, add a little extra to the function description. Why force people to add a description every time when it's rarely needed?

      > - return value (all possible return values)
      Again this should be obvious from the function name and description. If not, pump up the description a bit. Similar reasoning to parameters.

      >2. Add comments to each file you modify so that over time, the file becomes better documented
      Agreed, but only to the bit you modify - if you just change a constant value or something you shouldn't have to then comment the whole file!

      >3. Add ASSERT() like comments and ASSERT() or equivalent to your code
      Maybe. But only where it's really useful. A lot of the time seeing this isn't actually any better than having the code simply crash, assuming you have a decent debugger.

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

      >5. Put in a '?' comment for code that you do not understand (good for function headers)
      Refactor code you don't understand until you understand it. This will be very easy if the code has proper unit tests associated with it. You do use Unit Tests? What's that, legacy code? Then you'll need to start with writing the unit tests first.
      The thing is, why do you need to understand it? Presumably you want to change it because it doesn't work or you need to extend it - so then you need the tests to (a) prove you haven't broken anything and (b) prove your new functionality works.

      >6. Avoid stupid naming schemes for your local variables since that makes it harder to comment
      Avoid stupid naming schemes for *anything* since that makes it harder to understand!

      >7. Review your code for both logic and comment completeness after you code it before committing it to version control
      Yep. Dare I mention Unit Tests again?

      >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.
      Gah, big no no, really BIG no no. Have you seen code that's had this done to it for more than a few months. No, because you can't see the code any more, just these damned tag comments. I'm beggin' yer, I'm pleadin' yer, don't do this. Besides which, they are completely superfluous with any half decent revision control system. If you don't use one of those, then go install Subversion NOW!

      >9. Format your comments so that multiple line comments line up on the left hand side (increases readability)
      Yep. It would be good if most tools did this, unfortunately most standard IDEs come with really crap editors, and even a good code editor doesn't always do this. This would be one of my main requests to code editor developers everywhere, please do auto-wrapping and alignment of long comments.

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

      My basic philosophy is to have clean code: make what you see in your code editor as simple as possible (but no simpler). That includes comments. So don't force people to always put a special extra line for each parameter even when it's really not needed.
      And don't duplicate stuff in the comment that you can see straight away from the code (e.g. function name).

      --

      Skiing? Check out The Independant Skiers Portal

    27. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 1

      as grant-parent already said:

      USE A VERSION CONTROL SYSTEM, STUIPID!

      Really: with this comment form, you are unlikely
      to redo complex changes correctly. With version
      control you can easily unroll each change, look
      what changed together, who changed it and when,
      and so on and so forth.

    28. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      But do not forget to rewrite all the comments after you have written to code to tell what it actually do.

      If you are from the "Just plan before what you will have to write"-team, get either some real programming experience or finally start to refactor your code to clean up all the workarounds for fitting things into you pre-thought design.

    29. 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.
    30. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      What about side effect?

    31. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      Dude, haven't you heard of recursion? Maybe it's time you hit the books again.

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

    32. 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
    33. Re:Top Ten Code Comment Do's List by Espen+Skoglund · · Score: 1
      3. Add ASSERT() like comments and ASSERT() or equivalent to your code

      I can't stress enough how important this is. Not only do asserts tell the programmer looking at the code what the assumptions and invariants are. Asserts also make sure that you are notified immediately when any of these assumptions are not met. This is particularly useful if the result would be incorrect but still usable (and hence not resulting in a crash), or if breaking the assumptions lead to a non-debuggable crash (i.e., within low level systems code).

    34. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      Heard of version control systems?

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

    36. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      Right. or you could just save a copy of the old code someplace. If you lack the space to save a copy of your old code (or a portion of it) then you are working on too tight a memory system.

    37. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      Version control won't work every time, with poorly written code you may have to search through several files and check the change history on each file. Leaving the code in in some cases is a good idea. If the change turns out to be fine, the next guy in can remove the commented out code.

    38. Re:Top Ten Code Comment Do's List by fraxas · · Score: 1

      THIS is the post that should be moderated -1 WRONG. If you're not competent to use the features of your source control system -- annotate/blame/praise -- or your organization isn't competent enough to use a source control system that supports those operations, you shouldn't be dealing with 200+ DLL systems.

      Your techniques may have been appropriate before we had source control systems that would tell us who changed what when. But if you're committing commented-out code to a source base, you're an idiot and I hope I never work with you.

    39. Re:Top Ten Code Comment Do's List by mwood · · Score: 1

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

      Good for you. This means you can often just copy the material from the design documents when you begin building the code.

      Why are you looking at me that way?

    40. Re:Top Ten Code Comment Do's List by dubious9 · · Score: 1

      Moderate -1, Naive

      you can easily revert back all your changes without having to read through comments and figure out what you changed.

      Thats what code versioning is for bud. The ability to go back to any version (or date) is priceless and it will work far more realiably than your "comment out" method. Old code belongs in the versioning database, *not* in the current code.

      Furthermore, it's not -1, Wrong just because you have a system that you think is better.

      --
      Why, o why must the sky fall when I've learned to fly?
    41. Re:Top Ten Code Comment Do's List by mwood · · Score: 1

      Yes indeedy. Keeping track of versions as the code changes is a mechanical process, so have the machine do it for you. Keep your brainpower for the creative stuff that we don't know how to automate.

      An awful lot of poor systems and poor results can be attributed to making machines do what humans do better and vice versa.

    42. Re:Top Ten Code Comment Do's List by jlechem · · Score: 0, Redundant

      Man mod this guy up. This is a trick I learned a long time ago when I first started writing serious code in college. Doing this forces you to think through the steps of the algorothm/process your using. For me it makes it easier when I write the actual code to have these predefined steps already in place.

      --
      Hold up, wait a minute, let me put some pimpin in it
    43. Re:Top Ten Code Comment Do's List by Richard+Steiner · · Score: 1

      This is an excellent suggestion, and it's a practice I've followed since college. I think it helps me to organize my approach to a given problem, and it often results in a nicely structured program (even in the old dialects of Fortran I'm used to coding in for a living).

      --
      Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
      The Theorem Theorem: If If, Then Then.
    44. Re:Top Ten Code Comment Do's List by mwood · · Score: 1

      One of the things I used to like about DEC's Language Sensitive Editor, when I had access to such tools, was that it encouraged this style of development. There were built-in commands to open a pseudocode block, to skip to the next block, and to turn a block into a proper comment for the chosen programming language and position you beneath it to fill in the code. LSE took a bit of learning beyond the usual text editor, but after that it was quite pleasant to work with. I miss it.

      There's probably a way to do this in Emacs (there's a way to do everything *else* ever invented, in Emacs) but I haven't found it yet.

    45. Re:Top Ten Code Comment Do's List by Richard+Steiner · · Score: 1

      Not all platforms have source control systems, and it isn't always convenient to use a system living on another platform.

      Sometimes apparently "stupid" things are done for very good reasons.

      --
      Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
      The Theorem Theorem: If If, Then Then.
    46. Re:Top Ten Code Comment Do's List by Richard+Steiner · · Score: 1

      Why is it that people seem to assume that all tools exist for all platforms?

      Older techniques are sometimes still in use in various shops because that is all that is easily available.

      I don't mind seeing criticisms or suggestions to use tools, but baseless insults are uncalled for.

      --
      Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
      The Theorem Theorem: If If, Then Then.
    47. Re:Top Ten Code Comment Do's List by MalaclypseTheYounger · · Score: 1

      I use CVS. How else do I keep track of millions of lines of code?

      My point is, if you work on such a system like I do, and you make many changes for many different reasons for many different people (the system I work on is used worldwide) you easily lose track of what changed, and why.

      So, for example, I make a change for a particular customer, and put it in the way you say (and the other 7 replies I got state). I then write major modifications/changes on TOP of those changes later on.

      Eventually, a bug pops up with the first change I made. I CANNOT simply ROLLBACK and LOSE all of the other work I did. And it's a huge PITA to re-do and re-import all of the other changes I have done if I rollback, especially if other DLL's are involved. The whole system will crash.

      In actuality, I should explain myself better. In each DLL (and components of DLLs, if they are large) there is a COMMENTS section. In the code itself, we comment out the line, put in the new line, and mark it with a #, Name, and Date (and sometimes a quick couple words explaining why). In the COMMENTS section (totally separated from the code, so the code remains somewhat readable) we go into the detail why we made the change, what customer requested it, and any other pertinent (sp?) details, such as other DLL's / Functions that are affected.

      My major reason for being a dick in my parent reply is the person writing is so concerned about a 800 or 600 line application (I forget what they wrote) and half of those lines being comments. My system has MILLIONS of lines of code, and every single comment that is in there usuallly helps IMMENSELY when trying to debug something.

      I don't understand the big deal of leaving commented-out code in a source base, there really is no better place to put it. Hard drive space is cheap, so what if my release versions increase a few kilobytes? It's not like the compiler or the end-users product gets any bigger, the comments are simply ignored and left out of our release.

      (Please, all the other people who FLAMED me on my parent post, read/reply to this one.)

      --
      Check out the best P2P sharing website: MEDIACHEST.COM
    48. Re:Top Ten Code Comment Do's List by xtracto · · Score: 1

      because CVS is GPL and available for a lot of platforms... and guess what?? you can use it with that old 486 system that you have in that corner...

      --
      Ubuntu is an African word meaning 'I can't configure Debian'
    49. Re:Top Ten Code Comment Do's List by Skapare · · Score: 1

      Assert calls tend to result in error messages that are uninformative to end users. They would be fine for things that can only happen as a result of programmer error. They should never be used for user errors. Instead, check all user input conditions as soon as they are input, or at least as soon as the information needed to verify them is available. Then given informative information about the error. Additionally, the program should continue to perform as much additional user input checks as possible before aborting, so that a user who has multiple errors can correct them all at once.

      --
      now we need to go OSS in diesel cars
    50. Re:Top Ten Code Comment Do's List by jtev · · Score: 1

      Just out of curiosity what platoform have you used that doesn't have a version control system?

      --
      That which is done from love exists beyond good and evil
    51. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      > What about side effect?

      In general, you should always try to write code that does not have side effects.

      All changes should be returned by the function either in the return value or output parameters.

      This means that most, but not all, functions do not reference anything except for their input parameters.

    52. Re:Top Ten Code Comment Do's List by FuzzyBad-Mofo · · Score: 1

      I can't believe that made it past the lameness filter, bravo!

    53. Re:Top Ten Code Comment Do's List by Richard+Steiner · · Score: 1

      There wasn't one in use (or available that I know of) on the Unisys A-series (MCP) system I did some contract work on two years ago, and the Unisys 2200 (OS2200) systems I've been using professionally for the past 15+ years have no such thing.

      That isn't to say there isn't some element of control over changes, though -- we apply correction images against the base source, for example, and usually don't just do whole-hog source replacement.

      --
      Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
      The Theorem Theorem: If If, Then Then.
    54. Re:Top Ten Code Comment Do's List by Anonymous+Brave+Guy · · Score: 1

      Blockquoth the AC:

      Version control won't work every time

      Yes, it will. That's exactly the point.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    55. Re:Top Ten Code Comment Do's List by Anonymous+Brave+Guy · · Score: 1

      I appreciate the point you're getting at, but I wonder whether you're being a little defensive rather than fully considering some alternatives to what you're used to?

      For example:

      Eventually, a bug pops up with the first change I made. I CANNOT simply ROLLBACK and LOSE all of the other work I did.

      Diffing between two historical versions of the code to extract (and potentially undo) only those changes is almost a one-liner with a decent version control system. If that's not sufficient, just having old, commented out code there won't help you either.

      I don't understand the big deal of leaving commented-out code in a source base, there really is no better place to put it.

      Of course there is: that's what the archive's for. Code in the archive doesn't confuse tools, doesn't increase the time to run your tools over a large code base several-fold, and can't accidentally be uncommented or misinterpreted later on.

      Speaking as someone who's also worked on developments of the scale you describe, managed with CVS in the largest case, I've never found leaving commented-out code lying around to be an advantage for anything.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    56. Re:Top Ten Code Comment Do's List by Anonymous+Brave+Guy · · Score: 1
      Whole point of using asserts is to fail fast during development, so that errors become painfully visible, with a clear message: FIX ME NOW!

      Which may still not be the most effective response to the error...

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    57. 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.

    58. Re:Top Ten Code Comment Do's List by jgrahn · · Score: 1
      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 hate both that method and the alternative you describe, and I've had to use both.

      Look at any random Unix manpage (Linux execve(2) for example, or strncpy(3)). I prefer to write and read complete sentences about the arguments -- because they only make sense in relation to each other, you cannot explain one without explaining the other.

      In my experience, documentation that explains arguments enumeration-style often ends up saying obvious things about the arguments, and forgetting to say important things about the function itself.

    59. Re:Top Ten Code Comment Do's List by zsombor · · Score: 1
      Which may still not be the most effective response to the error...

      Yeah! As if it were not difficult enough to avoid errors in the first place, we can now handle them with same ease? After an assert()==programmer_error all your preconceptions are invalidated, there is nothing left to rely in your quest for a more effective response.

    60. Re:Top Ten Code Comment Do's List by fbjon · · Score: 1

      I always read it as "poison", especially in RPGs where it's supposed to provide healing.

      --
      True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
    61. Re:Top Ten Code Comment Do's List by Anonymous+Brave+Guy · · Score: 1
      After an assert()==programmer_error all your preconceptions are invalidated, there is nothing left to rely in your quest for a more effective response.

      What a load of rubbish. I might have any number of emergency data saving procedures, diagnostic output routines, other threads running completely unaffected, and more going on elsewhere in my program. The fact that something has triggered an assertion failure means that something has gone wrong, but it doesn't mean that my whole system has suddenly become some unstable nuclear device about to annihilate the world!

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    62. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      I think I see a pattern there...

    63. Re:Top Ten Code Comment Do's List by k96822 · · Score: 1

      Yesss! You're hired.

    64. Re:Top Ten Code Comment Do's List by Trejkaz · · Score: 1

      But then 5000 would be missing!

      --
      Karma: It's all a bunch of tree-huggin' hippy crap!
    65. Re:Top Ten Code Comment Do's List by schmink182 · · Score: 1

      No he didn't.

    66. Re:Top Ten Code Comment Do's List by famebait · · Score: 1

      But do not forget to rewrite all the comments after you have written to code to tell what it actually do.

      I'd rather recommend adjusting them along the way, not afterwards. But yes, of course they ned to evolve with the code. Where sensible I try to change them just before making the change, so the altered comment works as a micro-spec for the task at hand.


      If you are from the "Just plan before what you will have to write"-team,


      Not at all. But I do believe in dividing work (including changes) into small tasks, and forcing myself to formulate for each one what it really is I intend to do. Often catch a few surprises at that stage too. But as an onging part of coding, not something done at the start.

      --
      sudo ergo sum
    67. Re:Top Ten Code Comment Do's List by TG1 · · Score: 0

      Where's that then? Redmond?

    68. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      Method calls can follow the same logic, you just make your best attempt so that each function

      a. Only uses parameters passed into it and nothing else. (OK - An OO object can refer to its member variables)

      b. It does not modify anything except for its parameters. (Again, as this should be followed as much as possible).

      This type of function satsifies one of the oldest software engineering tenets:

      - Avoid linking anything to anything else when possible.

    69. Re:Top Ten Code Comment Do's List by Anonymous Coward · · Score: 0

      return value: x where 0xMAX_INT

    70. Re:Top Ten Code Comment Do's List by Zareste · · Score: 1

      I really hate those end-of-line comments. I prefer comments I can erase easily after reading, and don't add unnecessary whitespaces. Getting rid of those takes too much clicking around for me.

      --
      I am NOT a number! I am a - oh wait, I'm number 761710. Look! 761710!
  157. Best comment ever by Camel+Pilot · · Score: 1

    Somewhere in a perl book I came across a comment that said:

    "It works just like you would expect it to, however it is hard for us to write how you think"

  158. Comments... by RickHunter · · Score: 1

    Should tell the reader what the code should do, not simply describe what it does do.

  159. In Soviet Russia... by doxology · · Score: 0, Troll

    Code comments on you!

    --
    sigfault. core dumped.
  160. The acid test for comments and documentation by davidwr · · Score: 1

    The ultimate acid test for documentation:
    1) Is the documented code clearer than undocumented code?
    2) Is it plain to the naked eye that the person could've made the code significanty clearer by having more, less, or different documentation?

    Self-contained routines may need little or no internal documenation. Even a multi-page algorithm to do a specific function, like compute sin(x) to 50 significant digits in the days before floating point processors were common, may only need a one-line comment before the code if the variable names are carefully chosen and the code is easy to follow:
    /* compute sin(x) to 50 significant digits using Taylor Series approximation */

    On the other hand, some 4-liners need 800 lines of description to comprehend, particularly anything from this web site.

    --
    Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
  161. Always comment logic by fizban · · Score: 1

    Descriptive variable and function names and well organized code can only do so much. Someone still has to understand how that organization scheme came to be and what the relationships are between all those variables and functions. That's where comments come in handy.

    They can tell the reader the bigger picture; the reasons behind certain decisions, what relates to what and how things should work. The code itself describes the specifics of how things are done. Comments describe a general overview of the how, and more importantly, why they are done that way.

    --

    +1 Insightful, -1 Troll. What can I say, I'm an Insightful Troll.

  162. Make comments worthwhile by Nefarious+Wheel · · Score: 1

    More to the point, people need to put some value into their comments. "i++" commented as "increment i" is worthless; commented as "set foo pointer for next bar compare" might have some value.

    --
    Do not mock my vision of impractical footwear
  163. Nobody's 100% right by pg110404 · · Score: 1

    While there may be an argument for either case, I think there is no one clear-cut-absolutely-definitive-all-encompassing case.

    I've come in on a project that had the following functions barf() and snarf() with oodles of documentation and not one single byte of source file was of any use to me because quite frankly it was so horribly designed that even with a hunting dog and ouija board, I still couldn't make sense of it. If I remember correctly it took me about 2 or 3 weeks to finally figure what that particular section of the code did. barf and snarf? Who the hell thought barf and snarf were acceptable function names?

    I've seen an entire project written with every single function documented with the following: PURPOSE, USAGE, INPUT, OUTPUT and a bunch of other stuff, and about half of it was simply wrong because while it started off well enough, as the project matured and the nature of the functions changed, that documentation was poorly maintained to reflect those changes. Over time there becomes a chasm separating the actual behaviour of the code and the intended behaviour that is documented or started off as being documented.

    On the other hand, I've seen projects that were very easy to follow because the team who maintained it wasn't afraid to type in 20 character long variable names that actually meant something - specifically meant what it represented.

    I'm currently developing a java based application for my boss and one such group of functions ensures the double variable used to maintain currency remains as proper currency, so I wrote a simple class to reformat the value of the double to a proper currency format. That class is called 'CurrencyFormat' and has format() and toString().

    Seeing as how I've based it on several other classes found in the standard java API, anyone who knows java should be able to figure out quickly enough what

    invoice.currentSubTotal = 0.0;
    for (int i = 0;i < invoice.lineItems.length;i ++)
    invoice.currentSubtotal = CurrencyFormat.format(invoice.currentSubtotal + (invoice.lineItems[i].quantity * invoice.lineItems[i].value));

    does. I've looked at code I wrote 5 even 10 years ago and while I get the sickening feeling of 'what the hell was I smoking when I wrote this damn stuff', I've never had a more than the very brief problem of trying to decipher what the code actually did because my boss at that time insisted I use meaningful names for functions and variables..

    In my experience, while code and documentation might start off alike, during the course of an ongoing project, documentation - especially maintained by someone other than the original author of the block of code - will either be incorrectly maintained or will not be maintained at all. Sometimes it might not be a bad thing, sometimes the change can be so major that anyone who then relies on that documentation will go on for some time thinking that's what it does when in fact that is NOT what it does.

    My experience tells me that poorly maintained CODE documentation can be more detremental than no documentation at all. However, its probably important to have a proper PROJECT design AND documentation overview. For example, no reasonable project should have all source files in a single directory and even then it should be more than arbitrary. A good layout and set of rules as to what goes where is as effective as a chapter of docuemtation. I have a 'db' directory for classes that deal with the database and a 'lib' directory for simple library like classes and a 'ui' directory which also contains ui/lib and ui/dialogs and ui/reports, etc. It should not be unreasonable if not redundant to maintain a project level document to say lib/QSort is a quicksort class or ui/dialogs/About is the about box. In the course of the projects lifetime a 'project bible' describing the breakdown of the project in those terms (Any modal dialog box that displays information and/or prompts the user for information or for a response goes in the ui/dialogs directory), etc, should e

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

    1. Re:A database backend would go a long ways... by rewinn · · Score: 1

      And then if you linked your code/comment pairs to business requirements and to test plans ... it would all be far too easy!

    2. Re:A database backend would go a long ways... by Anonymous Coward · · Score: 0

      A single word Xanadu the father of actual web.

    3. Re:A database backend would go a long ways... by GenSolo · · Score: 1

      That would only work until people start doing what they basically do now and confirming that the comments are correct without actually taking the time to verify that fact. (Subtly incorrect is often much worse than obviously incorrect.) Granted, the system would remind the programmer to check, but a rushed glance at the comment will likely result in "yeah, it's fine" when it's not.

    4. Re:A database backend would go a long ways... by asoko · · Score: 1
      In Common Lisp, the first form in the body of a function is the documentation string. (And since strings evaluate to themselves, it's ignored, unless it's the only form)
      (defun foo_up (x y)
      "This completely foos up x and y."
      (+ (* x y) (/y x) (sqrt (- 2 x))))
      Since code is represented as data (a tree) in lisp, it's easy to parse the doc string out of the function definition.

      You just need a versioning system that knows S-expressions.
  165. Re:You're right, but Raskin is wrong [correction] by Univac_1004 · · Score: 1
    last sentence should read:

    ...one can demonstrate in Archy his pushing of his concepts to the limit resulted in the end not fully matching his goals. Somewhat like "Literate Programming", in fact.

  166. www.lysator.liu.se/c/pikestyle.html by justine_avalanche · · Score: 1

    good code = little comments
    http://www.lysator.liu.se/c/pikestyle.ht ml is a great model of how to write comments

    I'd suggest reading code from old unix sources, or plan9, or any program written by good programmers and you'll see that you have something when comments are almost gone.

  167. Re:And this, my friends, is why offshore outsourci by ickpoo · · Score: 1

    Something even more scary about India is when executing long term projects that require large amounts of domain knowledge. Indian programmers are jumping from job to job just like we did here in he late nineties. Typical time stayed at one company is less than two years.

    Our offshore (India) support team has had 100% turnover in the last year. When it takes at least six months for a typical developer to have enough domain knowledge to be useful it means that we have a large number of very cheap very junior developers to tell what to do. And sadly, telling them what to do usually takes just about as long as doing it myself.

    --
    I am not a script! .Sig?
  168. Not only are you right... by Timbotronic · · Score: 1
    In my experience, the opinion people hold on the need for comments in code distinguishes them between coders (amateurs/beginners) and developers (pros).

    No one with any experience in maintaining a system of reasonable complexity could sanely argue that good comments aren't of benefit during maintenance.

    I've worked at dozens of businesses as a consultant over the past few years. Lack of comments is *always* a give away that I've just walked into a bucket shop. Then the sinking feeling starts. Comment free code is often accompanied by the usual suspects:

    • No spec
    • Few functions and/or functions that do too much
    • No testing schedule

    I've seen this so often it's like Groundhog Day! It's particularly inexcusable if the developers have some experience of maintaining their own code. Perhaps their egos get in the way of critically analysing how they could do a better job. In development, arrogance is the brother of mediocrity.

    --

    One of these days I'm moving to Theory - everything works there

  169. Hacking vs. coding professionally by dgmckay · · Score: 1

    It's fun to hack away at home on personal projects, but professional efforts - especially big ones - really do require decent documentation and comments in the code.
    Unfortunately my experience is that the requirements documents, design documents, and even the comments in the code are usually out of step with where the code actually is at a given time.
    I've seen a lot of code written by the local genius that only that same local genius can maintain. That's not doing anyone any good.
    How many times have you looked at a chunk of code and thought it'd be easier just to re-write it than spend the time understanding what's there in order to modify it?
    Long story short, my vote is for well documented, well commented code. And keep it simple too. Unless you're under contraints that require you to get creative, just write it in a way that others will understand.

    1. Re:Hacking vs. coding professionally by releppes · · Score: 1

      Your last statement "...just write it in a way that others will understand." Obsoletes the need for code comments in my book.

      Myself, I feel a well written piece of code needs little or no comments at all. I also can't stand long drawn out variable names. Variables to me should be a single word or two that describes it's value. Not a sentence. Many people hate the short or one character variable names, but for things like loop control or comparison routines they are more than sufficient.

      I firmly believe a well written piece of code needs little to no comments what-so-ever. I've read code like that, and it's truely the best way to learn what's going on.

  170. No such thing as... by tius · · Score: 1

    self documenting code. It has to be said, and hammered and said, and hammered.

    The fact is that code is an implementation of a design's ideas and as a translation of those ideas it can misinterpret or even be erroneous. The idea of commenting code is to state what the intention of the code is (and hopefully there is a design document to back that up as well). And incase anyone doesn't get the point of that it's called comprehension and verification.

    I won't bother as to why people tend to not do this and why it usually adds massive maintenance costs and simply blows chunks wrt. quality....grrrr.

    Think I'll go toss some ice on that nerve...

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

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

    1. Re:You new fangled whipper snappers by BigZaphod · · Score: 1

      If you can dodge a wrench, you can dodge a car!

      (I'm not really sure why your comment caused that line to pop into my head... but I enjoyed it, so thanks.)

  172. Re:Even more annoying... so true by StarsAreAlsoFire · · Score: 1


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


    Hear hear!

    Although, I think it should be 10K lines. Of poorly commented code. And it should be real, honest to god code; grab it from some department or other. Most (I would imagine *ALL*) engineering departments have a number of 'small' codes that do useful things.

    If aerospace FORTRAN codes from the mid 70s don't teach a code-monkey-to-be WHY the goto statement should at LEAST be well commented (if it must be used at all), *NOTHING* will.

  173. A truism by Anonymous Coward · · Score: 0

    If the comments don't match the code, they're probably both wrong.

  174. Funny comments by dgmckay · · Score: 1

    The other thing about comments is that they can be funny. I remember a couple of bugs we tracked down where a failed hardware access resulted in an infinite loop. Sure enough, when we dug in to the code, that while() loop had a comment before it along the lines of

    /* i should probably put a guard counter here */

    Heh. And then I think of the pain and expense those bugs caused.

  175. I'm not saying they don't know English by melted · · Score: 1

    I'm just saying that they (usually) operate under a different set of assumptions and priorities. If you're writing shit someone else (in the US) will have to support, then why bother with proper coding standards, refactoring and comments?

    So far the code I've seen come from India has been ATROCIOUS. This is not to say that US programmers can't write atrocious code, but those who do usually get kicked out pretty quickly.

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

  177. Re:And this, my friends, is why offshore outsourci by Malc · · Score: 1

    I've worked with plenty of N. Americans who've done this c&p crap. Indians don't seem any worse. Perhaps you've had a bad experience, or are just a bigot.

  178. Comments are better! by nrlightfoot · · Score: 1

    Having recently worked though a 40 Kb cgi script (agora cart) with about a quarter Mb of libraries trying to make a few changes, I can safely say I would have rather had a lot more comments rather than the descriptive variable names in the program. Of course, descriptive variable names should be used with the good comments for maximum understandability.

    --
    what sig?
  179. Everyone has an opinion by Kwirl · · Score: 1

    and they feel that theirs is the definitive solution to the question at hand; is commenting more useful than well organized coding arrangements? In my novice experience with computers and various languages, I have realized that the most important element of handling someone elses' code is the ability to decipher their structure and intent. Sometimes good commenting helps, but in the long run, commenting can also impede the visual flow of my 'reading' the code, and make it more difficult to properly grok. Ultimately, when I handle another person's code, I am more grateful for well structured and defined blocks of code than silly comments that usually just tell me what I can read for myself. Granted, more complex blocks of code make this a bit more work, but I just print out hard copies of that section of code, and use highlighters and reference pointers to think about what the original programmer was doing, and then I usually discover the solution, while simultaneously having a better understanding of how that person's mind works. After handling 7 or 8 pieces of code this way, I can understand the programmer's coding better, which is a lot better than stating the obvious, which is what *most* commenting really is. I'm no super guru, and I leave my experience and interpretation of my work up to the community, but in regards to the original post, this is my opinion and justification of such, which is all I am capable of providing.

  180. Code does shit by gmplague · · Score: 1

    Last time I checked, code does shit. Comments don't.

    ever try to gcc your comments and run the executable?

    --
    __________________________________________
    Take comfort in your ignorance.
    Grandmaster Plague
    1. Re:Code does shit by Anonymous Coward · · Score: 0

      stfu you cum sipping, cock spitter.

  181. 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.
    1. Re:Literate Programming (with caution) by kubalaa · · Score: 1

      Literate programming (meaning stuff like WEB) is a disgusting hack to make up for the inefficiencies of a few poorly-designed languages. Things like costly subroutines, no higher-order functions, no continuations, no local variables, no declarations mixed in to function bodies. But really, it's precisely equivalent to sprinkling your code liberally with gotos, and hopefully we know why that's bad. There were more structured ways to make the literal flow of the program match the logical 20 years ago, but Knuth was too much of a NIH masochist to realize it.

      If you need bracketing code, put it in a higher-order function and call that with a thunk. Or better yet, use a macro. (You are using a language with real macros and not that non-referentially-transparent cpp-style crap, right?)

      --

      "If you look 'round the table and can't tell who the sucker is, it's you." -- Quiz Show

    2. Re:Literate Programming (with caution) by os2fan · · Score: 1
      The secret about Knuth's Literate programming is not so much how he did it, but what he did. I have read much of the stuff on it, and found it to be fairly restrained.

      I particularly wanted it for writing REXX scripts, but adapted it to write any text.

      It has no "reserved characters". What it uses instead is the qTextq style (ie the reserved character is defined string by string). This means that one does not have the c:\\\\msdos\\\\dir style so beloved of microsoft.

      I do add some string handling to the result: you could, type it as: #zc.,\,c:\msdos\dir,\\\\#, which would change every instance of \ in the middle string into \\\\.

      It supports variables as well. One can set something like !set ydir #c:\msdos## and it will work. It supports wing-comments, on either side, so you can write !! comment !!code !! os2 apps !!set yos2app #d:\os2\apps## !! dos apps !!set ydosapp #d:\mdos\apps## !! win apps !!set ywinapp #d:\win\apps##

      The bit on the left tells you what the line means. It's like a little table.

      It supports something like ifdef, but you can reset the things on re-runs. Even this is done in an elegant way, since one might want to have embedded alternate values, without a bunching at the end.

      In practice, the language is home grown. It handles a lot of nice things, and is designed so that the bulk of the discussed matter is live code. One might have a table of conditions: this can be set to be read direct into the output.

      The same table, for example, might be called several times, each time evaluating something different. (ie you manage one table, and include/exclude things).

      The actual code is done in Rexx, with most of the variables visiable most of the time. The output is not language-specific. One same source could put out an INI file, a REX script, a QBasic script, a .CMD file, and a readme file.

      --
      OS/2 - because choice is a terrible thing to waste.
  182. Re: On code maintenance and commenting by Anonymous Coward · · Score: 1, Funny

    Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

    John F. Woods

  183. Re:Even more annoying... so true by Anonymous Coward · · Score: 0

    A professor teaching operating systems had everyone modify sys_fork(), the proc struct, sys_read(), and sys_write() in the linux kernel (using UML) to implement a filtering mechanism and to write a loadable kernel module to install and remove the new functions (the proc stuct had the filter field independent of the LKM). Nearly everyone in the class got the assignment correct, using packetstorm and google as documentation.

    Only problem? Grading it was a pain in the ass.

  184. PHP-Nuke by Cbs228 · · Score: 1

    Recently, I've been developing a massive website with PHP-Nuke, and I've been modifying all of its modules extensively. Although the functions and variable names are self-documenting, since PHP is not a strongly typed language it is often difficult to see what a function accepts as a parameter and returns just by looking at its definition. I would have vastly preferred it if the developers had commented it.

    --
    At our school, we don't earn a degree when we graduate—we earn pi/180 radians
  185. Longhorn program comments by Gary+Destruction · · Score: 1

    If BSOD
    then
    do.reboot
    'When are we going to offer users
    'the ability to change the color?
    else
    do.eat "\Device\RAM\ALL DIMMS"
    'Damn this is some bloated shit
    end If

  186. You need comments by aCapitalist · · Score: 1

    Don't let your ego screw other programmers over. Everybody thinks that they write clear, logically-flowing code whose meaning is self-evident.

    Sorry, but your thinking about code doesn't correlate with my thinking about code and as the submitter pointed out, his own thinking about code doesn't even correlate with what he was thinking 3 years ago.

    The fact of the matter is that most people can hold about 7 items in their head at one time and those 7 items add up fast when you're dealing with code.

    At the very least, write a summary for the class/structure and summaries for the methods. Even if methods are small (as they should be), most of the time people don't care about the internal; they just want to know what it does, pre-conditions, post-conditions, and any other caveats.

    Even if code was written in English, it still would necessitate summaries. Think of code-folding in your editor and how you only want to look at what you're interested in.

  187. 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
    1. Re:Necessary on low-level code and interfaces by Jerry+Coffin · · Score: 1
      mov ah,7 # 7=character printing function
      mov bl,7 # color code : 7=white

      This looks to me a lot like substituting comments for good coding. I'd rather see something like:

      print_char = 7
      white = 7

      mov ah, print_char
      mov bl, white
      ; ...
      --
      The universe is a figment of its own imagination.
  188. 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/
  189. 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

  190. Does not apply to *slashdot* comments..... by eh2o · · Score: 1

    Slashdot comments are more important than....... uh, I can't think of anything right now. Anyone?

  191. English is far more expressive by BAH+Humbug · · Score: 1
    English is far more expressive than any computer language. A computer requires a precise set of instructions and therefore any language interpreted to machine code must match that requirement. The most efficient way to express an algoritm to a computer is likely not the most efficient for a human.

    English lets you to articulate the nuances of the code that might be missed in the harsh structured environment of Java. Comments allow you to draw outside the lines!

    I see several responses questioning the reliability of comments. Code can have bugs, why not comments? If the code has a bug I fix it. If a comment isn't "right", I fix it too. Just as you should look at all code with a bit of suspicion, do the same for comments.

    Sure, programmers can and do write bad comments -- and they're probably the ones that write bad code. We all grow. I no longer write one comment on each line of assembly code but instead use a paragraph or two to describe a section of C++ code.

    Writing self-documenting code is nice, but have you ever tried to interpret uncommented, templated C++ code? It isn't pretty. Thank goodness we have debuggers that will step through the layers and layers of indirection to finally get you to an invocation of some real code!

    Code is useful for describing what you are doing. Comments are for explaing why (e.g. "I'm calling the xxxx routine because there is a bug in the .NET framework v1.2 which will hopefully be fixed in the next version but this call should work in either case.")

  192. The psychology of computer programming by aCapitalist · · Score: 1

    Weinberg wrote a book with that exact title.

    The problem is that each progammer approaches coding in his unique way. There are an infinite number of solutions to all but the most trivial programs.

    I'm constantly saying to myself "Why did he write it this way?".

    Comments raise the abstraction level just like patterns and higher-level languages in general.

    So until we all become Borg, we're going to need comments

  193. Comment the contract... by dbc · · Score: 1

    What inputs are acceptable. What inputs should be rejected. What inputs lead to undefined results. What guarantees do you make about the outputs.

    A function makes a contract with the outside world. Make the contract clear. Then add assertions. Good assertions are often better than good comments anyway.

  194. Comments are for sissies by js3 · · Score: 1

    Imho comments are for people who can't read code or just write sphagetti code in the first place. I always say my code is my comment, because it is good and clear enough to understand, without littering it with silly comments.

    Btw my experience with comments are half of the time they don't match the code! They comment and then update the code, again and again and again and the code doesn't even match what they said it did.

    If you really want others to understand your code write a design document to give them an idea of what your code is supposed to do. They can figure out the rest from the code.

    --
    did you forget to take your meds?
  195. Doxygen and commented code by AhaIndia · · Score: 1

    I just wrote a piece of code and commented it properly. I used Doxygen style comments.
    The beautiful output documentation produced by Doxygen automatically was worth the little extra time spent on commenting my code.


    --
    ~Aha~
  196. 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?

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

  198. There are two types of programmers by Anonymous Coward · · Score: 0

    Type I

    Developers that spend all day complaining that all they code they have to work on doesn't have enough comments and how everyone needs to stop coding and write detailed design documents.

    Type II

    Developers that actually implement all of the functionality while ignoring the complaints of Type I developers.

  199. 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."
    2. Re:After coding for 22 years... by Spurion · · Score: 1
      I tend to agree. But still, "self-documenting code" can tell you at best what it does. It cannot tell you:
      • why the code does what it does;
      • why the code doesn't do something else;
      or a number of other things. For example, I sometimes encounter code that looks wrong but is in fact correct, even though I'm familiar with the problem domain. In such a case, an explanatory comment can guide my thoughts and save me having to spend time (perhaps incorrectly) figuring out whether it's a bug or not. In short: comments are very useful for getting another reader into your mindset, which will make maintenance much more straightforward.
      --
      Any sufficiently self-referential snowcloned .sig is indistinguishable from nonsense.
    3. Re:After coding for 22 years... by djmurdoch · · Score: 1

      I think it's safe to say comments are for the benefit of those who have not assimilated their language, their APIs, etc.

      When you write something, are you sure that only someone who knows as much as you about the problem is going to look at it?

      I've been programming for longer than you have, and I know that [me next year] is going to benefit from comments that [me now] puts in my code, because [me now] knows the context of the problem, and [me next year] will have forgotten a lot of it. [Me now] may have learned some horrible API in order to write the code, and [me next year] won't have used it for a year.

      And if someone else is looking at my code next year, they'll likely know even less than [me next year].

  200. da vinci never comment.... by Anonymous Coward · · Score: 0

    ... his pictures. managers need commented code because they can't read them.

  201. After 22 years of coding... by coolgeek · · Score: 1, Redundant

    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 as well as how certain events can interact.

    Conversely though, 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 22 years of coding... by djmurdoch · · Score: 1

      This is a cool way to increase your karma: post the same thing twice, and the moderators will mod both copies up!

    2. Re:After 22 years of coding... by coolgeek · · Score: 1

      I've been at 50 for over 2 years, perhaps even 3; I do not need to Karma whore.

      I got a "form expired" error from slashcode, although it seems to have accepted the post anyway. I hit reply again to repost, hence the double post.

      --

      cat /dev/null >sig
  202. Commenting is costly by Anonymous Coward · · Score: 0

    only comment those functions which are difficult to understand.

    And generally, if you use proper names for variables and functions, you won't need commenting for simple functions.

  203. x86 Assembly can be worse by grahamsz · · Score: 1
    I was thrown a 60kloc win 3.1 device driver written in assembler which had such glowing comments as.
    djnz ax, end: 'Decrement register ax and jump if not zero
    Never did get far with that project.

    Also forgive me if my syntax is rusty, it's been a long time (thankfully) since i touched that stuff.
  204. 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?
  205. 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.

    1. Re:Purpose of comments by Anonymous Coward · · Score: 0

      We need to create programs as a project. Remember all the necessary steps: Work Planning, function planning, etc. This is not only more work to do for you, because in fact it helps you and saves time and work. Now I do not mean only the if-case if-I-ever-will-update-my-code, NO! I mean it helps you right now. Better plan, easier coding - easier add reasonable comments. IMO

    2. Re:Purpose of comments by Anonymous Coward · · Score: 0

      I would argue that if your code needs comments to say what is being done then you aren't finished refactoring. :)

      As for comments about why something is done a certain way, I would go even further and suggest that comments should be reserved for cases where something is being done in a way that might not at first glance look like the obvious implementational choice but for which there is an important yet not immediately obvious reason for that implementation to have been chosen. In other words, only comment on why when the what looks wrong but is necessary.

      Good refactoring can remove the need for pretty much any comment except the specific type of "why" comment I describe above.

  206. My opinion. Others exist, but this one is mine. by rice_burners_suck · · Score: 1

    Comments may be important, but not quite as important as well-written, organized, and coherent code, with well-chosen names for functions, variables, and types. When a program is written in such a way that it's obvious what it does, so you can read it and understand it, the comments might just have to describe why things are done a certain way. In most code, 90% of the stuff is obvious, boilerplate, exists-in-every-program kind of stuff anyway... It's that 10% of code where the real logic of a program happens where you need to make sure that you comment everything so well that there's no screwing up.

  207. Useful comments. by Jerry+Coffin · · Score: 1

    I think this comes close, but just misses pointing out a few things that are salient here: 1) comments need to be tailored to the audience and the intent of the code. If you're posting code to alt.comp.lang.learn.c-c++ (for one example) it's perfectly resonable to write a lot of comments that would be downright insulting under normal circumstances. 2) Short of getting ridiculous, self-documenting code only documents what it does, not WHY it does that. Comments should usually tell why. 3) IMO, the comment elsethread about commenting interfaces started out well, but then went astray. Commenting an interface is a good thing -- but you should NOT have to tell what the interface does, because if comments contribute to that, the interface has serious problems that need to be fixed. Variable names are the least of writing self-documenting code; good function names and (where applicable) class names are far more important -- the interface itself should make its intent obvious. Comments on an interface _should_ be used to tell about those things that can't (reasonably) be made apparent otherwise, such as preconditions and limitations on the interface.

    --
    The universe is a figment of its own imagination.
  208. Wow by Anonymous Coward · · Score: 0

    I'm very surprised noone noticed, but the man who wrote the article passed away several days before the article was published:

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

  209. I think most interesting is that.... by xquark · · Score: 1

    a dead guy is writing articles about code
    development from the grave...

    come on at least give us a clue about the next
    life, is it hot or mild tempered ? ;)

    Arash

    --
    Arash Partow's Philosophy: Be a person who knows what they don't know, and not a person who doesn't know.
  210. Re: collapse/expand? by SolitaryMan · · Score: 1

    How about collapsing/expanding comment feature that most modern editors have? If you collapse all your comments, you can see code fine, but the comments are still here for those who need them.

    --
    May Peace Prevail On Earth
  211. Good code by planetoid · · Score: 1, Insightful

    Good code is code that's modularized into so many properly-named, small functions, that it looks like the pseudocode originally used to describe the algorithm in the first place.

    Still, if you're implementing some arcane algorithm that isn't documented very well in academia, let alone taught in most universities, and is full of obscure mathematica that even mathematics doctorates will have to squint at, then be a dear and just comment the fucking code to help make it easier for your colleagues to comprehend. If you can implement something so fancy and grandiose that it can have its own patent, certainly you can spend 5 minutes to clarify the principles behind it in documentation as well as sources. It isn't hard.

    --
    Slashdot requires you to wait longer between hitting 'reply' and submitting a comment.
  212. 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 ---
  213. Re:Comments? Pshaw! by Kwil · · Score: 1

    If all I wanted was to grok the way it's executed, I'd just run the program.

    If I want to understand why it's executing the way it does, give me comments. Maybe your time is cheap enough that you don't mind looking through 28 dependancy files to finally figure out what pointer is screwing with the function you're trying to debug. Mine isn't.

    --

    That Jesus Christ guy is getting some terrible lag... it took him 3 days to respawn! -NJ CoolBreeze

  214. Role of Syntax Hilighting by EEBaum · · Score: 1

    I've heard people say (and have experienced myself) that too many in-code comments tend to clutter a function and make it difficult to read.

    As a solution to the problem that exists because I just said it does, I think people far underuse syntax hilighting. I use a darkish blue-green background with white code and black comments. The comments are easily legible, but it is very easy to tune them out to see which lines of code actually "do stuff." With the default black code and green or red comments on a white background in many editors, this benefit is often missed.

    --
    -- I prefer the term "karma escort."
  215. KDevelop for C++ by WindBourne · · Score: 1

    In addition, there is a VB for KDE, but there is something very strange about professor unix wanting VB.

    --
    I prefer the "u" in honour as it seems to be missing these days.
    1. Re:KDevelop for C++ by Professor_UNIX · · Score: 1
      In addition, there is a VB for KDE, but there is something very strange about professor unix wanting VB.

      I was learning VB for my own survival. There are thousands of VB programmer jobs out there... It's something to fall back on should I need to. I'll probably have to get an MCSE soon as well if I want to stay in my hometown. My own personal love is security and networking, but every single job in the area wants their networking guy to double as their Windows2000 Server admin and wants an MCSE. It sucks, but we need to put food on the table somehow and moving is not an option (all our family is here and the wife doesn't want to move).

      I was thinking of learning Cocoa programming for MacOS X, but there don't seem to be any jobs at all for that. Too bad. :-(

    2. Re:KDevelop for C++ by WindBourne · · Score: 1

      Sorry to hear that. Hope things get better. Where do you live?

      --
      I prefer the "u" in honour as it seems to be missing these days.
  216. Use Vim or Emacs, not tab key! by Anonymous Coward · · Score: 0

    Use a proper editor, like Emacs or Vim. Setup the autoindentation mode, and use it. In Vim select the whole file, ggVG, and just shoot the autoindent, =. That's it.

  217. Comments are more important than code... by halleluja · · Score: 1
    Obviously, code is about work and comments are about expressing yourself.

    int c = getchar(); // why the FUCK an int??

    /* don't you frigging dare touch it */
    int x=3,n,m=2,*t,*a,*b=0;
    while(b?o:((*(t=b=(int*)mal loc(o))=2),a=t+1,o))n=*b,n>=m?c:x%n?(int)b++:N);
  218. Write in plain, uncluttered English by EEBaum · · Score: 1

    After a while on any project, the buzzwords tend to blur together. This is especially true when I begin to work on someone else's part of a project that I'm previously unfamiliar with. Some of the best comments, in my opinion, are those that are written by people who are good writers, not just good coders.

    Write comments so that a relative idiot (someone who knows how to code, but doesn't know beans about, say, four different graphics APIs) would understand. Heck, after six months away from my own code, I sometimes feel like an idiot wondering why I put something in a certain place.

    As coders, we tend to love long words and big fancy phrases that explain what something does. If, however, we can bite the bullet and divorce ourselves from "Assigns primary responsibility for the node list's functor to the parent's third data field before disconnecting it from the graphics pipeline" in favor of "Stops drawing," we can take a big step towards legibility.

    Heck, comments could even *gasp* tell WHY instead of WHAT. Looking at the code it's commenting will tell us WHAT. WHY is often much more cryptic, and a few choice words can clarify it for all readers involved.

    --
    -- I prefer the term "karma escort."
  219. Re:And this, my friends, is why offshore outsourci by WindBourne · · Score: 1
    India has more engineers than the USA. And these are smart people.

    Obviously, you have never been to India. India has smart people the same as the USA. But you are attempting to judge India by people that you see in America/UK/Whereever. Well that does not work. Plain and simple, the vast majority of Indian engineers in India are similar to what you will find in BFE America. That is they will have a 2 year degree in CS (actually CIS), or they will have the equivelence of a MS certificate (which is also the same). Then they will get a job with whatever comany they can. Once they have the job, it is their for the rest of their life (or until the jobs start moving to CIS or China).

    When you speak about the Indians that are in America, I have been impressed. But they are not your average Indian. In fact, think about the average American who travels over the world. They can assimulate into a culture, are flexible, and typically are soemwhat intelligent; the same as the average Indian here.

    Outsourcing is not the problem. The problem is that we got compfortable, and do not work hard enough. When I went to school for CS, I was #1 in all my classes. But right behind me were the Indians and Chinese; Rarely would I find other Americans competing.

    --
    I prefer the "u" in honour as it seems to be missing these days.
  220. Poor comments implies poor programmer? by QuestionsNotAnswers · · Score: 1

    I believe that only poor programmers comment their code poorly (useless comments, out-of-date comments, etc).

    Because of this belief I make an effort to write comments which will assist understanding of any code. (Not saying I am a great programmer, but I care enough to try to be).

    --
    Happy moony
  221. of course just ask Microsoft by Anonymous Coward · · Score: 0

    they have lots of comments in their code...many of which can't be said on tv

  222. Use the code by Anonymous Coward · · Score: 0

    After 40 years of looking at code I have no doubt that code comments are a waste of time and effort. I have spent countless hours reading useless and wrong comments. For me a good software implementation has a data dictionary, informative module/function/class/method headers, and clean self documenting code that has been code reviewed. I can step through most code in my head to figure out what is going on. And, for the code I can't get my head around, there is aways the debugger.

  223. Improving... by Vo0k · · Score: 1

    Learning, improving yourself, changing coding style, using new techniques, this all has such a strong impact, that I wouldn't touch my own code from 2005 with a 2-yard pole tied on the end of another 2-yard pole. I'd rewrite it from scratch, making it twice as fast, thrice as reliable and four times more readable. And taking 1/10 the time fixing the old code would take.

    Reading your own old code leads only to frustration. ("My god, I'm such a moron to have written this!"). A ton of GOTO in a C program? Excuse me, I'd better take the data files and don't make me look at that. Triple-nested switch()? Hurts! My brain hurts! Condition look-up table organised as some 100x100 array of if() RUN! RUN! IT'S GONNA BLOW!!!!

    --
    Anagram("United States of America") == "Dine out, taste a Mac, fries"
  224. Hpw to write unmaintainable code... by emilv · · Score: 1

    There's a fantastic essay describing how to write unmaintainable code. Here's the chapter about comments/documentation: http://mindprod.com/unmaindocumentation.html

  225. (Lambda (Comment) ()) by TaleriaKNT · · Score: 1

    For the most part, I find comments useless. They get in the way of quick typing (I hate hitting end and finding the curson beyond a comment, instead of still in the code where I can do something useful,) and they are only necessary if you can't understand the code.

    Of course the obvious thought alot of people have is, "What do you do in six months when you come back to make a change?" To this I say that you should eitherremember still (this may be difficult if you spent most of your time commenting rather than coding,) or you should figure it out pretty quickly as you glance through the code (if you can't, then how did you manage to write it in the first place?)

    Don't get me wrong. I think that comments CAN be useful. I just think that people tend to rely on them too much. I use comments as placeholders for sections of code I'll write later, and for tricky stuff sometimes, such as extensive bit manipulations, but I don't think there's much reason to use them elsewhere. Proper name choices will tell you enough to get going quickly, and if you're trying to alter things on a more detailed level, you'd better understand the code anyway.

    There's also an additional problem with comments in certain languages. In Scheme, for instance, when you can easily end up with very small, but powerful functions that have mutual recursion with multiple other functions, comments wouldn't really make sense. You would need to understand the functions already just to follow the order of execution in order to tell which comments you should even be looking at.

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

  227. If you need comments, you REALLY need unit tests by bADlOGIN · · Score: 1

    I'll take unit tests over comments any day. Unit tests are an executable explanation of what the code should do. Comments get out of date and ignored. A well written unit test says exactly what sort of service the method is providing and what the implications of that method call are assumed to be. The important thing to notice here is that it doesn't tell HOW the code is doing it. This, of course is GREAT! If the code is hard to read, get unit test coverage, understand it, "comment" it with tests, and refactor the hell out of it.

    --
    *** Sigs are a stupid waste of bandwidth.
  228. I prefer not commented code.... by KiroDude · · Score: 1

    I know it sounds stupid, but having to go through the code helps me to understand it much better than just reading comments. You see, the problem is that as much as a developer might comment his/her code, he/she will give as obvious some things that might be not so obvious, thus, you end up supposing you understand the code when you really do not. On the other hand, having to look at it deeply in order to understand it, gives you a better understanding. I like to use the GPS analogy with this: When you use the GPS you can move around a city quick, but once you disable the GPS, you have the impression that you've never been to the city. Never use the GPS, and in one week you'll know the city by heart.

    1. Re:I prefer not commented code.... by ArnIIe · · Score: 1

      I agree - although I would say some form of commenting is useful. "You see, the problem is that as much as a developer might comment his/her code, he/she will give as obvious some things that might be not so obvious, thus, you end up supposing you understand the code when you really do not." Is very true.. they may understand what the code is supposed to do/does but not how the code works - having said that (about to contradict myself) you could argue that thats just down to a bad programmer. I really think its a case of balance - its good to have comments for reference (and a documentor is very useful) but having a good code maintainer (programmer) is probably more important

  229. But even more important... by lyk · · Score: 1

    *Why* the function does what it does. Cite a paper, report, equation number or page.

  230. Marsellus Wallace by Anonymous Coward · · Score: 0

    Oooh, someone hasn't watched Pulp Fiction.

    1. Re:Marsellus Wallace by Frizzle+Fry · · Score: 1
      Oooh, someone hasn't watched Pulp Fiction.

      What?
      --
      I'd rather be lucky than good.
    2. Re:Marsellus Wallace by Maax · · Score: 1

      Set tabs to indent 2 spaces one more time! I dare you, I double dare you, motherfucker! Change those tabs one more goddamn time!

    3. Re:Marsellus Wallace by Anonymous Coward · · Score: 0

      What?

      Say what again. SAY WHAT AGAIN. I dare you, I double dare you, motherfucker. Say what one more goddamn time.

  231. You are by Angst+Badger · · Score: 1

    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.

    Your colleagues are almost completely wrong. "Short, descriptive variable names" will do when the algorithm is trivial and its function obvious.

    This afternoon, however, I wrote a chunk of code that takes a long series of colored line segments (identified by clr, x1, y1, x2, y2) and figures out how many closed polygons they describe. My variable names are all short and descriptive, but without at least a little introductory comment, most programmers probably wouldn't know what was going on without a whole lot of head-scratching. It's not that the code is that terribly complex, but all software ever does is move numbers around, and unless you know what the numbers are supposed to represent, it's just gibberish.

    --
    Proud member of the Weirdo-American community.
  232. 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.

  233. Quote by Anonymous Coward · · Score: 0

    "Always code as if the person who ends up maintaining your code
    will be a violent psychopath who knows where you live.

    John F. Woods (quoted on Usenet) 1997/08/20"

    Put "document" between "Always" and "code" and the psychopath probably will be less violent...

  234. Source code has no value by mcrbids · · Score: 1

    Recent events have caused me to conclude that source code has no value to a software company.

    The value is in the understanding on the part of the engineers who develop the software, who then develop the software to their understanding, which software gets sold.

    Without this understanding, the engineers and coders produce crap and the company goes belly-up. Given the understanding, they produce wonders that are well received and highly appreciated by customers who happily pay on time.

    So, the thing of most apparent value, and that which is sold, (the software) in truth is the LEAST significant assett for the software company.

    It's the understanding of the industry for which the software is to be written. It's knowing all the approaches that didn't work. It's knowing the terminology of the target industry. It's knowing what's already been tried, and why it did (or did not) work.

    The source code is merely a condensed, lossy format for preserving this knowledge.

    It's difficult to grasp - and yet critical for the long-term survival of a software company!

    --
    I have no problem with your religion until you decide it's reason to deprive others of the truth.
  235. You know it when you see it ... by Keeper · · Score: 1

    Properly commented/documented code is one of those things that is hard to describe, but you know it when you see it (or don't see it).

    If I'm working on a routine complicated enough that it forces me to think about the problem in pseudo code before actually writing the code, the pseudo code ends up being left behind as comments in the code. This allows me to focus on mini-parts of the problem without losing focus, and also tends to appropriately describe what is going on at a high level (assuming of course your code does what you think it does ;)).

    If I'm trying to figure out what a piece of code does, and it takes awhile to dawn on me, I add a comment.

    If I fix a wierd bug that doesn't look like a bug, in goes a comment to describe the buggy behavior so that someone else doesn't come in and make the same mistake a 2nd time. Sometimes I'll just comment out a line and add text above it which says "don't do this because of blah".

    If I do something non-obvious/clever/evil, in goes a comment.

    If time allows, I create "headers" for functions that describe what the function does, what the parameters are for, what all of the expected return values in various cases are, and what exceptions the code may throw (if any). I tend to do this more for core pieces of code than code that is rarely touched or considered throw-away.

  236. 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.
    1. Re:Actually, you illustrate a bigger problem by dooglio · · Score: 1
      Your idea has merit.

      But I think if you really want to teach the students about real world programming, they should be required to add functionality to a huge piece of nightmarish spaghetti code (you know, the kind with switch statements spanning many pages and dozens of variables at the top of the function, and hundreds of poorly documented global variables).

      The new functionality requirments should be sizable, and the deadline ridiculous.

  237. But surely... by N+Monkey · · Score: 1

    Hmmm, most modern programmers would just pick "Tools->Beautify Code" in their modern editor and not care how the other person formatted their code.

    But surely, "beauty is in the eye of the beholder" and not someone else's formating algorithm?

    1. Re:But surely... by greggman · · Score: 1

      Most modern editors have quite a few options for formatting so it should easily meet most people's preferences for style. And, the point is, it's not your code your reading, it's someone else's so all you need to do is make it more readable. One of the formats a modern beautifier supports should be close enough to make the code readable to the person trying to read it.

    2. Re:But surely... by petermgreen · · Score: 1

      i guess thats fine if your just reading

      but then you need to make a patch to send back to the original coder. I think diff and patch have an ignore whitespace option but i still think the result of such a patch process (makeing a patch against reprocessed code to use against the original) would leave quite a mess when the patch was applied.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    3. Re:But surely... by greggman · · Score: 1

      sounds like you are using outdated patching software

    4. Re:But surely... by fbjon · · Score: 1

      Yes.

      --
      True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
  238. 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
    1. Re:variable names are sooooooo easy by t_allardyce · · Score: 1

      There's no excuse even to shorten to 'ctr' with search and replace you can write and test a function with bad variable names and as soon as you've finished or the day is over search and replace some better names... Although a good code editor should auto-complete things and tell you what your variable is a member of and its type.

      --
      This comment does not represent the views or opinions of the user.
  239. 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.

  240. Blind Markers by Ulky · · Score: 1
    I had the misfortune of doing a MSc at what I now realise is probably one of the more badly run universities in britain.


    Aside from taking people with >5 years industrial programmamming experience, and then forcing them to do a basic Java course using BlueJ, the standard of the markers is questionable.


    Imagine my surprise when I recieved my final assignment back with the comment "No Comments!" (which there were). Perhaps the ultimate irony was that "No Comments!" was actually written over a comment.... muppets....

  241. Where to comment, not whether by tinkerton · · Score: 1

    The discussion seems to focus on in-source comments, and polarises on whether to comment there or not.
    Your post at least gets away from that, but there are more places where to comment. It depends on the type of comment.

    Places where to comment:
    - there's the headers
    - when checking in a revision in the repository , document per file. So that if you do a diff between revisions, you get the background behind the change. That background belongs to that moment in time. This mechanism is probably underused.
    - and document the whole checkin. Lavishly.
    - and add to that a place for the general thinking and design around the subject.

    There should be lots of effort for documentation, but each time the question is, where does it go.
    I still think that if you show me comments in the source , I'll show you an opportunity to improve the source.

    Obviously, if the ideas behind extreme programming lead to a situation where bad code is badly documented, then instead of one problem, you got two.

  242. Re:There are 10 types of programmers by Anonymous Coward · · Score: 1, Funny

    Those who understand binary, and those who dont.

    Sorry! :(

  243. Why not How by codexus · · Score: 1

    Good comments are not there to document what is obvious from reading the code they must add another information that one will not easily get otherwise.

    For example, instead of a comment that explains *how* something works write comments when it's necessary to explain *why* you implemented things that way.

    --
    True warriors use the Klingon Google
  244. Actually by Moraelin · · Score: 1

    Assembly is what taught me to use lots of comments. Every single line did have a comment, flowing like a column of text alongside the code, documenting what, why and how I've done.

    I also very quickly learned to not use the "Decrement register ax and jump if not zero" kind of comments, but rather stuff like "if we got this far, the data must be valid, so store it and move to the next record".

    Assembly is very cryptic stuff, as you already know. A 100 line C function can become a 1000 line ASM module. Worse yet, some 10 lines of C which are easily read, easily held in your head, and easily visible at the same time on the screen, can easily become 50 to 100 lines of assembly, which aren't either. You document it well, or you can't read it later.

    So personally I'd say teach the students assembly early, and make them maintain that code the next semester. That should drive the point home about comments and software engineering.

    --
    A polar bear is a cartesian bear after a coordinate transform.
  245. you only need by progr · · Score: 1

    I think that the only comment that you really need are: //FIXME reason //HACK what is the hack and why is present here //TODO what there is to-do at the end of the day I parse all my code and point out what to do and what to fix. Other comment are pretty useless.

  246. Tests cannot cover all cases by rp · · Score: 1

    Tests cannot be generic. It is impossible to test all possible code paths, there are infinitely many.Your tests are only going to cover a couple of use cases. So tests do not fully document functionality.

    1. Re:Tests cannot cover all cases by rewt66 · · Score: 1

      But if there are infinitely many possible code paths, it's going to be pretty hard to fully document functionality with comments, too...

  247. Using emacs: by kiwibird · · Score: 1

    M-<
    C-Space
    M->
    C-M-\

    Tabs normalized.

    1. Re:Using emacs: by Anonymous Coward · · Score: 0

      C-x h
      C-M-\

  248. Depends on your definition of "uneccessary" by BigTom · · Score: 1

    The article author says "I discard the radical position taken by proponents of extreme programming (XP) to get rid of 'unnecessary' documentation."

    Why? Surely no one wants to write 'unnecessary' documentation and comments? That would be a waste of time wouldn't it?

    As everyone agrees that you should put in 'necessary' documentation/comments then what's the problem? Rather than setting up a false dicotomy between commenting and not-commenting wouldn't it be better to try and work out what the necessary documentation is?

  249. Document how things interact by oglueck · · Score: 1

    Comments are good, no question. But they must be made on the right level of detail. Commenting every single line is complete overkill and helps only those who are completely unfamiliar with the language. So this may be useful for educational purposes, but not for real world code.

    When I inherit an existing code base, first thing I do is try to get the overall structure. In Java this is pretty obvious when the packages are well organized and have good names. Next I look into individual packages. There should be a package.html that quickly describes what this package does, what it should not do, and so on. This is still no comments in the classical sense.

    Next I look at class names. My IDE also distinguishes interfaces from classes, so they are easily spotted. No need to use naming conventions for interfaces and the like, though. Good class names already tell you a lot how things probably work and it's easy to figure out.

    The details of the classes responsibilities are in the class documentation at the top. This one I consider an essential comment. Knowing how to use this class, if it's thread-safe, immutable, it's contract etc. is the most important thing.

    Next the contract of the individual methods is important. So at least all the public and protected methods must have a good comment describing the contract in detail. Note: I am not interested in HOW a method performs a job, but only what goes in and in what state does it leave the object.

    Finally to comments on individual code blocks and private methods: use comments only when an algorithm is not obvious, when an arithmetic expressions needs explanation, when the reason for a thing you do is not obvious. Also document constructs that are very delicate when changed and likely to break something.

    Often I see code like this: //read input
    [some lines of code] //process bla bla
    [some more lines of code] //find data
    [some more lines of code]

    Instead of placing comments in front of each code block the code should have been broken up into smaller methods that have a speaking name.

  250. Genius programmer by StrawberryFrog · · Score: 1
    He was a genius programmer - but wrote code that almost no one else could ever maintain.


    Any fool can write code that a computer can understand. Good programmers write code that humans can understand. -Martin Fowler, "Refactoring: Improving the Design of Existing Code "

    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan


    Why do you say "genius programmer", and not "genius, and inscrutible programmer"?
    Did nobody tell Mr "Genius" that his code was unreadable, that this was stupid, and that he could do better if he was actually as smart as he thought, and was any good at programming?
    --

    My Karma: ran over your Dogma
    StrawberryFrog

  251. No, no, no, no, no.... by measterbrook · · Score: 1
    There are two audiences to code. 1) Developers. 2) Compilers. It may come as a surprise to some, but the compiler cannot read the comments. If you write it in the code, both the developers and the compilers are working to the same source. Anything in comments is invisible to the compiler - it will be ignored, always. A really really simplified case:
    /* Initialise all variables */
    int i, j, k = 0;
    Here it is easy to see that the comment is wrong. In more complex cases it often isn't. Until compilers are able to read comments - DON'T USE THEM. I repeat - say it in the code - if you feel you have to add a comment then you are writing difficult-to-understand-code - rewrite it so it is understandable. Of course it is important to document the code, and the best place for documentation in next to the code (which is very different to comments). The documentation should indicate the why (not the how - code does the how):
    /* Use single character variables because this is
    just an example and they don't have any meaning */
    int i = 0;
    int j = 0;
    int k = 0;
    OK, I've got my asbestos suit on - flame away....
  252. What I got taught by AcIdR3IgN · · Score: 0

    In highschool, we got taught to add lots of comments, even when my rebelious uprisings didn't change this. I refused to comment silly lines like a = 25; And on my first exam I did get degraded because of this. So then I just started adding larger blocks of comments to blocks of code. When on work experience, I got told by someone in the company that it's best not to comment your code, because once the project is finished, and they let you go.. then need to upgrade their code, I (as the programmer) would be pretty much the only one that could read my code. Meaning I'd always (mostly) have a job, because other programmers would waste their time trying to decode what I wrote. On one side, this is a nice idea... on the otherside, it's pretty rediculous, seeing as that after a few months I probably won't even remember what I coded in the first place. So now I just tend to add comments on a regular basis, but not on every line. In college they don't even teach us to use comments... which is odd.. although in this so called CS course we're only using VB.NET... quite sickening.

  253. This is the worst kind of SE article there is by lskutt · · Score: 1

    Wow, it still amazes me how far behind Software Engineering is when compared to the rest of the modern world. I can't think of any other engineering nor scientific disciplin which could get away with stuff like this. You might think that I am a bit harsh, and you are probably right, but let me explain why through an example.

    The programmer/homebrew way to solve (or rather, explain away) the Lack of Comment (LoC) problem: "I have worked as an X for Y years and I have found that this and only this works. People shouldn't be so lazy, people are stupid, management is stupid, customers are usually right, the programming languages needs more technical features bla bla bla /../ some more anecdotal 'evidence'."

    No, this simply isn't good enough. We have to do better than that. Let's instead try what engineers do best: engineering.

    The engineering/positivism way to try to solve LoC: "We first have to realize that there are two different approaches to this problem; the comment writer perpective and the comment reader perspective. We then subdivide each area into a number of distinct sub-cases which..."

    While this might seem like a good way to solve a problem such as LoC, we have to realize that we are trying to systematize people. And, as our short and turtle slow SE history will show us, it will simply not work. We are all human beings and cannot be dealt with in this way with any degree of success. What else can we try? Let's go for some other type of science:

    The social science/hermenutic way to try to solve LoC: ...after completing the survey we chose to interview X number of people in order to find out how each respondant observed the situation where they were to interpret different types of code comments /../ We also discussed the issue with a psychologist and a didactics specialist and we found striking similarities between comment writing and writing tutoring books and..."

    Is this the ultimate way to solve problems like this? In all likelyhood no. But I am willing to bet that this is as good as we're going to get at this point in time. And while reading anecdotes can be entertaining, it is still only one persons highly subjective opinion and there is NO WAY that we will advance another centimeter (or inch, for the world standard challenged) if we don't fix this way of thinking about software development issues. Right now.

    1. Re:This is the worst kind of SE article there is by DennisInDallas · · Score: 1

      you jump to a conclusion / make an assumption that LoC is a problem to be solved. But view the situation from a different perspective, the PHBs that sign the checks for example:

      Only things that can be sold hold any value - the source code is like tailings from the mine.
      Source code, and the comments within are the domain of menials. These menials weep, moan and nash their teeth because of their lot in life. We, the ruling class, must constantly be engaged in the search for cost savings on the path to profit. The song of the menials as they toil is not a source of cost savings, or profit. If they have so much spare time that they can complain about each other's writings they are not working hard enough.

  254. If you can't read code, by Ray+Alloc · · Score: 0

    you should not have anything to do in the business of programming. I almost never put any comment in my code, it is way more readable and maintenable than my neighbour's code, where you have to look for code inside the comment jungle.

  255. it's notepad's fault by Anonymous Coward · · Score: 0

    Open it in Wordpad and it will indent properly

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

  257. Good comments would prevent bad software patents by Anonymous Coward · · Score: 0

    If you think it is hard for *you* to determine what your code does two years after you wrote it, think about what you are expecting some poor patent examiner to do when examining a software patent.

    How the hell do you expect a patent examiner (or for that matter, an attorney representing some poor clod being sued) to decipher your code and discover that it is prior art that invalidates some claim in a software patent if *you* can't even figure out what *your own* code does a couple of years after you wrote it?

    If nothing else, *that's* a good reason to write coherent, *understandable* comments for your code that do more than parrot the C-language (or whatever) statements on each line of code.

  258. Both are right/wrong by Sindri · · Score: 1

    The methods: "using short, descriptive variable names", "write code based on good documentation" and "write plenty clarifying comments in the code" simply don't contradict.

    You should use all of them.

  259. But are they? by newandyh-r · · Score: 1
    Comments indicate what the writer intends/thinks the code does. But only the code itself is "meaningful" to the computer itself.

    One of my friends has a policy that the first thing he does when attempting to maintain some (usually badly written) program passed onto him is to strip out the comments so that he will not be misled.

    I don't take such extreme measures myself - descriptions of procedure parameters and return values and references to unusual or clever algorithms are a good idea. Warnings like You are not expected to understand this or You are advised in your own best interests not to modify the following code without contacting ...* also have their uses.

    * Most slashdotters will know the origin of the first of these quotations, but how many know where the second one comes from? (unless you have looked at an assembly language known as GIN5 you are unlikely to be even able to guess!).

  260. Errrr.... Obvious ? by Anonymous Coward · · Score: 0

    What you are saying is BLINDINGLY obvious !

    In addition, there is no such thing as "self-documenting" code - the concept is utter rubbish.

    If you write code and don't comment it then you basically get what you deserve when you then try and maintain it years later.

    Code that is not sufficiently commented is at worse (ie - usually) unmaintainable, and at best very expensive to maintain.

    Simple.

  261. check out wtf by Anonymous Coward · · Score: 0

    this problem is not solvable. a pretty cool site is www.thedailywtf.com. It shows real-life, real-world, real-pain programming horrors that happen each and every day. The worst ones are the ones that are best commented.

  262. I was generating Smalltalk code from documentation by crovira · · Score: 1

    written in WordPerfect (the format was available, if not quite open).

    We wrote the documentation first and it was great. That was when I learned to hate Smalltalk's layout, so I changed its pretty printer to make some sense and used that instead to indent the output.

    --
    MSBPodcast.com The opinions expressed here are my own. If you don't like 'em... Think up your own stuff.
  263. 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.

  264. Re:Even more annoying... Checked Exceptions by Anonymous Coward · · Score: 0

    Bull, Checked Exceptions are More Important the comments.

    Had the unhappy experience of having to write a library for Dot Net. With No Checked Exceptions it was IMPOSSIBLE to pass along to the user of the class information about what Exceptions the class metheds threw.

    I could document the exceptions, which no one will read
    I could put doc in the class as comments which no one will read...

    I decided to make each method WRITE it's list of EXCEPTIONS TO Console.out.

    That solves the problem for anyone calling the library from within VisualStudio, But what about ASP.

    The real problem is LAZY Companies attempting to copy JAVA and get it WRONG.

  265. Commenting in Assembly Code by Zusstin · · Score: 0

    You know what, I have seen lots of Assembly language code for airlines, and i think the programs are *more often than not* well commented. A lengthy program header explains the programs relevance in the application, when it will be called, who will call it, in what process, its input/output etc etc. All subroutines also have a subroutine header which describes what it does, the input it expects/receives and the output - normal as well as in error scenario. This documentation - being assembly language - is down to the last bit! literally...Then the instructions are also well commented , most of the time i can get around with only reading the comments.

  266. Formal specification languages by jcrowly · · Score: 1

    There is quite a few reasons these languages are not more commonly used. Lets take Z for example, Z is a specification language you state with a form of set notation what the program should do (not how). However no client can read and understand your specification so determining if it's correct is very difficult. You then do lots of design work about the how, there is no method to automatically move from the what to the how(VDM attempts to address this but it's still far from automatic). You then implement, and test your code. Then find out the spec is not exactly what the client wanted fix test and so on. This is a very long winded process slow process which in the end does not guarantee any thing. Rapid prototyping in practice works a lot better you talk to your client get an idea of the data they wish to store and how they what to use it. Knock up some sample throw away screens to confirm with you client that you have understood what they meant, this stage gets repeated a few times. With reference to that, design data structures, and code tree, then implement and test. While all the time though you have the reference screens, and the ability to keep popping back to the client. This method is faster, the client gets constant feed back of how their app is taking shape. The problem with formal methods is a limited number of people can understand them and they don't work that well in real situations. They consume a lot of time for very little piratical gain. Ask IBM how much software they developed using VDM and they invented it. A lot of these formal methods are created by people who either can't program or have not done so for such along time they have no concept of how the industry works. They write their methods as an idealized version of how things should work and ignoring a lot of the human factor. There is always an in-built assumption that clients know what they want a system to do, or that the requirements can magically be divined by the people involved in the project.

    1. Re:Formal specification languages by GileadGreene · · Score: 1
      There is quite a few reasons these languages are not more commonly used.

      Yes, and many of these reasons have to do with the fact that your average code monkey doesn't want to learn something "new", or "hard", or that involves math instead of just random hackery. I shudder to think what would happen if we let other engineering disciplines get away with that kind of thinking. Imagine a structural engineer not well-versed in differential calculus and finite-element methods.

      Lets take Z for example, Z is a specification language you state with a form of set notation what the program should do (not how). However no client can read and understand your specification so determining if it's correct is very difficult.

      Z is not meant for the client. Z is meant for the design team. It is a way of precisely and accurately capturing a statement of what you currently think the client wants. Of course you're going to have to translate it for the client. That happens in all sorts of engineering disciplines. But if you're going to write specs - which you should be doing - you might as well write them in a form that has a well-defined meaning.

      You then do lots of design work about the how, there is no method to automatically move from the what to the how

      Yes, that's because what you're doing is called "design". It is a creative process. Often there are many ways to do a task. It's up to a good designer to decide on the right one. IMHO it is highly unlikely (barring the introduction of design AI) that you will ever be able to automatically move from specs to design. That's been a holy grail of sorts in other, far more mature engineering disciplines, and they still haven't worked it out. There're a few techniques that work when you have a limited and predefined set of components, and a straightforward problme domain, but that's about it. Design is inherently creative and very hard to automate.

      Then find out the spec is not exactly what the client wanted fix test and so on. This is a very long winded process slow process which in the end does not guarantee any thing.

      Sure, there'll be spec errors. There will also be implementation errors. But formal methods have a proven track-record of catching many spec errors - before they become implementation errors - and of making it easier to spot implementation errors. Are there any guarantees? No, of course not. There's simply an increased confidence in the design. And frankly, I don't think the process is as long-winded or slow as you make out. There are a number of well-known projects that made use of formal methods, and yets were able to deliver their software faster than usual, and with an order of magnitude fewer defects.

      Rapid prototyping in practice works a lot better you talk to your client get an idea of the data they wish to store and how they what to use it. Knock up some sample throw away screens to confirm with you client that you have understood what they meant, this stage gets repeated a few times.

      And you claim that this process isn't long-winded?!

      BTW, please note that I'm not suggesting that prototypes aren't valuable. They are. But so are formal specs and models. In fact, formal models can often be used as a first-cut prototype (I've done that myself with CSP), before you even get to code.

      While all the time though you have the reference screens, and the ability to keep popping back to the client.

      Which assumes that (a) you are developing a GUI intensive application, and (b) the client has the time to be bugged like that on a regular basis. Sure, if all you're doing is throwing together some kind of nifty GUI that does little in the way of backend processing then maybe formal methods aren't going to help (although I'd argue that even then there might be some value in formally capturing any feedback you geet from the client). But it's silly to assume that every developer does that kind of work. You don't use the same techniques to knock together a doghouse

    2. Re:Formal specification languages by bit01 · · Score: 1

      Just math.

      While I like formal methods and use them occasionally it's worth remembering that if you have to use informal methods to translate the customer specifications to the formal domain (and you do!) then you don't really have a formal method at all. It's just an informal hack that may or may not be better than other informal hacks like rapid prototyping etc.

      Like programs, formal methods are a tightrope - one false step and you're history. Having said that in many problem domains formal methods are a good fit. e.g. well defined realtime systems but probably not user interfaces because the user is complex and fuzzily defined. Depends on what you mean by a formal method of course.

      ---

      Large public or private organisations paying perpetual, recurring, per-seat licensing for software are being economically stupid.

    3. Re:Formal specification languages by GileadGreene · · Score: 1
      Having said that in many problem domains formal methods are a good fit.

      As I said, there's a difference between doghouses and skyscrapers.

      It's just an informal hack that may or may not be better than other informal hacks like rapid prototyping etc.

      The difference lies in the fact that once you're in the formal domain you can do many things that informal hacks simply do not allow. It's all about increasing your confidence in that the end-result is correct. Using formal methods allows you to firewall the imprecision and ambiguity, which makes ensuring the design is correct much easier. Informal hacks allow imprecision and ambiguity to permeate the design process - it is far harder to achieve confidence in your design if the design itself isn't really defined.

  267. Not so fast! by Anonymous+Brave+Guy · · Score: 1

    Some of those are on my top ten don't list.

    1. Comment each function
    - Function name

    Why do you need to repeat the name of the function? It's right there in the code. IME, this is one of the most common times when comments get out of sync with reality. Duplicating function names, parameter names, etc. adds no value, and can be misleading.

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

    Code with personal annotations should never be released. 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. In any case, the whole project dev team doesn't need to know that someone, somewhere didn't understand something.

    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. If I can, then whoever wrote it probably didn't fit it into the surrounding code and/or follow coding standards properly.

    Obviously, comments that cite a particular bug reference can be useful. Also, you can always look up who changed something and when using source control if you really need to ask them something, and that will get you information guaranteed to be accurate without the need for potentially misleading comments.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    1. Re:Not so fast! by mwood · · Score: 1

      Code with personal annotations shouldn't be *released*, but it's good in the interim. For example, early on I tend to write a lot of /* FIXME xxx */ comments so I can get the basic idea into working order and then go back and think about the corner cases without a lot of other concerns swimming 'round in my head. The module is not ready until all of the FIXMEs have been replaced with code which no longer makes me want to write FIXME. Sometimes a FIXME marks a stub that will be replaced with a sizable code block, but which serves to have something runnable for checking out the rest of the function.

      A *release* is like a finished building, but development versions are more like a construction site: there's mud and mess and temporary make-dos everywhere (all of which will be cleared away before the building is presented to its owner), and that's not a problem.

    2. Re:Not so fast! by AuMatar · · Score: 1

      On tagging bug fixes with names- sometime bug fixes are arcane. For example, you could have to add 2 lines to fix a bug that only occurs on one combination of hardware, and that makes little sense (or would actually break) other combinations. Tagging it with a name tells maintainers and future developers who to contact if they come into a similar problem or if the hardware bug is later fixed and it breaks the code. It shouldn't be done on every change, just the difficult to understand ones.

      --
      I still have more fans than freaks. WTF is wrong with you people?
  268. // time commenting could be time coding by Pastis · · Score: 1
    Allow me to link you to this 'fake' commercial reference:


    Day in, day out, you pull off star moves: gnarly algorithms, wicked refactorings, stunning optimizations. Why should you stop and explain? Yes, you've got plodders on your team, but hey -- YouAreAStar and YourTimeIsExpensive. Time spent explaining, documenting, commenting -- dude! -- that's time you could be using to crank out yet more mind-altering code.

    Welcome The Commentator


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

  269. Who's right? by Wormholio · · Score: 1
    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?

    They are wrong, you are right.

    --
    "Education is not the filling of a pail, but the lighting of a fire." -- William Butler Yeats
  270. The Unlearnable Lesson by Anonymous Coward · · Score: 0

    When I was learning C in college in the late 80s, a professor insisted that the programs we turned in for our assignments have an *average* of one line of comments per line of code.

    I thought he was a nut.

    Later, when I got into programming for a living during the early 90s (since left for greener pastures), and was writing code that I had to maintain, I decided to check my comment-to-code ratio on code that I was producing. Darn if it wasn't an average of 1:1. Several years later, I was able to dig that code up, and I found I could tell what a module or function was supposed to do and how it worked.

    Good commenting, like good end-user documentation, is a lost art these days. Programming courses don't emphasize it enough, and programmers in general would rather whine than write decent comments for the people who'll have to maintain their code. And management-types are the worst offenders, because they have no comprehension of the value, and hence won't budget the time needed to do it right, nor insist that it be done.

    Basically, software engineering is dead, and has been replaced by code monkeys who pound out code that management hopes to sell as the latest from Shakespeare.

  271. Re:Comments? Pshaw! by djmurdoch · · Score: 1

    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.

    Code can have bugs and it doesn't always do what was intended. Sometimes comments have errors too.

    We don't throw up our hands and say "never write code, it might not be perfect", so why do that over incorrect comments?

    Learn to do your job right. Don't depend on what was written in any comments. The compiler ignores comments; so should you.

    As your own experience showed you, sometimes what was written in the code can't be depended on either. Compilers can have bugs too.

  272. Ban all comments and insist on readable code by RobWalker · · Score: 1

    There's nothing more annoying than old, out-of-date, or just plain confusing commments used as an excuse to explain poorly written code. Ban all comments and work on making your code compact and easy to read and understand. I'd much rather read 20 lines of well written code than 50 lines of garbage with another 20 lines of comments as an excuse for not writing it better in first place.

  273. Code and Fix! by Anonymous Coward · · Score: 0

    That reminds me of a humorous anecdote:

    One of my computer courses in college was Software Design, where they teach you how to document and plan before you code, and various development models.

    One day the teacher was going over all different models, the first of which being "Code and Fix". Right after she said that, half the students cheered. Her response was a sigh and a shrug...but it was clear that everyone knew what reality was, and still is.

    One note of interest: This was not an introductory, or even first year programming course. This was my 6th, maybe 7th course even...

    1. Re:Code and Fix! by mwood · · Score: 1

      One difficulty in teaching the more structured development models is that you need a *big* project to really feel in your gut that this stuff is necessary. Most courses just don't have the time to do big projects, so the class sit there thinking that what they're learning is overkill for anything they've done.

      I'm reading up on some of this stuff right now, and half the time I find myself thinking, "yes, that looks useful, but not on any of the tiny projects I get."

  274. Mod parent up! by sgtrock · · Score: 1

    Probably the single most useful post in this entire thread!

  275. Comments can't be more important than code by SavageSMC · · Score: 1

    The whole point of the code/comments it to create a computer program that does some function. This can be accomplished without a single comment, but can't be without code. I appreciate code that has what I call "good comments", but code that has wordy, or even innaccurate comments (which is over half the code I look at) is less readable than the plain code. A lot of times the comment says one thing, while the code does something else.

    I think if you are going to be competent enough to write software in a given language, then you should be able to read it fluently - hence no need for a lot of comments in the middle of code. There are a few times were something tricky is being done, or there is some interaction with code in another location, where you need a brief statement to remind a later reviewer of such things, and some documentation in the interfaces (headers) is nice - IF KEPT CURRENT AND UP-TO-DATE WITH THE CODE!

  276. Edges and constraints make coments critical? by QuestorTapes · · Score: 1

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

    I think there's an important point there. Code == documentation makes the assumption that the code is clear. Many times it isn't -possible- to make the code as clear as it needs to be to be useful as documentation. Third-party code is one of the reasons; time constraints and legacy codebases are a couple of others.

    I remember once in the newsgroups, P. J. Plaugher was discussing the C++ Standard Library implementation in VC6, and mentioned that one reason the code was unclear was because of compiler limits; when VC expanded certain templates, the identifiers for some template classes exceeded the compiler's limits.

    What else makes it more difficult or impossible to write code that is clear enough to be documentation?

  277. Manager's Riposte by 4of12 · · Score: 1

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

    True enough. I subscribe to the philosophy of doing things the best right way personally, too.

    But any manager could tell you that there is a time value to money, getting that money in hand sooner rather than later is better, and with the interest made on that money we can patch things up only as much as absolutely necessary (kind of like how successful landlords work - they want the money right now and they'll get to kludgy repairs some time next week as soon as he can get hold of that guy that does slipshod work for cheap).

    --
    "Provided by the management for your protection."
  278. Good code is self-evident by Anonymous Coward · · Score: 0

    The "really best algorithm" is always self evident and writting and maintaining "commnets for dummies" is a waste of time.

    Moreover, I write open source. Why should I make it easy for you to rip off and steal it? If you can't figure it out, patches are welcome.

  279. Yes, it makes search/grep/replace harder to do, by Anonymous Coward · · Score: 0

    What about your version control system? You are using version control, aren't you?

  280. Re: On code maintenance and commenting by Odocoileus · · Score: 1

    That is how I view every possible interaction I ever have.

    --
    ...
  281. Good programmers don't comment. by Anonymous Coward · · Score: 0

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

  282. Comment your f$#king code!!! by Anonymous Coward · · Score: 0

    The subject says it all, no more comment needed :)

  283. Well... by ThePyro · · Score: 1

    Well what do you expect, when evil professors tell students that they must comment EVERY line of code or lose points on their grade? That was my experience.

  284. Many coders are not good writers by mildgift · · Score: 1

    That's why there's so much aversion to documentation. Many, if not most, people are averse to writing in any language. Their spelling isn't great, or their grammar isn't quite right, or they have some trauma they experienced in English class. These people develop an aversion to writing.

    I like to write, to the point where I can even tolerate editing second and third drafts. Not surprisingly, I like to document code, edit the documentation, and even re-document code correctly if I screw it up the first time.

    I do not, however, like the literate programming style. That's a whole different thing. My favorite style of documentation is JavaDoc, or PHPDocumentor.

    JavaDoc rewards you for writing extensive documentation for your interfaces, and penalizes you for writing lots of comments in your code. It encourages you to develop a narrative about your objects, rather than a detailed outline of your code.

    Not that there's something wrong with outlining code! I often start coding by writing a couple dozen lines of documentation about the specific alorithms and methods I'm using to implement a function. This kind of "documentation", however, isn't that useful to someone who needs to figure out if they're making changes in the right part of the application.

    They need the overview, and that takes more effort to write.

    PS - I'm not a big believer in using accurate variable names everywhere. I think it's often better to use generic names, preferably the ones used in the examples in the man pages, and explain what's going on in a couple lines above the code. Once you have the output you want, save the values to variables with long names, or better, save them into objects. Here's what I mean:

    result = query("some query:);
    for (i=0; i=next(result); out += i);
    total_hours = out;

    result = query("some other query:);
    for (i=0; i=next(result); out += i);
    total_break_time = out;

    It's better to reuse the variables, because it's a way to signal to the reader that in both blocks of code, we're doing the exact same thing. This is "idiomatic" programming. At the top of the block, you "set up" the unique aspects of the block. At the bottom of the block of code, the output is assigned to a unique variable.

    Arguably, you can put the repetitive code into a function or macro. However, it's not always worth the extra effort, and can be confusing if you have two or three very short, very similar function that differ in just one or two lines. Sometimes, unfactored code is okay.

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

  286. Like this? by Mintee · · Score: 1

    from arch/sparc/lib/sdiv.S in the linux kernel. /* (I do not understand this) */
    ! %o5 > %o3: went too far: back up 1 step
    ! srl %o5, 1, %o5
    ! dec %g7
    ! do single-bit divide steps :D

    --
    Help me get a PSP! Who can afford s
  287. PHB woes by hotspotbloc · · Score: 1
    Allowing comments would "encourage coders to use clever tricks" according to the technical director.

    Our's banned comments because he said it made the executable bigger. Not a problem since the project never shipped. =)

    --
    "I hate to advocate drugs, alcohol, violence or insanity but they've always worked for me" - HST
  288. Re:And this, my friends, is why offshore outsourci by Politburo · · Score: 1

    All taxing the wealthy does is drive economic activity out of the US.

    Tell that to Bill Clinton.

  289. Programming languages are languages - be literate by dazedNconfuzed · · Score: 1

    Code is more important than comments. It's what you're actually writing purposefully - so write it clearly in the language which other programmers understand. If we both know C++, why must we drench your program in English translations of what has already been written in a language we both know?

    Obfuscated or clever coding, obscure enough to require comments, is rarely needed. If someone needs a comment to understand what you've coded, you probably can de-obfuscate the code better and make it more readable (and thus probably less buggy). On the whole, code should explain itself as the ultimate detailed documentation of what the computer must do; context, decomposition, and meaningful naming does far more in most cases to explain what is happening than translating that linguistic expression into another language.

    Write code for other programmers. They know the language - write in a manner which they can understand in that language. Doing so largely eliminates the need to subsequently translate that into another language.

    Yes, comments are occasionally necessary. Some things just make more sense when expressed in another language. Most of the time, just write clearly in whatever language is most appropriate; for programmers, get literate in C++, Java, SmallTalk, whatever.

    --
    Can we get a "-1 Wrong" moderation option?
  290. Self-documenting code...written *when*? by whitroth · · Score: 1

    So the piece's co-worker/opponent thinks all you need is short, descriptive variable names. Conditions? Functions?

    Oh, and when were those short, self-descriptive names chosen - 0337, 18 hours after your first coffee of the day?

    mark "i_blertfk"

  291. code example by sonofagunn · · Score: 1

    if (codeIsWellWritten)
    {
    writeCodeWithoutComments()
    }
    else
    {
    writeCommentsThatWillSoonBeOutOfDate()
    }

  292. Simple steps that should always be followed by n_clero · · Score: 1

    I thought this was a pretty interesting topic seeing as I was up until the wee hours of the morning last night doing some major programming for one of my final assignments.

    This was a group assignment so we have essentially 3 guys, 2 who are programmers working on the same project. I do a bulk of the programming so most of the code there is mine, but the other programmer has a style of coding completely opposite of mine.

    We're coding this thing in J# which we all taught ourselves. We're all hug java fans so that's why we chose this language.

    Our code has basically no commenting. It did at first in the early stages of development, but as things took off, the code doubled and tripled and soon there was so much. I think the main reason for this is because many of the forms used follow the same logic, all have similar functions (but not similar enough to design a class to handle all the operations). Anyway, since I was project lead, and I did most of the bulk code, I knew what was going on at any point in time - since it was my logic. The other programmers code which handled different operations was not so readable - but he probably thinks the same as mine since I specialized in the part of the application which handled interacting with the database.

    The following are things that I think greatly aid the readability of code between programmers:

    1) Good Variable Names - descriptive, but not a novel, short, but not an abbreviation of an abbreviation you've made yourself.

    2) Follow flow and use proper indenting. Methods, functions, subroutines, all that should be indented properly. So many times I rely on the indenting to understand the flow of the application.

    3) Comment difficult procedures. If something has caused you a lot of grief to program, document what the hell it is that you came up with. A programmer trying to interpret your code is going to be just as confused as you were when you encountered the problem. If you document how you solved that problem, or why you chose to do what you did your teammates are going to love you.

    I guess there can be excessive commenting and what's required. With good variable names, proper indentation, and comments guiding the readers of your code through the more difficult areas you'll be fine. I mean hell, if they don't know a thing aabout programming to begin with, why would they be reading? You should assume the reader has at least a minimal understanding of programming logic.

    --
    Yes, I am a programmer.
  293. A good heuristic for how to comment by Dixie_Flatline · · Score: 1

    Forget about other people. Worry about yourself. If you document code so that you would be able to come back after 5-10 years and be able to pick up where you left off with just a little bit of time reading comments, it'll be good enough for anyone.

    For you 'genius' programmers out there that don't need comments: you're lying. I find most people that take that stance end up just hacking up a solution to their problem and cramming it in, regardless of thee appropriateness, and spend a lot of time complaining and debugging (though still never really getting everything working quite as well as would be liked).

    Besides, commenting code is fun. It gives you an extra chance to be creative during the day. You can be conversational in your comments. I don't see anything wrong with comments that read like: // Holy frijoles! Our pointer ended up NULL, and now we're boned. Call the failover case and clean up.

    Sometimes, if you're under stress, you may want to reduce that timeframe. In University, I spent a whole weekend awake and working on a project. At some point, I was adding documentation so I could remember what I was doing 4 LINES ago. Ideally, don't code tired, I guess. Barring that, though, make the comments work for you.

  294. My favorite uncommented code of all time: by chad.koehler · · Score: 1

    if (!(strFilter == R996 && NoChanges(pStruct))) { ... }

  295. well duh by AviLazar · · Score: 1

    Anyone who took CS141 can tell you this is one of the first things taught. One of my teachers went so far that 25% of your grade (for that programming project) was based on your comments and your flow chart.

    --

    I mod down so you can mod up. Your welcome.
  296. You are right by mwood · · Score: 1

    Just because you understand your code today does not mean you'll remember why you did it that way six years, or even six months, from now. It's happened to you. It's happened to me, too, and to lots of others.

    Notice that in the tech books filled with big slabs of code, code crafted *specifically* to teach the reader, the author still has to explain, sometimes at considerable length, what the code does and why it does it that way.

    Poor commentary is a waste of time -- it only tells you what the code tells you. This is true. But good commentary tells you things that cannot be expressed in the code. Things you'll need to know if you want to repair or recast or reuse the code.

    But aside from that, writing good, durable commentary helps you to build better code in the first place, by making you think twice, in two different ways, about what you are doing. I wish I could recall specific examples, but I'm sure that more than once I've saved myself from error when I looked at the comments I wrote and said, "that's nonsense -- what is really going on here?"

  297. Business Rules and minimal comments by Maxo-Texas · · Score: 1

    You should have an external document that says what and how your system should do. Constraint and validation definitions should be there. When users propose a change, update that document and review the proposed changes with them. Then implement the agreed on changes in the code. Comments should be limited. Code should be kept in a source control program with versioning and old commented out code should be removed after a few months to a year if not immediately. In my experience comments are often wrong on code which has been maintained more than a few years by more than a few programs. You should require all variable names to be descriptive if their scope is more than a tight loop. Code should be reviewed by another programmer before it is installed. You should use a program that does automatic validation of your minimal coding standards.

    --
    She was like chocolate when she drank... semi-sweet at first and then increasingly bitter.
  298. You are right by oogoody · · Score: 1

    Have these people come up with a big bunch of code that is self documenting. Then if they can, which they won't, how much of that code exists, even if people are trying? Less than 5% certainly.

  299. Clean the code, Comment the subtle or exceptional by tz · · Score: 1

    One great OO evil I see is instead of allowing "a=b", which would be obvious, you must do SetValueOfA(GetValueOfB()); Which simply retrieves the private copy of B and sets the private copy of a. If "A" is doing something critical, e.g. in an embedded system, so it must be limited as to range, how fast it changes, or validated against other variables to keep things safe or sane, use SetValueOfA, as it tells you that it is doing something more than a=arg in the body.

    Comments are similar. First, the worst peeve is when they get out of sync. More comments, the more likely they are to get out of sync when code changes but comments (some may be a few lines away, or at the function header, etc.) don't so you are trying to figure out which of two has a bug.

    When the function of code is clear from the topology, local variable names should make things clear (I use i,j,k for throwaway indexes, curtated names for temporaries, e.g. something in converted engineering units, and longer names for important variables).

    Many comments are very important indicating subtlety, e.g. if you are accessing something from a buffer which is really a struct but don't want to worry about doing unions and endians, it would be made very clear by simply saying "Pulling a 32 bit unsigned as record size starting at byte 8" - and that comment would be clearer than doing the union/struct/htonl stuff.

    Comments ought to be like a gloss on the code, explaining the subtleties or exceptions. When something appears simple but is doing something underneath, it needs commenting. Or if you doing something where EOF will be an exception or signal handled completely outside the block of code so it doesn't appear you forgot.

    They should be few because if these critical comments are merely a half-dozen among several hundred, how do you find them? Look for "CRITICAL:" - will that be maintained?

    Good code with clear topology (see "The Programmer's Stone" on the Quality Plateau), with comments bringing into high relief the nonobvious is a beautiful balance - for lack of a better word, it is Zen.

    Comments won't fix badly written code. Good code won't be helped, and may be obfuscated by lots of redundant text (isn't it better to see the whole routine on one screen, than have to scroll across several because every operation occurs twice - once in code and once in comments?).

  300. Unit test and UML diagrams by $nickname_212 · · Score: 1

    Unit tests will show how a method is used. This should be enough documentation on the use of a method. In addition, the unit test will tell you when you have broken your code with a bug fix(a regression).

    I supplement the above with class diagrams and most importantly sequence diagrams. The value in a class diagram is kind of obvious. But what comments lack, and to a degree unit tests, is showing the overall sequence that occurs. This should diagram the interaction of events. The digram illustrates when certain methods are called, what methods they call and what returns the caller receives. There are a number of other useful diagrams like the collaboration/deployment, state, activity, and last, but not least, Use Case diagrams. Without the code being associated with a Use Case, it can be argued you are writing code that adds no value to the code; in other words, you are just wasting resources.

  301. I agree by robyannetta · · Score: 1
    Code is important, comments are priceless. Let me give you some examples of comments I've seen digging through someone else's code: (the following is true)

    /* what the hell does this do? */

    /* who wrote this shit? */

    /* this is supposed to fix the code that didn't work but I don't know which code it was supposed to fix - if you know what this is supposed to fix email me at [email address here] */

    /* whoever wrote this beware: when I find you I will track you down and kill your dog!!!!! */

    --
    - Just my $0.02, take with a grain of salt, your mileage may vary.
  302. No kidding by SuperKendall · · Score: 1

    My new rule of thumb is that if I can fix a bug in Emacs in less time than it takes Eclipse to start, I use Emacs.

    I haven't fired up Eclipse in weeks.

    For those not in the know - JDE! It does enough that you can live without Eclipse (or anything else for that matter).

    Then use NetBeans for debugging because it takes about a second to mount your source tree and start debugging against it. Does it care you don't have libraires defined to build? Nope! It just lets you debug assuming that the reason you pointed it at that source is that it was correct for the debugging session!

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  303. He still would have been docked by SuperKendall · · Score: 1

    I don't think you have a proper understanding of computer courses. It doesn't matter how clear the variable names are, the checkbox for the professor is "are there comments". Code is not comments, and therefore that code would have got him docked just as badly.

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  304. An all-time favourite meta-comment by Anonymous Coward · · Score: 0
    switch ( function ) {
    case -1:
    /* it would be nice to have a comment here;
    * if this is obvious, you need help
  305. Evil use of doclets by SuperKendall · · Score: 1

    "Hey, why is the compile taking so long? It's been over an hour!"

    "Well, you see, there's a new doclet that inserts a comment for return values in a methodthat returns the set of all postive numbers. It's the latest AMD box so it shouldn't take too long, I don't understand it.".

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  306. 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.
  307. Good Self-documenting code? by sirgoran · · Score: 1

    This was written a few years ago by a friend of mine . He thought it was a great way to express the business plan of the company we both worked for.

    We often joked about using it in real work. Has anyone ever used something similar to show job dissatisfaction?

    function develop (newIdea);
    if (newIdea == yourIdea && newIdea > jorisIdea){
    get (swiftKickInTheAss);
    } else if (newIdea.mentioned (toJori) && newIdea != jorisIdea){
    get (swiftKickInTheAss);
    selfWorth = null;
    set var (newIdea) = jorisIdea;
    delete spine;
    develop (newIdea){ ? (yourJob = CompanyName);
    }

    -Goran

    --
    Carpe Scrotum - The only way to deal with your competition.
  308. "nothing to do" comments by timster121 · · Score: 1
    I once worked for someone who decided that there should be no negative IF statements what so ever. Something about "morale needs to improve and we can help this by writing positive code. Plus it will be easier to read." I don't know what he was smoking.

    This means that simple comparisons like $something != $something_else became way more difficult and contained completely usless comments:
    if ($something == $something_else)
    {
    // nothing to do
    }
    else
    {
    ...code...
    }
    These were probably the most annoying comments I've ever seen. It only got worse with statements like ($something != $something_else && $this == $that).
    1. Re:"nothing to do" comments by WillAffleckUW · · Score: 1

      I do this all the time.

      But the reason I have // nothing to do
      comments inside if statements and while loops is that TODAY it does nothing, but later some code might be added to deal with the other possibility.

      It's relatively easy to add code in a section, but harder to change the code to use reverse logic later.

      Now, that doesn't mean I don't have statements like:

      if ( (!($foo) && (length($foo)==0)) && (!($bar) && (length($bar)==0)) && (!($bush) && (length($bush)==0)) && (!($m0r0n) && (lenght($m0r0n)==0)) )
      {
      $hash_frog{$mufti}=0;
      }

      But's that usually preceded by something like:
      # if invalid, reset frog to original color

      See?

      --
      -- Tigger warning: This post may contain tiggers! --
    2. Re:"nothing to do" comments by WillAffleckUW · · Score: 1

      dang, compile error ...

      (lenght($m0r0n)==0))

      obviously I meant length

      never write code if you are busy doing something else in another window.

      --
      -- Tigger warning: This post may contain tiggers! --
  309. A clue???? by Anonymous Coward · · Score: 0

    What code like that tells ME is that something probably changed and I should probably find out why!

    As opposed to the second example, which wouldn't alert me to possibly unmissed side-effects of that change.

  310. Depends on the language. by Richard+Steiner · · Score: 1

    When I'm writing in assembler and doing a lot of register juggling, for example, I'll usually put in-line commentary in the code describing the nature of the values I'm working with and the operations I'm performing (since that isn't obvious at all from the code statements themselves).

    I also sometimes do that in older Fortran dialects since most of them are limited to six-character variable names, and since it's not always obvious what is being done.

    --
    Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
    The Theorem Theorem: If If, Then Then.
  311. And now without comments: by Chemisor · · Score: 1
    // Update frames-per-second statistics
    current_time = SDL_GetTicks();
    update_interval = current_time - last_update;
    fps_stats.totalTime += update_interval;
    ++ fps_stats.nFrames;
    last_update = current_time;
    You wouldn't need so many comments if you named your variables right. You name your variable 'tmp' and then use it first as a holder for the last update time, and then for the interval. Why? Don't you know that the compiler is perfectly capable of reusing a register? Then you assign current time to last update when you still need the old value. Add a variable and you no longer need tmp and the code becomes much clearer than your comments made it. The code becomes a comment, and that is exactly the result you should strive for in all code. I only have one strategic comment in my version, but even that should be unnecessary if you placed the code into a function named something like update_fps_statistics.
  312. new technologies getting it backwards by kisrael · · Score: 1

    An interesting thought in all this...
    I'm slowly formalizing a philosophy that the most "control flow" should happen in a single file, preferably readable on a single screen. Difficult tasks should be delegated to appropraite API and/or objects.

    We keep talking about "comment your code" but so many modern technologies (J2EE, I'm looking at you) try to do more and more "without writing a single line of code!" So in some ways we're set back. I guess you can "comment your XML file!" but it seems to be that there's often a disconnect.

    --
    SO YOU'RE GOING TO DIE: The Comic for Dealing with Death
  313. Justify the code by Skapare · · Score: 1

    The commentary should justify why the code needs to be there. If you can't justify it, remove it. But comments like

    /* this program dies if this code is removed */
    don't really cut it. The comment should explain what role this code has in the overall design. For example if you have a call to the fopen() function, it should be obvious that a file is being opened. But answer the question "why?" to make the comment informative.
    /* re-read the config file */
    Of course, having good names for things can also help:
    config_fp = fopen( config_file_name, "r" );
    --
    now we need to go OSS in diesel cars
  314. Re:And this, my friends, is why offshore outsourci by Anonymous Coward · · Score: 0

    Have you ever considered the possibility that work came to India because it wasnt commented well enough the first time?

    Welcome to the real world. Indians get your jobs because you cant do it well enough.

    Its a sad thing that I bite the bait.

  315. computer-generated HTML - a good thing by matt+me · · Score: 1

    in a language as understood as HTML, comments are pointless. computer-generated HTML is also very nice. though the source may view source, if you want to decode it. perl::HTML makes it so easy to extract information from the perl-generated bbc website.

    my fave comment in php is from blog-system Wordpress
    "if you delete this line, the sky will fall on your head"

  316. Anyone who thinks code can be self-documenting... by bwcbwc · · Score: 1

    ...has so many bugs in their code that they still work on it on a daily basis years after they originally wrote it.

    Regardless of your philosophy about HOW to comment, I don't think anyone rationally can argue that code should exist without any comments.

    --
    We are the 198 proof..
  317. what kind of article is this anyway? by the0ther · · Score: 0

    Sounds pretty self-serving man. Why read your article when the classic "Code as Design" has already been written. Stupid noobs gotta do their homework.

  318. My philosophy is by robertjw · · Score: 1

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

  319. code is more important than c omments by Anonymous Coward · · Score: 0

    My job is to deal with unfamiliar code. I never read functional specs. I skip most long comments. cscope tells me most of what I want to know. I do rely on structure fields and flags having comments. The code I read has a change log; I read that too.

  320. Form follows function? by Anonymous Coward · · Score: 0

    "Form follows function - that has been misunderstood. Form and function should be one, joined in a spiritual union."
    Frank Lloyd Wright

  321. Documentation is like sex... by gorodish · · Score: 1

    Even when it's bad, it's still pretty good.

    1. Re:Documentation is like sex... by DennisInDallas · · Score: 1

      I've read quite a bit of source that led me to believe that the author must have been choking his chicken

  322. A Reason for commenting "Hello World" by jtpalinmajere · · Score: 1

    After being trained to take over two of my universities Intro to Programming courses, I was granted the almighty insight as to why the curriculum (and thus graders) require such innane comments all over the place in history's most inconsequential programs to date.

    I'd have to wager that many of us found the process quite annoying... and it is. Especially so for those who already have a knack for programming. For these people, the intro classes only serve as an intro to the language the rest of the more meaningful classes use. However, for those who are less talented, or are completely clueless to the field to begin with the commenting process becomes very crucial.

    In this case, the commenting becomes a tool for student and teacher/grader alike to assess how much the student understands just what it is they're doing. Unfortunately in most cases where the student is gifted, they feel it is just a mundane practice since they're commenting things that are 'obviously' obvious to everyone else... which actually isn't the case in the intro courses.

    I've graded more programs than I care to think about where the program, while performing as requested, was littered with code that essentially did nothing. The use of comments allows teachers to understand why a piece of code was written by the student, and also acts as a preemptive remedy for useless code when the student realizes that a line of code he thought was needed, or had a hunch on, actually wasn't.

    Past that primary focus of the commenting process in the intro classes, the object of commenting is very minimally for the purpose of developing good commenting skills for later use in collaborative projects. This is because, it is assumed that all future 'good' employers already have different standards for good commenting in place, and becoming a 'good' commenter, not to mention organizer of code, depends solely upon the framework your organization allows you to work in. In other words, they opt out of strictly teaching 'good' commenting in favor of a "Practice makes perfect" approach.

    ... at least from my university's perspective.

    Also, I believe it is dangerous to assume what is obvious and what is not. If we compiled a list of what everyone thought every 'good' programmer should know, i would imagine the list of things would come close to an effectual "a good programmer should know... well... everything". Thus, it is safer to assume nothing.

    Let me give you an example of what I mean. Lets say a VB programmer was the only resource on hand to tackle a project originally written in C by a very saavy C programmer... and this VB programmer had never written or read a single line of C to that point. Beside the fact that he would have to learn the language on the fly, many of the things that the C programmer might consider obvious would likely present themselves as huge stumbling blocks to the VB programmer. I mean... you gotta start learning somewhere.

    That may be an extreme case, but I've seen it happen more times than one might think it could happen. The principle essentially holds when writing in languages otherwise not considered 'popular' at the time, or if you're updating old code that WAS 'popular' at the time, but no longer is... kinda like COBOL.

    To reiterate in one last statement, "Never assume ANYTHING!"

  323. Comments don't execute by Symbiot · · Score: 1
    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

  324. The Thesis of TFA by Anonymous Coward · · Score: 0

    Let me start off by saying that if you can't clearly communicate in your code, then you probably can't clearly communicate in your comments, either. The belief that one person would write obscure arcana with their left hand and interweave it with a plain-spoken interpretation of itself using their right hand strikes me as ridiculous -- they're either doing a poor job of making the obscure readable or they're not telling exactly what it does.

    That said, the conculsion of the article is this:

    "Good documentation includes background and decision information that cannot be derived from the code."

    First of all, we call those "Business Requirements" and "Design Documents", not "Code Comments"

    Second of all, I've yet to work with any Asian folks who would be able to not only make good sense of "We used a Byzan-Floritine quasi-macro here which allowed us to leverage the demo code we presented to management in June while maintaining synnergy with project Foo Bar [Update: Foo Bar got cut due to lack of funding; no time to revisit this decision.]" but then also maintain the code that goes with it.

    That kind of comment neither particularly helps them understand the code ("My Microsoft Certified Training does not cover this Byzan-Floritine quasi-macro of which you speak.") nor does it do anything to help them take ownership of the code so that they stop calling me and taking up my time which our IT department deems to be substantially more expensive than their time -- which is why I'm not allowed to maintain my own code.

    The comments that tend to go in my code typically start with "Here's where things get tricky about [bit of esoteric business logic]" or "Not the prettiest, but this actually works..." -- and we've got automated unit tests to ensure that it actually works, too.

    The sort of code that doesn't get documented?
    throw new ValidationException.Because(Reason.NumberTooSmall) ;

    Wouldn't you know it, those Malaysian support folks said that they liked how easy it was to read my code compared to the 4 other projects they were taking off our hands.

  325. 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
  326. Extreme Programming by mosel-saar-ruwer · · Score: 1

    That would only work until people start doing what they basically do now and confirming that the comments are correct without actually taking the time to verify that fact. (Subtly incorrect is often much worse than obviously incorrect.) Granted, the system would remind the programmer to check, but a rushed glance at the comment will likely result in "yeah, it's fine" when it's not.

    Last night, after posting the grandparent, I was thinking about that very problem, and thought that [for big shops with the resources to pull it off] extreme programming might be the answer here: The code and the comments are flagged as dirty after any changes made by the primary programmer, and can only be flagged back to clean after they have been cleared by the secondary programmer.

    Again, it would require a huge investment up front [say $100,000 per programmer, and $100,000 for the ultra-cool database-driven document-management content-versioning system with the kitchen sink], but, down the road, it might offer some significant savings, in the form of more stable, more maintainable, and less bug-ridden code.

  327. I think you need a lesson in platform diversity. by Richard+Steiner · · Score: 1

    Ah. Would you care to port it to OS2200 then? The Unisys 2200 environment has no CVS port as far as I know, and it must be an easy task to do so given the flippant attitude in your response.

    Right?

    Or perhaps it didn't occur to you that there are a number of production *mainframe* systems out there that have been around for a very long time and that don't run on Intel hardware or use POSIX-compatible operating systems.

    The whole world isn't UNIX and Intel, just the majority. But that doesn't mean that other platforms don't exist.

    --
    Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
    The Theorem Theorem: If If, Then Then.
  328. FWIW... by Richard+Steiner · · Score: 1

    We are able to manage multi-million-line systems quite effectively without using tools like CVS.

    All it takes is some sort of intelligent change management system, not necessarily source code management, and perhaps also some additional tools so people can quickly see the status of a given source module.

    FWIW -- we often leave small blocks of commented code in the production source. Why? Because our internal customers have been known to change their minds in the past. Believe it, or not. :-)

    --
    Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
    The Theorem Theorem: If If, Then Then.
    1. Re:FWIW... by MalaclypseTheYounger · · Score: 1

      I think we have the same customers :)

      Obligatory Clerks reference:
      This job would be great if it wasn't for the f***ing customers.

      --
      Check out the best P2P sharing website: MEDIACHEST.COM
  329. 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)

  330. tmp is a curse word by DennisInDallas · · Score: 1

    descriptive variable/constant names are good thing, they only are not sufficient, but a good thing none the less.

    The snippett referenced above could be cooler by escewing the use of 'tmp' as a data element name... There may be some extremely rare instances where such usage is warranted. But in large, use of such names is somewhat akin to the use of profanity: the resort of the weak minded when they are at a loss for comunication tools.

    Here's another go at it:

    \//add elapsed time to fps accumulator and counter
    current_update_time = SDL_GetTicks();
    msec_since_last_update = current_update_time - last_update;
    last_update = current_update_time;
    fps_timer += msec_since_last_update;
    fps_counter++;

    maybe that's no %$#^* better

  331. Write the comments first by DennisInDallas · · Score: 1

    ...then off shore the coding

    we're doing it the other way around here and it's not working out very well (no, I'm not saying where here is)

    Once I had to write a windows 3.11 device driver, so I downloaded the windows device driver developers kit (DDK) from microsquish... It was all 80286 assembler with the comments in spanish. I like assembler: it's not all uptight and regimented like c is, but I would have liked to have been able to read the comments. I was able to get my device driver written & working (& two years later a win95 version but I bailed on the win98), I'm not sure that it would have worked out as well if I didn't understand the example code but I did get the comments. I guess that's what being a PHB would be like.

  332. Re:Commenting ion Assembly Coders by DennisInDallas · · Score: 1

    it's been my observation that programmers that work in assembly are more disciplined and neater than those that work in oh, say VB or c# for example.

    Now, it's harder to draw such broad generalizations about perl coders, some are elegant and others are, well... like a kid with finger paints.

  333. What vs. Why by CarlBarnpipe · · Score: 1

    Even the best self-documenting code can't tell you why it was written.

    A good comment, by contrast, can answer the question, "Why the hell did he do it THAT way?" or "Now, what the fuck was I trying to accomplish when I wrote this?"

  334. Programmer XOR Musician by (1-9)(0-9)* · · Score: 1

    good programmer ^ good musician

    Elaborate please. Someone is claiming the opposite view that musicians are more prevalent in the programming profession than elsewhere!

    1. Re:Programmer XOR Musician by bluGill · · Score: 1

      More prevalent yes. However look at quality. Those who are good at one are bad at the other. If you read the link you will see that my claim is not incompatible with theirs, though some who write there will disagree.

      I'd be considered a musician because I play mandolin. However I lack the talent to play it well. I enjoy it, so I keep on, but I will never be good. I'm generally a good programmer. (Not the best, but I'm better than most)

      The musician in my original post (needed 20,000 lines to do what was redone in 3,000) was an excellent jazz musician. If touring wasn't so difficult he would make just as just as much playing on the road as he does as a programmer. To his credit, he can get by with code, and he is a better leader than most programmers, so he is worth more to management than most programmers even though overall he isn't a good programmer.

    2. Re:Programmer XOR Musician by dooglio · · Score: 1

      My question would be--sure the guy reduced the original code down by quite a lot, but why was the code written in such a way in the first place? Was it designed to be extensible and reusable? Did the junior programmer in question make the code run faster and more reliable? Did he just concatenate lines and strip out comments? Or was the senior coder just not competent?

    3. Re:Programmer XOR Musician by bluGill · · Score: 1

      The new guy completely re-wrote it from scratch. Part of the reason the code was so bad is it grew rather than be designed. Speed wasn't an issue (it was just a modified bootp server, the old guy started with a BSD bootp in fact), fixing bugs and the ability to add features was.

      The old code was commented well, but stripping comments still would only be worth a few thousand lines, and the code would still be unreadable. I'm told be the junior's mentors that his code was more readable as well. (I didn't see his code, but I would tend to trust his mentor)

      The senior guy took 9 months to write it, and had several more years of maintenance. The new guy re-wrote it in 3 months. Now granted the features where stable for the new guy, but the old guy never refactored his code to something maintainable, and I count that against him.

    4. Re:Programmer XOR Musician by dooglio · · Score: 1

      There is something to be said for refactoring. The trouble I've experienced is that you seldom have time to. And hence, you wind up with spaghetti code that has grown almost unmanagable over time, even though the project may have started with a basic, good design.

  335. Why Tab Normalization Doesn't Work by coaxial · · Score: 1
    That doesn't solve the problem.

    Try this with tabstops at mod-8, align all the comments:
    int x = 3; // 4 spaced line tabbed comment
    int q = 4; // tabbed line spaced comment
    int y = 11; // tabbed line tabbed comment
    int q = 11; // 8 spaced line spaced comment
    int qq = 21; // 8 spaced line tabbed comment
    After your keystrokes, the
    int
    s are aligned, but now the comments aren't. All this does is move the misalignment to another column. That's not a valid solution.
    1. Re:Why Tab Normalization Doesn't Work by kiwibird · · Score: 1

      True, it is a problem if you don't give your comments their own line. Soo... looking on the bright side (or: following the style of the article mentioned here), it might make you comment better ;)

  336. I have a simple principle by gidds · · Score: 1
    ...but no-one's going to get to read it, coz it's been over 20 minutes since the story was posted. Ah well.

    Anyway, it's this: Make as much as possible obvious from the code itself. And comment everything else.

    It's not really about the volume of comments; it's about their content. You should usually be able to see the low-level of what the code is doing, and how; comments on that are not only superfluous, but their redundancy makes them actively dangerous when they don't get modified along with the code. What's usually much harder to see is the big picture: why it's doing it, and how that relates to the rest of the system.

    As a result, comments tend to be more important at the top of classes/methods/functions/procedures than in the nitty-gritty, because that's where the high-level info fits. Literate systems, especially JavaDoc, are good at encouraging that sort of comment, but there are no silver bullets: it's down to the developer thinking about the code, and (most importantly) thinking about the poor sod having to maintain it in a few years' time. I think you really need to have been in that position in order to fully appreciate what comments should be.

    --

    Ceterum censeo subscriptionem esse delendam.

  337. propaganda by Anonymous Coward · · Score: 0

    Actually, the French have a saying, "Never underestimate the bandwidth of a van full of backup snails."

  338. Future programmers? by HTH+NE1 · · Score: 1

    the thing that separates human-written code from computer-generated code is that our stuff is readable to future programmers

    Wouldn't that depend on who the future programmers are: men or machines?

    --
    Oh, say does that Star-Spangled Banner entwine / The myrtle of Venus with Bacchus's vine?
  339. Re:And this, my friends, is why offshore outsourci by MrBigInThePants · · Score: 1

    Thanks for the insightful mods, I guess public moderation suffers from "patriotic duty" amoung other things!? To the "flaming moderator": You can mod it down all you like, but it does not make it any less true!!

  340. Douglas Adams' ghost is going to kill me by Dogtanian · · Score: 1

    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.

    "But the designs were on display..."
    "On display? I eventually had to go down to the cellar to find them."
    "That's the display department."
    "With a flashlight."
    "Ah, well, the lights had probably gone."
    "So had the stairs."
    "But look, you found the notice, didn't you?"
    "Yes," said Arthur, "yes I did. They were on display on the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying 'Beware of the Leopard.'"

    --
    "Slashdot - News and Chat Sites Deviant". (Click "homepage" link above for details).
  341. Awful article. by Anonymous Coward · · Score: 0

    What an AWFUL article. As a maintainer of code I immediately read comments as though they were lies. The only useful comments are bug numbers or project identifiers so I can go look up the specification to match the pertinent code with the spec. Anything else is a junk comment. Heck, even the comments mentioning a bug number are lies.

    The part about the search routine? You don't need a comment for that. "Oh what's this code doing? It's clearly called blah_blah_heuristic_search so I freaking wonder. We clearly have another function lying around called binary_search (that's how we know this other search is quicker -we previously profiled it). Let's try the binary search. OH it profiles slower. Let's stick with the heuristic search."

    The article should be "Documentation is important". Comments are a last resort of a documentation strategy and Raskin even moves onto his real point in his conclusion. Why wasn't this his thesis?

  342. Five Simple Rules for Commenting Code by WillAffleckUW · · Score: 1

    1. KISS - and don't use acronyms like I just did.

    2. Whenever you're coding something ambiguous or tricky, always comment as to how and why - this saves time later.

    3. When declaring variables the first time, try to comment them and declare them in sections so it's obvious which are related - you can do this by naming conventions, but it's easier to read the comment.

    4. Never assume it's obvious - if it's a long calculation, comment as to what it does (or that you think it does), so when it breaks or is changed someone (or you) can figure it out.

    5. Don't use the number 5. You've made to many comments, so take a break and have a coffee.

    --
    -- Tigger warning: This post may contain tiggers! --
  343. Comments by MacWiz · · Score: 1

    If it was hard to write, it should be just as hard to figure out.

  344. Version Control Commit Messages by khanyisa · · Score: 1

    I think the best and most important way of commenting is through version control commit messages.

    That way, you attach the comment to the particular change you are making, and by looking at the history you can see exactly why certain lines of code are added.

    It also doesn't clutter up the actual code where unneccessary.

    And it doesn't have the problem that the code can change and make the comments wrong.

  345. 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;
    }

    1. Re:Uncommented potion code by Anonymous Coward · · Score: 0

      wtf??


      a = min(a,b);
      b = max(a,b);

  346. Re:There are 10 types of programmers by FuzzyBad-Mofo · · Score: 1

    If one doesn't understand binary, they are no programmer.. so I there's only one type. :)

  347. Optimal tab sizes and coding by CarpetShark · · Score: 1

    There have been studies done showing that 4 is the optimal tab size for code. I think it could be standardised easily, at least in coding standards like GNU's. Of course, with in-code settings like VI allows, or IDEs that save their settings in a project file, it's not so much of an issue anyway.

    1. Re:Optimal tab sizes and coding by coaxial · · Score: 1

      There have been studies done showing that 4 is the optimal tab size for code. I think it could be standardised easily, at least in coding standards like GNU's. Of course, with in-code settings like VI allows, or IDEs that save their settings in a project file, it's not so much of an issue anyway.

      Never worked in a large software house have you? Every group will have it's own standards, heaven help you if you have to look at another group's code.

      Anyway, tab should indent code to the proper level with spaces. Four spaces for a block. Two spaces for a continued line. (Which hasn't even been discussed here). After the initial indention, tab should then insert the tab character (0x09). When 0x09 is encountered, the cursor should be advanced to the next column that is divisible by 8.

    2. Re:Optimal tab sizes and coding by CarpetShark · · Score: 1
      Never worked in a large software house have you? Every group will have it's own standards, heaven help you if you have to look at another group's code.
      Actually, I look at different coding types all the time. Your tab specifications sound very arbitrary, so I'll agree to disagree on that. If you're basing those numbers on a study or something, though, I'd be interested to hear about it :)
  348. Re:I think you need a lesson in platform diversity by Retric · · Score: 1

    You can use code in OS2200 and still use cvs.

    How?

    Well if you have a network you can save your files to another system and use CVS from that system. Do all your coding in OS2200 and then run a script that copys everything. You should look at CVS as a backup of all your code. I mean you do back up your code to something off that system right?

  349. Re:I think you need a lesson in platform diversity by Richard+Steiner · · Score: 1

    You can use code in OS2200 and still use cvs.

    Perhaps. As I've said, though, the lack of such a source control system really hasn't been an issue with us.

    I mean you do back up your code to something off that system right?

    I don't make backups explicitly, no. The systems folks to automagic backups of all working files to tape at least once daily (active files are snapped two or three times), and there's at least one offsite backup of that information in addition to the local stuff on the tape silo here.

    This isn't a PC we're talking about, remember. :-)

    --
    Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
    The Theorem Theorem: If If, Then Then.
  350. Re:I think you need a lesson in platform diversity by Retric · · Score: 1

    Sorry, I was more referring to capability. I know some people that work on secured systems and are vary limited in how they can interact with other systems.

    Anyway, having worked on a lot of legacy code; being able to jump through CVS and look at when where and why code was changed becomes vary useful. Like a good IDE it's not needed but CVS makes you more productive over time. Even though it has other uses being able to diff you code right before bugs show up with the code right after the bug shows up is enough to save you the few hours it's going to take to set it up and the 3-4 min a day it takes to use. Yes you can do this by hand but in that case CVS is going to save you time right off the bat as you don't need to keep lhe {}{JNK 05/05/05 - updated to fix error 2715} style logs.