Slashdot Mirror


What is Well-Commented Code?

WannaBeGeekGirl queries: "What exactly is well-commented code anyway? Can anyone suggest resources with insight into writing better comments and making code more readable? After about six years in the software development industry I've seen my share of other people's code. I seem to spend a lot of time wishing the code had better (sometimes _any_) comments. The comments can be frustrating to me for different reasons: too vague, too specific, incoherent, pointing out the obvious while leaving the non-obvious to my imagination, or just plain incorrect. Poorly or mysteriously named variables and methods can be just as confusing. In a perfect world everyone would follow some sort of coding standards, and hopefully those standards would enforce useful comments. Until then, any suggestions for what you, as a programmer, consider to be good/useful/practical comments? Any suggestions for what to avoid? Also, I usually work with C++ so any resources/comments specific to that language would be too."

802 comments

  1. Variable Names by ludey · · Score: 1, Funny

    I sometimes get, uhh..."creative", before I program. End up with variable names like "$iHateThisProgram" and "$godFinWorkAlready"

    Anyone else experience this phenomenon?

    --
    --------------
    David O.
    1. Re:Variable Names by alpha1125 · · Score: 2, Insightful

      My variable names usually are forced into be changed after a code review by my peers...

      They don't have that funny bone, when the code is going to be in production software, and maintance by others.

      It's a professional image thing...

      --
      Money cannot buy happiness, but can buy something soo darn close, that you can't really tell the difference
    2. Re:Variable Names by gazbo · · Score: 4, Insightful
      I experience code from others who have this problem, and frankly it pisses me off. Not meaning to flame you, but what seems creative and amusing at the time stays in the source, and becomes stupid and annoying later.

      The same goes for 'amusing' comments in the code, or CVS logs.

      For your sake in the future, and your coworkers' sake now, please stop it.

      PS. Did I mention how fucking annoying it is?

    3. Re:Variable Names by NWT · · Score: 0

      Not quite... when I program, i just take the names that come to my mind. These are often $foo, $muh or just plain $data, sometimes $raw_data.

      But i think a clear code-structure is more important than variable names or detailed comments.

      --
      Life sucks.
    4. Re:Variable Names by emag · · Score: 5, Insightful

      On one of the last projects I worked on, the specs we received from the customer were horrendous. Actually, it wasn't the customer themselves who had done the specs, but another contracting firm. Spending 5 months on the project, and finding repeated errors in the "data maps" (it was apparently too bloody difficult for us to be supplied with a schema for the DBs we were supposed to be accessing and updating), I'd finally had enough.

      Querying the DBs directly showed that the data maps were works of pure fantasy in several spots, or would lead to outright data loss if followed precisely. In a fit of pure...creativity...I ended up setting a "$workAroundFuckups" variable, and in the sections where it was needed, had a false evaluation do precisely what thee datamaps said, which would corrupt data. If the variable was true (ie, non-zero), it would work correctly, which meant ignoring the data maps and doing what was needed to have the data be entered correctly.

      I ended up getting moved to another customer (due to the limited resources *we* had, not because of my creativity), so I don't know if the remaining folks on the project removed it after I left. When I added it, I explained to them precisely why I'd added it, and since they'd had similar experiences with what we were given to work with, were behind me 100%.

      This wasn't even the *only* part of the project which was FUBARed, but it was unfortunately what I spent many a 15+ hour day dealing with, so I was rather familiar with it. Had I access to the server that *read* the data and used it, I probably would have just gone in and redesigned everything "for free", just to avoid having to deal with such a horrible layout.

      This is also the client where, after a few months of an irksomely out of sync clock (off by 12 hours...made figuring out when something happened a bit of a PITA), I finally went in and set the damned clock to the proper time. Not surprisingly, the same folks who made that wonderful novel for us were the ones admining the dev server we were working on. AFAIK, no one ever noticed that the time suddenly became "correct" either.

      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
    5. Re:Variable Names by Anonymous Coward · · Score: 0

      But i think a clear code-structure is more important than variable names or detailed comments

      Its been my personal experience that variable names and/org detailed comments are AS important, if not MORE important than a clear code-structure. If there is not clear structure then if the code's commented at least it may be easier to determine what the original developer was trying to accomplish.

    6. Re:Variable Names by Iffy+Bonzoolie · · Score: 1

      I sometimes get, uhh..."creative", before I program. End up with variable names like "$iHateThisProgram" and "$godFinWorkAlready"

      Everyone once and a while, while implementing a hack I don't like, or a feature I disagree with, or something, my willpower will break down, and I am forced to name a variable or method with a name like stupidTwoPass[relevant part]Hack() instead of just the "relevant part" if, for example, I'm doing two iterations through a list instead of one, and I don't like the fact.

      Of course, at work we have a standard of using // HACK: IB - Doing extra iteration because [reason]-style comments when we do stuff like that.

      -If

      --
      Run a pencil-and-paper RPG campaign with your far-off friends: Gametable!
    7. Re:Variable Names by Anonymous Coward · · Score: 0

      What a dumb attitude! Variable names are half the comment. If you call something 'FileIsOpen' of 'foo' makes the code so much more readable. An if-statement will be near-English with proper variable names, whereas you and all the people after you will have to remember what 'foo' did this time.

      Gm.

      ps anonymous caward is nonsense, the registration does not work.

    8. Re:Variable Names by Grab · · Score: 5, Interesting

      Sometimes, from other ppl. If I see it, it goes right back in review, and I won't pass the review until the fuckwit responsible has removed them. If you're writing code for yourself, then fine, please yourself. If you're writing code that anyone else will see, *especially* the customer, then hell no.

      Thing is, there's two essential things that a reviewer/maintainer has to understand about a program: what it does; and why it does it. It should be possible to work out the first one of these just from the code, so long as the variables and functions are named sensibly. The second can be worked out from code with some effort, or the coder can add comments to explain why they're doing things that way and make it easier for maintainers.

      But if someone has deliberately given all the variables names which don't reflect what they do, then it's utterly impossible to work out what the code is doing, and it's therefore also impossible to work out why it's doing it. So the code is unmaintainable - it isn't possible for anyone else to pick it up and work out what it does, except with massive work. If in 6 months time your company says "oh, we've got this code we can use with slight modifications, let's quote 1 month to do this contract" and then they find out you've made the code utterly obscure, then they'll crash and burn. And if that happens, the company *will* fire (or at least formally discipline) the person who wrote the original code, bcos they've been grossly negligence in doing their job. And you can kiss goodbye to any reference from them, so you'll be SOL in finding your next job.

      Grab.

    9. Re:Variable Names by ColdGrits · · Score: 1

      Then I just hope I never EVER have the unplesant misfortune of having to maintain any code you write.

      With such stupid variable names, all you do is make the job harder for anyone else.

      Still, as long as it makes you happy, right?

      --
      People should not be afraid of their governments - Governments should be afraid of their people.
    10. Re:Variable Names by Dynedain · · Score: 2

      a guy at my work did that with filenames regarding projects (not coding)...the day he was out of the office and the boss was looking over a coworker's shoulder as they desperately pulled the stuff they needed....well...it wasn't a good day for him

      --
      I'm out of my mind right now, but feel free to leave a message.....
    11. Re:Variable Names by peddrenth · · Score: 2, Funny

      $StringPlusOne = $DollarDivideBy * $HashSemicolon + 8;

      print "$EndQuote Semicolon new line";

      getURL "http$Colon$Slash$SlashSlashDot${dot} org$slash";

      ...

    12. Re:Variable Names by Squashee · · Score: 2, Interesting
      Besides naming your variables meaningfully I have an additional suggestion. I allways (when applicable) add a prefix to my variables that identifies the type. Name then becomes sName.
      • s - String
      • i - Integer
      • f - Float
      • r - Reference
      • a - Array
      • etc...
      I know this does not work for everybody, but for me this has done wonders when it comes to understanding my own stuff a couple of months later.
      --
      When in doubt, act determined. Business 101
    13. Re:Variable Names by GigsVT · · Score: 2

      What happens when you recast it to something else?

      --
      I've had enough abrasive sigs. Kittens are cute and fuzzy.
    14. Re:Variable Names by Aqua+OS+X · · Score: 2

      hehe, if one was to view the source of a big web site that I made, they'd probably run into quite few JS variables with names like "ihateExplorer" or "ihateNavigatorfour"

      --
      "Things are more moderner than before- bigger, and yet smaller- it's computers-- San Dimas High School football RULES!"
    15. Re:Variable Names by Squashee · · Score: 1

      That's where the "if applicable" part kicks in. That basically means that "do not use this scheme if you know it wont work".

      --
      When in doubt, act determined. Business 101
    16. Re:Variable Names by badl · · Score: 0

      I find that over a few weeks I tend to write in little poems or sayings, what ever is on my mind at the time.... sometimes when i get pissed off i name my variables accordingly ( $fucken_work="xxx"; ). But despite all that this funny periods are struck down with serious or grumpy modes, which look upon such antics as childish, and i end up talking it all out to make it look strict, ordered, and sexy!. Even still comments don't do much for the absent minded. Hell I can write something and then next day when i look what i have done, I have no clue what the hell is happening.....

    17. Re:Variable Names by Darren+Winsper · · Score: 2

      One of my web sites uses a Javascript function called isCrappyBrowser(). It does exactly as the name implies, returns true if the user's using a crappy browser :)

      Of course, what is crappy browser is up for debate, but it's easy to add or remove browsers from the list.

    18. Re:Variable Names by Krapangor · · Score: 1
      • The type should be obvious from context and variablename automatically. If you have to prefix the name with arfc... to make the type clear, then you have a bad coding style.
      • Huangarian notation is evil.
      • Charles Simonyi is an anagram for Limises Yonarch, anyone with some occult knowledge know what this means.
      --
      Owner of a Mensa membership card.
    19. Re:Variable Names by Mr.+Slippery · · Score: 1
      I allways (when applicable) add a prefix to my variables that identifies the type.
      Hungarian notation is a bad idea. It's just too common for things to change type. "Oh, I need a pointer, not a reference, to work with that API." "We should use unsigned int for that, not int." "You should use a string, not a char *, for that." And so on.
      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    20. Re:Variable Names by Anonymous Coward · · Score: 2, Funny

      I've seen some of these in real world code, and they're not too annoying (unless you're trying to figure out what the code does :-).

      One of my favorites was a temporary function pointer named funcSoulBrotherInDaHouseNow. The same guy made a function named BashTheProcessor() with the comment //Shareef don't like it!. Another programmer named a miscellaneous callback YouWantFriesWithThat(). I was guilty of leaving around the comment // printf -- output function of kings for no reason whatsoever.

      None of these symbols are exported, so the world at large was spared until now.

      Staying anonymous to protect the identity of my coworkers. :-)

    21. Re:Variable Names by The_Systech · · Score: 1

      Bah, It was hard to write, it should be hard to read...

      --
      To err is human, but to really foul things up requires a computer
    22. Re:Variable Names by jeremyp · · Score: 3, Insightful

      There's a third thing the maintainer needs to know which is "what it's *supposed* to do. Comments are invaluable for that. Consider the following C code fragment:

      for (i = 1 ; i ARRAY_SIZE ; ++i)
      {
      do_something_to (array [i]) ;
      }

      Why isn't it doing something with element 0?
      Now look at these two fragments

      /* Do something to all elements in array */

      for (i = 1 ; i ARRAY_SIZE ; ++i)
      {
      do_something_to (array [i]) ;
      }

      and

      /* Do something to all elements in array except */
      /* the first one because... */

      for (i = 1 ; i ARRAY_SIZE ; ++i)
      {
      do_something_to (array [i]) ;
      }

      Just by adding a one line comment, a bug has been exposed, or the maintainer has been prevented from inserting a bug in the second instance.

      As a maintainer, I'd want to be able to see what the code does (well set out, good structure, descriptive names etc) and what the programmer meant it to do, i.e. good comments.

      Anybody who puts jokey unhelpful comments in their code should be aware that these will inspire feelings of hatred and extreme violence towards them in the maintainer who has two hours to fixe the air traffic control system before the 747s start falling out of the sky.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    23. Re:Variable Names by SecurityGuy · · Score: 3, Funny

      Bah, he was hard to work with, he was easy to terminate.

    24. Re:Variable Names by SurfTheWorld · · Score: 1

      Things to *not* do:
      - abbreviate variables
      - define all your variables at the top of a method
      - document how the method is doing what it does

      Why *not*?
      - abbreviate variables.
      This enables naming collisions. For example: AddressInformation ai and AssertionInclude ai. If a maintainer has recently been in the assertion portion of the application logic, and is dropped into the user component (and comes across ai), they may make a mistake

      - define your variables at the top of the method
      Defining (and instantiating) variables only before the blocks of code where they are required adds extra meta-information to those variables. Blindly defining them at the top can lead to situations where blocks of code are removed from a method, but variables are not removed because they are defined and instantiated many lines above the block of code that was removed.

      - define how the method is doing what it does
      A comment of "iterates over the array specified, and performs a binary search of the class member foo, checking for equality with any of the elements" is meaningless to me at an API level. "compares the provided array with the internal state returning true if they are equal" is much more meaningful

      Lots of luck to you on this. On my project it's really hard to get people to write good documentation. I don't know C++ very well at all, but a useful exercise for us Java programming folks (and maybe there is some analogy in the C++ realm that I'm not aware of) is looking at JavaDoc's first. If you are on a project with 500+ classes and you need to use an instance of some other class in the system, pull up it's JavaDoc information. Don't pull up the source. When you pull up the source, you tend to look at the actual code to figure out what the method does. If you look at the API you are evaluating the quality of the documentation. This leads to better documentation (because people realize the current documentation is inadequate) as well as a better developer knowledge. Treat your own internal API as an external library (like xerces). See how well the two stand up in terms of clarity and ambiguity. It's certainly the best lesson I've learned...

      --
      Do it for da shorties
    25. Re:Variable Names by voncheesebiscuit · · Score: 1

      Why *not*? - abbreviate variables. This enables naming collisions. For example: AddressInformation ai and AssertionInclude ai. If a maintainer has recently been in the assertion portion of the application logic, and is dropped into the user component (and comes across ai), they may make a mistake

      A better reason to not abbreviate...abbreviation leads to less readable code, any programmer that has to maintain your code later (yourself included), will have a much easier time figuring out what the code does if you use longer, more explicit variable names.


      - define your variables at the top of the method Defining (and instantiating) variables only before the blocks of code where they are required adds extra meta-information to those variables. Blindly defining them at the top can lead to situations where blocks of code are removed from a method, but variables are not removed because they are defined and instantiated many lines above the block of code that was removed.

      I'd prefer to see smaller functions/methods so that they do less. Instead of having blocks and blocks of code inside a function/method definition, break it into smaller, more atomic functions/methods.

    26. Re:Variable Names by Anonymous Coward · · Score: 0

      or, do this for even more clarity:
      // std::for_each, but not quite so constrained
      template<typename ForIt, typename UnaryFunc>
      UnaryFunc
      for_each(ForIt first, ForIt last, UnaryFunc f) {
      for( ; first != last; ++first)
      f(*first);
      return f;
      }

      // then...

      void doStuff() {
      vector<Thing> vt;
      // populate vt
      for_each(vt.begin(), vt.end(), twiddle);
      }

      consider using standard library algorithms to add more words instead of loops in your code. http://www.sgi.com/tech/stl has a good starting point.

    27. Re:Variable Names by Pig+Hogger · · Score: 2
      ...
      Spending 5 months on the project, and finding repeated errors in the "data maps" (it was apparently too bloody difficult for us to be supplied with a schema for the DBs we were supposed to be accessing and updating), I'd finally had enough.
      ...
      This is also the client where, after a few months of an irksomely out of sync clock (off by 12 hours...made figuring out when something happened a bit of a PITA), I finally went in and set the damned clock to the proper time.
      Lemme guess. Those clients were civil/mechanical engineers, right?
    28. Re:Variable Names by Paranoid · · Score: 2

      Actually, as a part-time sysadmin, most-time coder, I agree.

      The point of this whole thread is to understand what the code does, right? If your code is unclear, you can aid people in reading it through comments and variable names, but if your code structure is easy to understand, then the goal has already been achieved!

      Sure, it can be difficult to decide without bias how understandable your code is. Never overestimate the intelligence of the person who will maintain your code. However, to me, thats simply thats another argument for keeping your code structure clear to begin with.

      --
      Paranoid
      Bwaahahahahaa.
    29. Re:Variable Names by jdavidb · · Score: 2

      I do that too!

      • $ - scalar
      • @ - array
      • % - hash
      • & - function

      and so on. Oh, wait. :)

    30. Re:Variable Names by lazuli42 · · Score: 1
      See, stuff like this really makes me angry. We wonder why we spend millions of dollar on systems that ultimately fail? It's because of the 'not my problem' attitude that you're demonstrating here.

      If the database was such a big problem, why didn't you raise the warning bell about it? As you said though, you'd rather find your own workaround since the rest of the project isn't your responsibility.


      Sorry, I don't mean to vent at you specifically. It's just that our company got burned by some contractors that had the same attitudes. It took us months to figure out their logic and we ended up tossing half their work.

      --

      "There's companies that are just so cool that you just can't even deal with it," - Bill Gates, about Google

    31. Re:Variable Names by Anonymous Coward · · Score: 0
      Of course, at work we have a standard of using // HACK: IB - Doing extra iteration because [reason]-style comments when we do stuff like that.


      As long as you control the wording of your comments based on the fact that you have no control over who will eventually read them, they can be very useful. I remember one situation that I had to deal with. I commented several files explaining that under no circumstances should anyone use fd as a global. It seems that the database vendor had used that as a global variable in one of their libraries and hadn't made it static. To make life more interesting, it was not a file descriptor. It was an array of file descriptors. We were not amused.

    32. Re:Variable Names by Anonymous Coward · · Score: 0

      GROW UP!

    33. Re:Variable Names by Anonymous Coward · · Score: 0

      I do believe in meaningful variable names, but you can always recognize one of my COBOL programs by:

      IDENTIFICATION DIVISION.
      DATE-COMPILED. I HATE COBOL.

      (My comment is replaced by the current date in the listing, of course. It's a harmless tension-reducer.)

    34. Re:Variable Names by cyborch · · Score: 1

      ehh... a google search on Limises Yonarch did not produce a single hit, could you explain your reference to the rest of us ?

    35. Re:Variable Names by Anonymous Coward · · Score: 0

      Not really, if what you're talking about is mini-editorials expressed in variable names.

      I don't see anything wrong with a lighter touch though coming up with names that are descriptive. It could be said that good code tells a story, and that anyone at least somewhat familiar with the syntax should be able to read that story and know what is going on. Consequently, I don't have problem with an array of items to be deleted being named theDamned and the function to delete them being called toOblivion. toOblivion($theDamned) is pretty clear code I think without any comments.

    36. Re:Variable Names by Anonymous Coward · · Score: 0
      Do you use enough descriptive name and comments that the code is readable? I have nothing against jokes in the code, but you should not allow them to detract from the clarity of the code.

      Remember, code that is hard to debug and maintain is not clever.

    37. Re:Variable Names by edisk1353 · · Score: 1
      I'm in a Java programming class in a high school, and the person two computers down is a very heavy-set twit, and I don't know how he made it in. He's become reknowned in the class for his variable names, including:
      • bananaPancakes
      • nutPie
      • apple

      And the piece de resistance:
      • wang

      I repeat, this is a fairly heavy-set kid. Now we know his fixation.
    38. Re:Variable Names by Anonymous Coward · · Score: 0

      Perhaps emag did raise the warning bell. He never said he didn't. Whether the bell was heard by the costumer is controlled more by management than a programmer...

      On the other hand, if you give crappy specs to contractors expect back *very* crappy code. The only way to get even *decent* code out of contractors is with a fist of iron and specs of gold.

    39. Re:Variable Names by n9hmg · · Score: 1

      In the real world, there are political relationships which dictate that he write the code the way they told him to, and make it work. He succeeded on both counts, and left his variable behind so anyone examining the code would understand what it was for. I hope he left in a full narrative comment explaining it.
      I've been in his boat, and took your approach. I raised the warning bells, was told I was wrong, I escalated the issue until it was understood and fixed. This made a few people in power angry, and one day after being called in to be thanked for my good work and told what a valuable asset I was to the team, I was told that I wasn't fitting in to the way they work, and fired. Now I work for smart people.

      Do what your bosses tell you(customers are also bosses). Make their stupidest ideas look like gold. Document the necessary kludges (don't use the variablename "workAroundFuckups", but make it clear what it's for). Live long and prosper.

    40. Re:Variable Names by Anonymous Coward · · Score: 0

      I can't recall the last time a customer read some of my code...

      In my experience, there's a lot more process to software development then this. If programmers aren't given bounds and a framework things nearly always go to hell. Given a tight fitting smoothly running framework, even poor quality (or inexperienced) developers can write code that performs well and remains readable without much effort.

      If your company is giving out time quotes before anyone capable of doing the work in question has looked at the code and estimated by planning a course of action, I don't see how they can still be in business. Personally, I'd give a programmer such as the one in your example kudos for getting his/her project accepted in the first place!

      Blaming programmers for project failure or code difficult for others to maintain is just plain foolish. If you're going to blame programmers, blame them when they don't follow the rules laid down, or when they aren't getting enough work done relative to other programmers. If no rules are laid down, and all programmers seem "too slow", perhaps it's time to re-evaluate management.

    41. Re:Variable Names by __david__ · · Score: 1

      We used to joke about some people who coded for us because thay all abbreviated their variables in the most obnoxious manner. The standard seemed to be: drop the vowels of every variable, function, and file name. It was very difficult to deal with.

      For example: CntNmTrcks() ... How is that possibly better than CountNumberOfTracks()?

      This of course caused me to counter back with overly verbose variable names like:
      FixStupidWriteBugInSectorCountRegisterButOn lyOnTue sdaysFlag and such.

      Now my *FAVORITE* abbreviation was one that came back from a Japanese company that modified some of our code for production tests. They kept abbreviating "Count" by dropping just the "o". :-) I fell off my chair when I first saw it...

      -David

    42. Re:Variable Names by cmdr_beeftaco · · Score: 1

      I never found out if this is true. But a boss of mine once said we should never use comments that have the word "hack" or "bug" or "incomplete" because the comments could be used against you in a lawsuit. He said a software development shop was sued because of the comments in their code...

    43. Re:Variable Names by owenomalley · · Score: 1
      I used to work for a company that analyzed other companies' source code for problems. I was looking through the code and found some really insulting and offensive comments in the CVS repository. We aren't talking "Karl messed this up", but "Karl is a s*-headed m*-f*...". We also saw some comments of the form "this still doesn't work, but it is 4am so i'm going home."


      Ah, the joys of looking at other people's checkin comments.


      I strongly suggest that if you are tempted to put in such comments that you reconsider. CVS repositories live for a LONG time.

    44. Re:Variable Names by Iffy+Bonzoolie · · Score: 1

      [...] a boss of mine once said we should never use comments that have the word "hack" or "bug" or "incomplete" because the comments could be used against you in a lawsuit.

      Damn, I never even though of that. It's probably quite true. What a pain! I guess the solution is to come up with some code words for these things, like "PURPLE=HACK" and so on. Then we can say "Man, this code is PURPLE!"

      // PURPLE: Doing an extra iteration for now.

      -If

      --
      Run a pencil-and-paper RPG campaign with your far-off friends: Gametable!
    45. Re:Variable Names by woonjas · · Score: 1

      it can help but it tends to be a bit too restrictive.

      What if you end up needing another type? You're forced to go over the code and change all occurances of the variable or leave it as is and end up with a variable name that doesn't reflect the type.

    46. Re:Variable Names by woonjas · · Score: 1

      I have to agree here.

      stuff like that's ok for your home projects but have no place in professional projects.

      If you ever programmed in languages like assembly or Miranda, you probably appreciate the value of documented code (clear variable/function names etc.) but the use of any programming style/convention depends on one thing: DISCIPLINE.

      It takes a little discipline to teach yourself to document functions etc. especially when a function seems really obvious. My experience has taught me that in the long run you'll be doing yourself and others a favour. (sometimes small functions grow up to be monsters to bite you a year later when you need to apply some changes)

      if you describe the purpose of a function, what it should be doing and you use variable names that reflect their use, and add some comments for the less than obvious parts, it'll actually be possible to work with the code even a year later without having to go over every line of code.

      Good code is readable.

    47. Re:Variable Names by sister_snape · · Score: 1

      We don't need no stinkin' variables! Really, "modern" languages that make variable assignment and the checking and massaging of variable types a large percentage of the code are very seriously flawed to start with. In decent languages a much more functional approach would be taken. Of course then you have the problem of properly naming functions. Even in so called "modern" programming inanities, it is much, much more important to me to have classes, methods and functions have good readable names that tell me the one (only one, thanks) purpose the function is for rather than worrying much over variable names.

      In my not so humble opinion, being hung up on variable names shows just how backwards software engineering is in practice today. A well designed system is designed and decomposes according to classes, methods and functions not according to variables! In a well designed and implemented system, function/methods are generally short enough that the names of the variables are just not that important.

    48. Re:Variable Names by PepsiProgrammer · · Score: 2

      Exactly, my whole coding philosophy is to name my vairables and procedures so that the code reads as much like english as possible. If i do my job correctly my code should halfway comprehendable by people who dont even know wtf c/c++/java/insertlanguagehere is

      --
      "The United States has no right, no desire, and no intention to impose our form of government on anyone else." - Bush 05
    49. Re:Variable Names by Yakko · · Score: 1
      You're right... to a point.

      My private CVS repository, my rules, my code. If it ever gets more than my eyeballs, I can spend the time to clean it up. :o)

      (I have the distinct (dis?)advantage of not being a programmer by occupation, btw)

      --

      --
      Me spell chucker work grate. Need grandma chicken.
    50. Re:Variable Names by TimMann · · Score: 1

      Seems like getting fired by the stupid people was a good thing for you, if you're now working for smart people instead. So your advice to conform to the stupidity instead of pointing out the problems doesn't sound so good to me. In hindsight, would you really rather still be working for the folks who fired you instead of where you are today?

    51. Re:Variable Names by emag · · Score: 2

      Actually, they weren't. I can't quite say who they were, but you're about as far away as you can get from what they do...

      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
    52. Re:Variable Names by McPierce · · Score: 1

      Yes. In product code, the above would get you a written warning. Such things are unprofessional and would get flagged during code review.

      --
      Darryl L. Pierce "What do you care what people think, Mr. Feynman?"
    53. Re:Variable Names by Pig+Hogger · · Score: 2

      Fashion designers?

    54. Re:Variable Names by McPierce · · Score: 1

      We had, at my last job, some programmers we "adopted" when we "merged" with another company. During a project for our only customer, we were writing code in Javascript. The adopted programmers used variables names like "kyle", "stan", "cartman" and any temporary variable was named "kenny1", "kenny2", etc. They also used "evil.com" and "fuckshelbyville" and the like in the code.

      Needless to say, the CUSTOMER was always supposed to take ownership of the code after it was completed. Sure, the variable names were cute and funny at the time, but the customer saw that and adopted a whole new view on my company afterward.

      The programmers were released from their duties...

      --
      Darryl L. Pierce "What do you care what people think, Mr. Feynman?"
    55. Re:Variable Names by mustangsal66 · · Score: 2, Informative

      I once worked with a guy whos favorite variable and was asdf (Just roll your left hands fingers across the keyboard), and when he needed another he'd roll his fingers the other way(fdsa). It was maddening to debug. I find it useful to comment each section with what the code chunk expects in terms of data in, what it does with this data, then how and where it returns the data. I sometimes also note my thought process in writting the code this way. There are also times when I don't comment the code at all... especially if it's a chunk for an embedded box with limited storage. I do write docs for it, but they're stored elsewhere. -Just my $.02

      --
      Why worry? Each of us is wearing an unlicensed "nucular" accelerator on his back.
      Sig changed for readability by G.W.
    56. Re:Variable Names by Anonymous Coward · · Score: 0

      People like you do not think beyond what they are working on. You have to write code in a way that a convention does not break when there is a change in the future. Yea, Yea, I know that you can not see the future, but you can avoid a problem by thinking a bit about possibilities. I once had a boss that never thought that something different could happen; he would say "just do it, the spec is complete and will not change.". Well, the spec always changed and I always wanted to strangle the bastard for being a dick.

    57. Re:Variable Names by bakert · · Score: 1

      Well I think you can be forgiven that one as it is clearly available from first principles. Our intranet Look and Feel (both ASP and Java versions) contain a function IsCrapBrowser() or isCrapBrowser()

      --

      "Don't open the gates, who the hell needs a wooden horse that size?"

    58. Re:Variable Names by UnknownSoldier · · Score: 2

      I allways (when applicable) add a prefix to my variables that identifies the type. Name then becomes sName, etc. I know this does not work for everybody,

      Hehe, why are programmers so passionate about HN. Seems like coders tend to fall into 2 camps - they hate it, or they see the underlying merits, and use a modified version.

      Years ago I absolutely hated Hungarian Notation. IMHO it was far too meticulousness - you spent more time trying to keep your variables up to date, then coding! (Ok, it wasn't that bad, but close.)

      You can see how painfull raw HN is:

      Microsoft Hungarion Notation

      Does one *really* need to be that preverse about specifying the difference between byte, char, short, long, dword? Sheesh !

      (Notice how this pattern shows up when you take any good idea / methodolgy and become a "zealot" about it, but I digress.) Most of the time you don't need to split hairs over ints, floats, bools, chars, strings, etc. You're just making busy-work for yourself.

      That said, here's a heavily modified HN (namely a lot less restrictive) for C++ that I find extremely handy:

      • s static
      • g globals
      • _ member variables

      There are a few variations on this: Microsoft uses m_ (I don't care for this style, as this is too "wordy" IMHO), Some of the well know C++ gurus (forgot if it was Eckel or Meyers) use a trailing _ (again too easy to miss IMHO)

      • p pointers
      (s, g, _, p are always in this order)

      I find these to be a good compromise:

      • n for any number / int / float
      • i index / iterator
      • a array
      • r reference

      And since I'm dealing with so much 3D math I also use:

      • v vector
      • m matrix
      • q quaterions

      To keep track of what I'm converting to/from.

      ~ 2 ~ Having a standardized coding standard at work has been a Good Thing (TM) in the long run. I didn't like it at first, (habits and all :) but it's made working on other peoples code easier.

      ~ 3 ~ I can't stress this next tip enough: Use *descriptive* variables names.

      A descriptive name almost takes away the need for comments (almost ;-)

      i.e.

      If you iterating over a set, or range, say it !

      for( iCard = 0; iCard < nCards; iCard++ )

      ~ 4 ~ Use whitespace. Align the columns of your tables up. There is a reason tables exist - to make it easier to read.

      ~ 5 ~ If you have a function that does some complex calculation, document where you got the formula from.

      i.e. See Graphics Gems Volume N, Pages nn-nn

      ~ 6 ~ As you come up with ideas for how the block of code you're working on could be better, made more robust, effiecient, etc, put a comment: // TODO: rewrite so is cleaner

      This way you can do a search to see which parts of the code needs to rewritten.

      Cheers


      --

      "The issue today is the same as it has been throughout all history, whether man shall be allowed to govern himself or be ruled by a small elite."

      - Thomas Jefferson

    59. Re:Variable Names by Salamander · · Score: 2

      I don't think you need to be quite so anal about it. Comments or variable names that are uninformative are bad, whether they're intended to be funny or not. Comments or variable names that are informative are good, and making a dreary chore out of anything discourages people from doing it. I'll take good comments with bad humor over no comments at all any day.

      --
      Slashdot - News for Herds. Stuff that Splatters.
  2. Code Complete by kimba · · Score: 5, Informative

    I can absolutely recommend a book called Code Complete. Yes, it is published by Microsoft, but it is an invaluable language-agnostic guide to writing software that includes heavy doses of common sense regarding commenting, coding styles etc.

    1. Re:Code Complete by Anonymous Coward · · Score: 0

      I agree totally. Excellent book. It even has a list of how you explain to your boss why you should put in some effort in design.

      It also teaches you how to write selfdocumenting code and when it's necessary to explain things further in comments.

      Buy it today.

    2. Re:Code Complete by NewtonsLaw · · Score: 5, Insightful

      I can absolutely recommend a book called Code Complete [amazon.com]. Yes, it is published by Microsoft

      Yes, that's on my bookshelf -- but, given the fact that they go to great lengths to point out the importance of checking for buffer over/under-runs and fencepost errors, one can't help wondering if (in the wake of all those critical bugs in IE/Outlook/IIS) any of Microsoft's own programmers have read it.

      More "do as we say, not as we do" from Microsoft?

    3. Re:Code Complete by ZanshinWedge · · Score: 2

      I agree completely, it should be on every programmer's bookshelf. You can hardly call yourself a professional software engineer if you have not read this book.

    4. Re:Code Complete by jsse · · Score: 3, Funny

      Yes, it is published by Microsoft

      *Abruptly stops the finger from clicking the link*

    5. Re:Code Complete by c0dE+fReAk · · Score: 1

      I never thought I'd see the day that /.'s would actually recommend something, let alone, anything from Micro$oft! And oh yeah, I do have the book in my bookshelf. Awesome stuff, nonetheless...

    6. Re:Code Complete by Anonymous Coward · · Score: 1, Funny

      You can hardly call yourself a professional software engineer if you have not read this book.

      Since the people who wrote the book could not possibly have read it before they wrote it, then when they wrote it they had no right to call themselves professional software engineers. Why should I read a book that was not even written by professional software engineers?

    7. Re:Code Complete by Anonymous Coward · · Score: 0

      I can vouch for this - it's a great book. I've read it twice.

      It doesn't matter what language you use, this book is for you.

      Also, although it is published by Microsoft, it doesn't have any bias towards Microsoft languages or tools, in fact it doesn't much mention anything to do with Microsoft as far as I can recall.

      One of the best books on my bookshelf.

    8. Re:Code Complete by Anonymous Coward · · Score: 0

      Moderation rant. Please mark parent and this: (-1, Offtopic)

    9. Re:Code Complete by Anonymous Coward · · Score: 2, Insightful

      One of the most useful things he explains when it comes to comments is that, if you choose your function and variables names well, you shouldn't need many comments.

      e.g.

      // check to see if whatever is true

      if ( [complex bit of code] ) {
      do something;
      }

      This is much better written like this, without the comment:

      Whatever = [complex bit of code];

      if ( Whatever ) {
      do something;
      }

      He gives lots of examples like this, showing how to write your code so it doesn't need so many comments.

      Great book.

    10. Re:Code Complete by Anonymous Coward · · Score: 0

      does anyone see a stack overflow being caused here?

    11. Re:Code Complete by Anonymous Coward · · Score: 1, Insightful

      Good, zealots like you don't deserve quality books like this one anyway.

    12. Re:Code Complete by peddrenth · · Score: 1

      "Yes, it is published by Microsoft
      Abruptly stops the finger from clicking the link"


      Age of Empires is published by Microsoft, but I still play it. Tron is published by Disney, so unfortunately I can't play it. The slashdot boycott effect is such a random thing...

    13. Re:Code Complete by Anonymous Coward · · Score: 2, Funny

      They must have read it in the process of writing it; so they were not professionals before, but they were after. But my opinion doesn't count for much -- I haven't read it -- I can hardly call myself a professional software engineer.

    14. Re:Code Complete by Stephen+VanDahm · · Score: 1

      *Abruptly stops the finger from clicking the link*

      Don't worry -- books can't crash.

      Steve

    15. Re:Code Complete by ochinko · · Score: 1

      I had the book, read it a couple of times, but finally gave it away. Hungarian notation is bad for your code, period.

      ---
      I'd love to take you out tonight, honey, but I've got some /. comments to moderate...

    16. Re:Code Complete by plumby · · Score: 1

      Personally, I prefer

      if (whatever())
      {
      doSomething();
      }
      ------
      boolean whatever()
      {
      [complex bit of code];
      }

      This gives you a nicely separated block of code. But I do agree with the general point about sensible names being preferable to comments in most situations.

    17. Re:Code Complete by Anonymous Coward · · Score: 0

      I have the "bad" habit of naming my functions with almost complete sentences, it makes the code more readable, but it doesn't always explain WHY the functions does something, it only says that it does it, so comments are still needed

    18. Re:Code Complete by Mr.+Slippery · · Score: 1
      This gives you a nicely separated block of code.

      Which is useful if it that block is used many times, but otherwise it means someone reading the code has to jump around. Keep doing that and you make the reader bounce around between files like a ping-pong ball.

      Only separate blocks out if they cleanly abstract a concept.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    19. Re:Code Complete by Anonymous Coward · · Score: 0

      Anonymous Coward rant. Please mark parent and this: (-1, Offtopic)

    20. Re:Code Complete by BRSQUIRRL · · Score: 1


      Code Complete is fantastic (and has absolutely nothing to do with Microsoft, by the way, other than the fact that they currently publish it). In fact, new hires at our shop are required to read it before they write a single line of production code.

      Regarding comments, the author Steve McConnell would be quick to point out that the best comments are no comments...that good code should flow almost like English and therefore document itself. Comments should be reserved for the (hopefully rare) cases where, for one reason or another, this isn't possible.

    21. Re:Code Complete by Anonymous Coward · · Score: 0

      Have you relized that Steve C McConnell is not emplyee of M$.
      He is CEO and chief software engineer at Construx Software.
      He is also Editor in Chief of
      IEEE Software magazine

    22. Re:Code Complete by broody · · Score: 1

      Kimba is spot on.

      Code Complete also goes over layout and style, the other two pillars of readable code. Check out the link in the previous sentance, it is to the author's site which includes sample chapters, the table of contents, and a link to deal pilot where you can help the author by giving him the referal commission and get the book on the cheap.

      --
      ~~ What's stopping you?
    23. Re:Code Complete by arkanes · · Score: 2

      Microsoft Press also publishes a magnificent book called "Writing Secure Code". Interestingly, the guys who write it (MS engineers) talk alot about how hard it is to force secure coding onto co-workers who don't give a shit.

    24. Re:Code Complete by plumby · · Score: 1

      I suppose it depends on what language you use, but for most of the ones I've worked on this doesn't involve bouncing around bewteen files. The function would live in the same class/module as the calling function.

      As for your last line, that is exactly what it is doing. Your 'if' statement, and whole function that you are working on, is wanting to know whether the particular thing is true or false, not how it came to that conclusion. By moving it to a separate function, you are specifically abstracting out the concept of how that decision was reached. If it's a complex decision, then it should be abstracted to a separate place to hide that complexity.

    25. Re:Code Complete by SecurityGuy · · Score: 2

      Steve McConnell doesn't work for Microsoft. He's worked for them in a contracting role, and has also written a highly insightful piece which explains a heck of a lot about why Microsoft is so hopeless, although he may not have intended it to carry that meaning. Basically, a high premium is placed on making the developer happy. Creeping featurism isn't seen as a problem. Of course you can figure this out by using any of their products as well.

    26. Re:Code Complete by Tower · · Score: 1

      And, as with the previous example, your enviornment may make a difference in how you do that... in an embedded env, you may have code space concerns, or if you are in the performance path, you may need to clutter the if, and completely avoid any function calls (or inline and be good with registers as appropriate)...

      Coding style in those cases can be somewhat dictated by the requirements - if you are writing part of a GUI dialog box, and you expect to run on a GHz+ system, a few extra function calls won't hurt... on the other hand, a DMA function driver for a gigabit ethernet card or SCSI/160 adapter might want to avoid all path length possible.

      --
      "It's tough to be bilingual when you get hit in the head."
    27. Re:Code Complete by juliao · · Score: 2
      From the people who gave us Hungarian notation?

      Learning coding styles from Microsoft is like getting cooking tips from McDonalds...

    28. Re:Code Complete by Anonymous Coward · · Score: 0

      I couldn't agree more: well designed and written code needs few comments -- they should only be necessary when something non-obvious is going on.

      If you want to know what the inputs and outputs of a function are, you should be able to tell just from the signature, which contains variable types and names. If you want to know what a local variable does the same thing applies.

      Similarly, object methods and functions should have functionality that is well described by their names. Ideally, code should read kind of like strangely formatted English.

      Consider for example the following self-explanatory python code:

      for stream in streams:
      if stream.is_dead:
      stream.resurrect
      The question that remains in the reader's mind is what does it mean for a stream to be dead and how do you resurrect it? That should be explained at the definition of the two methods in question. Everything else is clear from the code itself.
    29. Re:Code Complete by Ooblek · · Score: 2

      Comments in code? The poster must not be a Jedi, for real Jedi do not need comments. They can feel the purpose of the code.

    30. Re:Code Complete by Anonymous Coward · · Score: 0

      You're a professional spaz.

    31. Re:Code Complete by Mr.+Slippery · · Score: 1
      ...doesn't involve bouncing around bewteen files...
      Well, excessive bouncing around within one file is bad enough. :-). But I was recalling one C project where the (poor, IMHO) code control practice dictated one function per file. Ugh.
      If it's a complex decision, then it should be abstracted to a separate place to hide that complexity.

      Agreed, so long as in the place where you're calling it's clear in the abstract what the decision is. I.e.

      if (condition(x)) {
      ...
      }
      versus
      if (is_valid_id(x)) {
      ...
      }

      Don't just move it, abstract it. I think we agree, just wanted to bring that out.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    32. Re:Code Complete by lostguy · · Score: 1

      Anyone who hasn't read that book by now has no interest in producing decent code. :-)

    33. Re:Code Complete by plumby · · Score: 1

      For some very specific areas there may be a good reason to avoid extra function calls, but for almost all areas I've ever worked in, any extra overhead of the function call is almost totally irrelevant.

      I almost always start with writing code in the most readable way that I can, and then if there's a performance issue, analyse the code and optimise later. I've forgotten where I first read it, but I agree entirely with the statement It's a lot easier to optimise tidy code than to tidy up optimised code.

    34. Re:Code Complete by Anonymous Coward · · Score: 0

      The problem with saying things like "the best comments are no comments..." is that poor coders stop listening at this point, thinking "wowee, I don't have to sweat over comments anymore!" The resulting code has no comments *and* no visible logic, which is the worst of all.

    35. Re:Code Complete by atstardot · · Score: 1

      I can recommend a book called Java Structures.

      It is written by Duane A. Bailey. Mainly it is about structures, but Bailey has some interesting ideas about pre and post conditions; very important when commenting your code.

    36. Re:Code Complete by Tower · · Score: 1

      I agree - function first (with nice form), then speed up as necessary is not a bad way to go... I have personally been involved in situations where an extra function call and a few (5-10) extra load instructions has had a rather detrimental effect on system performance in specific cases. Obviously this is somewhat specific to embedded systems (though a reasonably fast PowerPC chip), but creating extra latency and reducing throughput for certain paths can really get some people angry, even if it is only a few percent :)

      --
      "It's tough to be bilingual when you get hit in the head."
    37. Re:Code Complete by fscking_coward_2001 · · Score: 1

      Have you read the book? It's not a style guide for programmers. Coding styles are language-specific. Coding practices are more global, applicable to good programming regardless of the language chosen. Refusing to read this excellent book because you don't like a variable naming style is extremely short-sighted.

    38. Re:Code Complete by Misha · · Score: 2

      Yes it sucks. This is straight from one of many Microsoft's HN intros, which I assume Code Complete also contains.

      In conclusion, the name of our quantity would be coRed, provided that the color type co is properly documented. The value of the name will show later in program segments such as the following:

      if co == coRed then *mpcopx[coRed]+=dx ...



      is that as unreadable to you as it is to me? the only thing i can extract from it is that i should read the documentation for the type co, rather than find out what this line does. sure, my dyslexia is not helping, but they could have done much better.

      yes, outlawing turing machines would be bad, but it's not like you have one sitting on you desk, do you? ; )

      --



      I was thinking of how to intentionally fail my drug test... It would make a good memoir story someday.
    39. Re:Code Complete by 56ker · · Score: 1, Flamebait

      "Microsoft Press also publishes a magnificent book called "Writing Secure Code""
      Oh the irony of it all - I suppose the second in the series is entitled "Writing a Secure OS" or "Writing an OS for Dummies"

    40. Re:Code Complete by Anonymous Coward · · Score: 0

      I have to disagree with you, but not because of any complaints about the book itself. When I read it, I was impressed that it summarized so many of the things that I learned getting a good CS degree and a decade of experience. For anyone without a CS background or with less experience, your choice is Code Complete or several other books. You will learn more from the other books in the long run, but it will take more time. I recommend both approaches with Code Complete being the first.

    41. Re:Code Complete by Anonymous Coward · · Score: 0

      determining the value of information from the
      source of the information is absurd. the
      information should be evaluated on its own
      merits. even trolls/anonymous cowards say deeply
      insightful things from time to time.

    42. Re:Code Complete by sydb · · Score: 2

      Or perhaps "Ethics in Software" by Bill G.

      --
      Yours Sincerely, Michael.
    43. Re:Code Complete by circusboy · · Score: 1

      curiously I worked for a company recently where all the programmers were "recommended" into reading one of these microsoft coding guides. ("writing solid code" I think it was.)

      Oddly the company went under shortly afterwards.

      This, of course, may only be a coincidence

      --
      -- it's ridiculous how many people misspell ridiculous... (damn, damn, damn...)
    44. Re:Code Complete by circusboy · · Score: 1

      Of course, depending on how you look at it it could just mean that it came too late.

      --
      -- it's ridiculous how many people misspell ridiculous... (damn, damn, damn...)
  3. Make the variable names mean something! by dweezle · · Score: 2

    I Have to scan through code regularily and the biggest problem is the variable names. I realize that they must mean something to the coder but to us maintainers they're most times akin to Sanskrit. Function(method) comments are nice too.

    --
    In a time of universal lies, Telling the Truth is a revolutionary act - George Orwell
    1. Re:Make the variable names mean something! by jilles · · Score: 2

      Yes I would have to second that. In addition, it also helps to trust the compiler a bit more to do the inlining. If a method has more than a screen full of code (i.e. about 20 lines), split the method into multiple methods. This has two advantages: you give a name to a piece of related code (abstraction) and you may be able to reuse the function. A good compiler will inline so there's no performance penalty.

      Similarly if your module/class whatever becomes too large it will be more difficult to maintain. Usually large modules/classes are a clear indication of lack of cohesiveness which is bad for maintainability.

      Another thing that can be extremely helpfull are pretty printers (the beautifier that comes with JEdit is great, automatically does its job whenever you save). Good ones also generate the necessary Javadoc stubs (if you're coding Java) thus lowering the burden of creating meaningfull comments (javadoc like tools exist for C++ too!). In addition pretty printers give your code a uniform structure, making it easier to browse.

      Enforcing all this requires code reviews. Most larger software organizations with competent software developers in charge will insist on this already.

      --

      Jilles
    2. Re:Make the variable names mean something! by Mr.+Slippery · · Score: 5, Informative
      If a method has more than a screen full of code (i.e. about 20 lines), split the method into multiple methods

      I strongly disagree. The proper delineation of a function or method is the operation that it abstracts, not how long it is.

      If a subroutine is only called once, and doesn't cleanly abstract some idea (i.e., if you can't tell me what it does in one simple sentance), it should not be in a separate subroutine.

      I've seen too much code written in the manner you suggest, that makes the reader bounce around from function to function to function for no reason other than "otherwise that function would be more than 30 lines".

      void foo()
      {
      foo_part_1();
      foo_part_2();
      foo_part_3();
      }

      If I have to maintain such code I always refactor it into one subroutine.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    3. Re:Make the variable names mean something! by jilles · · Score: 2

      I've never seen a method over 20 lines that really needed to be that long. Long methods are usually the result of poor design. If you have to maintain such methods, you lose a great deal of time figuring out what they do. Because they are so long, the method name is not a great help in figuring out what it's supposed to do.

      --

      Jilles
    4. Re:Make the variable names mean something! by spudnic · · Score: 2

      From your last couple of comments it seems evident that you need to become acquainted with the use of CTRL-] in vim to do all the jumping around for you. ;)

      .

      --
      load "linux",8,1
    5. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      You don't understand the concept. Go read Martin Fowler's Refactoring (Extract Method in particular). You don't break up code by line numbers, you do it by what the code does -- and you insure that all method names are meaningful. It really isn't as hard as you think. Would you please post a long method that you believe can't be refactored?

    6. Re:Make the variable names mean something! by FyRE666 · · Score: 1

      I totally agree. In fact I never create a new function/method if it's only going to be called from one statement. Not only is it frustrating to have to scroll around (or even hop between separate source files) but it's hardly efficient. I've seen functions broken up like this where a subfunction is called within a loop, which demonstrably sucks CPU cycles (pushing and popping registers over and over again is no way to optimise).

    7. Re:Make the variable names mean something! by Fulcrum+of+Evil · · Score: 2

      I've never seen a method over 20 lines that really needed to be that long.

      I've got one right now that's 20 lines, just for the setup and return. The meat should be another 20 lines or so. Of course, this is parsing a free-form text field.

      --
      "We returned the General to El Salvador, or maybe Guatemala, it's difficult to tell from 10,000 feet"
    8. Re:Make the variable names mean something! by am+2k · · Score: 1
      Would you please post a long method that you believe can't be refactored?


      I got one, which became pretty long over time. It creates new PPP configurations and looks like this (pseudo-code):

      function() {
      array allconfigs=getAllConfigs();

      while(gotMoreConfigs) {
      hash newconfiguration;
      bytes password;

      newconfiguration.set(
      username=thisConfig.username);
      password=scramble(thisConfig.password);
      newconfiguration.set(password=password);
      newconfiguration.set(telephone=thisConfig.telephon e);
      // etc etc etc

      allconfigs.add(newconfiguration);
      }

      storeConfigurations(allconfigs);
      }

      It's all linear and around 2 or 3 pages long.

    9. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      >>I strongly disagree. The proper delineation of >>a function or method is the operation that it >>abstracts, not how long it is.

      You are partially correct - the example you provide is referred to by McConnell as "fan-out" and should be avoided.

      However that is a pathological example - notice how the responsibility (think CRC here) of method foo is not clear whatsoever; in fact is primarily a "controller".

      Have you ever heard of the McCabe complexity metric? One of its measures of complexity is the length of the function. If you read Code Complete you will find cites to studies at places like JPL, TRW and NASA which clearly show that programmer comprehension as well as bug rates are dramatically reduced when keeping all method lengths within the complexity metric.

      There are other far less extreme ways to refactor long methods while still keeping the responsibility of the original method intact (or perhaps the original method never HAD a clear Responsibility?)

      Later,
      Wade

    10. Re:Make the variable names mean something! by Anomaly+Coward · · Score: 0

      Ha! You just proved his point by refactoring your own code to less than 20 lines. And that code actually makes sense.

    11. Re:Make the variable names mean something! by Mr.+Slippery · · Score: 1
      I've never seen a method over 20 lines that really needed to be that long.

      The question is not how long does it need to be - you could make every line of code a method of its own, or put everything in main(). The question is what division of methods best encapsulates the operations that are happening.

      Long methods are usually the result of poor design.

      I would say that too many methods which are only invoked at one place are usually the result of poor design.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    12. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      I know the McCabe metric is evolving but last I read it did not take into account length of the code.

      I quick search through google didn't resolve the issue.

      Anyone know where I can get the up to date standard for the McCabe metric?

    13. Re:Make the variable names mean something! by SteelX · · Score: 2

      Doesn't that depend on the language being used?

    14. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      Have your ever heard about inline?

    15. Re:Make the variable names mean something! by Mr.+Slippery · · Score: 1
      you need to become acquainted with the use of CTRL-] in vim...

      Being an emacs guy, I have no idea what that is. :-) (Some sort of tag facility?) But I know it won't help me at all when looking are hardcopy.

      Yes, hardcopy. Still one of the best methods of reviewing code; print it out, get a big conference table all to yourself, a pencil, and spread that sucker out. I always do this with code I've just taken over, and with code I've finished writing.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    16. Re:Make the variable names mean something! by Mr.+Slippery · · Score: 1
      However that is a pathological example

      Yes. But I've seen it "in the wild".

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    17. Re:Make the variable names mean something! by Anonymous Coward · · Score: 1, Insightful

      The whole point is that you don't have to keep scrolling around. You see the call to getSubtotal() and you know it just adds up all the numbers without having to see the code.

    18. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      The code is bad enough that it isn't obvious what it is doing (unless you are intentionally doing things in an illogical way), but here are some comments.

      It looks like you're just copying a map with a few twists (like scrambling the password). Are you using a language in which map's cannot simply be copied? You can apply any weird changes directly to the copy afterwards. copyConfig() should be separated out so that the loop simply calls it and adds the result to allconfigs. What is the function called anyway, addCopyStoreAllConfigs()? It seems to be doing way too much.

    19. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      You are right - I was (mis) speaking of the S.L.O.C. (Source Lines Of Code) metric which commonly accompanies the complexity metric.

      It is worth pointing out that most times cyclomatic complexity and S.L.O.C. are in direct correlation with one another - but obviously not in the case of the pathological foo routine...

      Here's a Decent Link for Cyclomatic formula:
      spec
      Later,
      Wade

    20. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0
      I realize that they must mean something to the coder but to us maintainers they're most times akin to Sanskrit

      Actually, you may be too kind in some cases. I've noticed that badly named variables can imply that the original programmer didn't fully understand the problem, and therefore didn't even know enough to assign a useful, descriptive variable name. So really, the names might not have meant anything to the original guys :)

    21. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      So if I can write my perl interpreter in one function, I should? I thought the point of functions was to break up a larger task into simple, smaller subtasks. If you refer to Strunk and White's classic Elements of Style, you'll notice a recommendation that large paragraphs be broken into more managable ones -- even if they really seem like one topic. It's a question of understandable and readable code, and long methods are usually as annoying to read as long paragraphs and sentances.

    22. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      That line "// etc etc etc" might need a bit of fleshing out in the real code...

    23. Re:Make the variable names mean something! by Anonymous Coward · · Score: 0

      Well, I ran across another problem - I have such a function (linear, no cycles) that serves 2 purposes and has about 150 lines of code. If I decided to write 2 functions instead of this one, I would have 2 functions, every with 110 lines of code, about 80 percent duplicate. The worst thing is that it is written in Python, and so it has same functionality as 400 lines of code in C. I hate this function and I really do not know how to refactor it.... Any siggestions?

    24. Re:Make the variable names mean something! by ebyrob · · Score: 2

      Having trouble reading your code? It's probably a better idea to break your code up into functions that are likely to be useful in more than one place. Instead of just breaking them up because they are too long.

      If this doesn't seem to work for you, I'd have to see some specific examples...

    25. Re:Make the variable names mean something! by ebyrob · · Score: 2

      I wholeheartedly agree! Having to dredge through a few difficult functions doesn't take that much time. By contrast, trying to figure out what 50,000 functions do in a million line program can drive a developer (or maintainer) insane! Especially if only 10,000 functions do anything useful.

      That said, every rule needs some limits. I've also waded through functions that required 4 source files (due to 32k compiler limits) and been ready to commit great voilence afterwards.

      I find that combining your rule of functions matching abstractions with an effort to reduce total code size works the best for me. My guiding princible is this: "Will the next person to see this line of code, program, etc be glad it exists, or wish it didn't."

    26. Re:Make the variable names mean something! by Pinky · · Score: 1

      easy:

      function() {
      array allconfigs=getAllConfigs();

      while(gotMoreConfigs) {
      addConfig(...);
      }

      storeConfigurations(allconfigs);
      }

      Wow.. that suddenly got readable too.

      Granted you still have a funciton that doesa a whoile load of things but that is now nicely contained in a factiont that makes sence!!!!!!!!!!

      Even better would be some sort of OO way of coding it like:

      ConfigCollection::addConfigs(array allconfigs) {
      while(gotMoreConfigs) {
      addConfig(...);//part of config
      ///collection
      }
      //add config does what is needed
      //to store the config.
      }

      YOU can split this thing up into seral funciton not bigger then a few lines, expect the function that does the adding garbage.. and even that can probably be broken up since it loks like misc things arebieng added to misc objects and such a thing should probably never happen.. of course this all depends on specifics...

    27. Re:Make the variable names mean something! by am+2k · · Score: 1
      Granted you still have a funciton that doesa a whoile load of things.

      Right, and that's exactly the problem. Removing the while-loop removes only a small percentage of the whole function. The real problem are those 20 settings, with about three lines per key.

      Oh, and it uses Apple's CoreFoundation, so there's no need for "real" OOP.

  4. Describe before you apply by inflex · · Score: 3, Funny
    I like to see comments where the function of the next code block is well described in a continuous comment block. Additionally, any further specific comments can be placed at the end, or on top of the lines in question. It's simple enough, and permits comment/documenting-scrapers to produce some potentially useful documentation.


    ie,
    // Foo():infinite loop
    // We attempt to complete an infinite loop
    // here as quickly as possible, in order to
    // remain true to Linus's statements of
    // being able to do them faster with linux.
    while (1) {
    ... // Oooh, this is a fancy line, watch out for it doing nothing.
    }

    1. Re:Describe before you apply by ranulf · · Score: 2, Interesting
      The problem with this is that
      while (1) {...}
      or more commonly
      for (;;) {...}
      is a well known construct for infinite loop. If you turn such a simple construct into six lines of source, then I dread to think how much commenting you'll use when you actually get down to solving the problem in hand.

      for (;;) { // infinite loop
      is far better - it reminds people what you're doing and if someone sees your code and doesn't understand that construct then they know what it does from the comment and they can go and find out how it works and learn it for next time.

      While you're at it, you should probably think about hiring real programmers who know basic constructs in their chosen language...

    2. Re:Describe before you apply by spongman · · Score: 3, Interesting
      how about while (true) { ?

      1) It reads right in english.
      2) It's type-safe in C++ for -Wall.
      3) It doesn't use antequated or obfuscated C-isms.

      I can't stand things like:
      #define ever ;;
      ...
      for (ever) {

    3. Re:Describe before you apply by peddrenth · · Score: 2

      while(true) { can be especially useful in an program you're hoping to secure the maintenance contract on...

      ... right after you've redefined true.

    4. Re:Describe before you apply by Permission+Denied · · Score: 2
      #define ever ;;
      ...
      for (ever) {

      This is nasty because the programmer is trying to be cute with the macro. However, if you see this:

      for (;;) {

      And it pisses you off, that means you haven't seen enough of other people's code yet. This is perfectly idiomatic and it reads as "for ever." Don't try to invent new idioms, or apply Pascal and Java idioms to C and C++. If someone prefers "for (;;)" that's purely a stylistic decision, and it's a valid stylistic decision since a lot of C and C++ programmers do that.

      Real code shouldn't look like pseudocode: it should be idiomatic and idiomatic C++ looks nothing like pseudocode. Consider, for instance, looping over an STL collection using an iterator: that looks nothing like pseudocode (where you would just say "for each x in y" or something similar), but it should be perfectly recognizable to any C programmer (eg, you can recognize it as a for-each with a glance, without stopping and thinking - important cognitive distinction).

      Summary:
      C:

      for (;;) {
      or
      while (1) {
      In C++, you can also use:
      while (true) {
      But you should never use "while (true)" in C because a given project might use boolean types defined by six different APIs (all incompatible - so just use an int instead).

      All three of the above are in common use in C++ and getting pissed whenever you see one of them indicates a lack of the "interpersonal skills" managers are always talking about.

    5. Re:Describe before you apply by Permission+Denied · · Score: 1
      looping over an STL collection using an iterator ... should be perfectly recognizable to any C programmer

      Of course, I meant "C++ programmer" here. This is to stave off the trolls.

  5. Microsoft Press by ObviousGuy · · Score: 2

    Code Complete by Steve McConnell

    Writing Solid Code by Steve Maguire

    --
    I have been pwned because my /. password was too easy to guess.
    1. Re:Microsoft Press by Frogg · · Score: 1

      Whilst I (and lots of other posters) agree that Code Complete is a great book, I personally think that Writing Solid Code is simply not on the same level. In short, if I had to recommend one of these books over the other, Code Complete would win hands down - it's a book I've gone back to time and time again, whereas Writing Solid Code has been sat on my shelf collecting dust for a while now. Not that it's a bad book, it's just not as good as Code Complete.

      Just my humble opinion....
    2. Re:Microsoft Press by Anonymous Coward · · Score: 0

      Quite Frankly, when microsoft produces "complete" and "Solid" code (that happens to be bug free) then I *might* buy these books.

      Any company that is foolish enough to place "bug-Free" as any part of a title/sub-title of a book is obviously does not understand the complexity of writing software.

      When microsoft *PROVES* that they are producing "Bug-Free C Programs", Now there is a book worthy of buying.

  6. Comments are evil. by slumpie · · Score: 0, Flamebait

    The best comment is the code.

    1. Re: Comments are evil. by dorward · · Score: 2, Funny

      The best comment is the code.

      Unless the code is Perl ;)

    2. Re:Comments are evil. by ggeens · · Score: 1

      The best comment is the code.

      Actually, it is the worst comment.

      Most code tends to include a lot of error handling stuff. In C, you can end up with more than half of your code devoted to error handling. (C++ and Java are better, because of exceptions.)

      If you read such a program, you'll have a hard time figuring out what it does in the general (non-error) case.

      --
      WWTTD?
    3. Re:Comments are evil. by Iffy+Bonzoolie · · Score: 1

      The best comment is the code.

      For a really good resource on why this is, and how to make your code actually live up this ambitious declaration, check out Refactoring by Martin Fowler. Most of the comments I write are about things that have some external significance... hacks, basically. :|

      While this idea about this book is to improve the design of existing code, it's somewhat nontrivial to apply in practice on some nasty, tangled, obtuse code that tries to do too much. Rather more trivially, it makes new code that I write, and then the maintainance of that code, much better.

      -If

      PS: I've found both Refactoring and Analysis Patterns by Fowler to be well-written and insightful. Substantially less dry than works by his counterparts (Kent Beck, Gang of Four, etc).

      --
      Run a pencil-and-paper RPG campaign with your far-off friends: Gametable!
    4. Re:Comments are evil. by bullgod · · Score: 1

      The best comments tell the reader why the code behaves as it does. This is something the bare code can never tell you.

      Code will tell me that i is incremented.
      It will not tell me what i represents, why it's done here or what will happen if i were not incremented.

    5. Re:Comments are evil. by Anonymous Coward · · Score: 0

      Actually, if your variables and functions names are meaningful you DON't NEED Comments. And you should have unit tests that presents the features of the code... like a sort of binary and executable spec... read Tests first on the wiki

    6. Re:Comments are evil. by Anonymous+Brave+Guy · · Score: 3, Insightful
      Actually, if your variables and functions names are meaningful you DON't NEED Comments.

      Sorry, but that's just not true.

      You need fewer comments if your identifiers are well-chosen, certainly. But I've never seen a significant piece of code that would be adequately described by well-chosen identifiers alone.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    7. Re:Comments are evil. by Anonymous Coward · · Score: 0
      meaningful... you mean like
      long currentTimeDecrementedByOneHourIfWeAreCurrentlyInD ayLightSavingTimeOrNotDecrementedOtherwiseBecauseW eNeedTheTimeInAFormatThatIsIndependentOfTheBarbari cTraditionOfDayLightSaving;
      ?
      this would be much more easier to read:
      // current time, decremented by one hour
      // if we are currently in daylight saving time
      // (we need to make abstraction of daylight
      // saving, some parts of the world don't use it
      // at all)
      long adjustedTime;
    8. Re:Comments are evil. by SecurityGuy · · Score: 2
      There is no good resource on why it is, because it isn't. :P


      I say this for one simple reason. The code tells me what you actually did. It doesn't tell me what you intended to do. Auditing someone elses code is a royal PITA when they haven't bothered to tell you what a function is supposed to be doing.

    9. Re:Comments are evil. by Anonymous Coward · · Score: 0

      I think your example is a good example, but you picked a horribly named variable just to prove your point. I think it's hilarious that people throw stones at this concept of self documenting code, without being familiar with how to do it correctly.

      If I ran into this piece of code, I would probably approach it a bit differently then trying to cram that entire comment into the variable name. Apparently the idea is to get a time that is calculated ignoring daylight savings time. So..

      public void doSomething(){
      long time = calculateAdjustedTime();
      //Do whatever you want with the adjusted time
      //here
      }

      private long calculateAdjustedTime(){
      long adjustedTime = currentTime();

      if(isInDaylightSavingsTime()){
      adjustedTime -= 1;
      }

      return adjustedTime;
      }

      I think this would be a bit cleaner then what you suggested. Of course, there are other approaches, but my point was that if you want to throw stones, at least use a realistic example. Exaggeration doesn't help prove your point.

      Now, I didn't address the part where you comment that the whole world isn't on daylight savings. First, the question is, does that HAVE to go in the documentation. If not, then simply documenting that you DO correct for being within daylight savings may be enough. If it does have to go in, then a small comment may be enough. A line above the if statement that is short, sweet and to the point.

      //The whole world is NOT on daylight savings.

      Hope this helps.
      RTF

    10. Re:Comments are evil. by Iffy+Bonzoolie · · Score: 1

      Well, one of the ideas behind Refactoring is that the code should be self-documenting. i.e. function names should convey the purpose of the function, and variable names should convey the purpose of the variable. If you cannot represent a function's purpose in the name, then your function is doing too much, and you should apply Extract Method.

      Of course in the real world this is not always practically applicible, but it covers the trivial 70% of code that really doesn't need documentation. What it does it minimize the need for comments, which often make it harder to read code.

      Read the book!

      -DG

      --
      Run a pencil-and-paper RPG campaign with your far-off friends: Gametable!
    11. Re:Comments are evil. by Anonymous Coward · · Score: 0

      No, no, no.

      The code only tells you what the program does. The comments tell you what the program was *expected* to do, and *why*.

  7. Per project by mnordstr · · Score: 2, Insightful

    I guess the only real solution is to give a specific coding standard for every project. Before you begin coding, make up a standard that every developer has to follow, for comments, code layout, etc.

    A good standard for C++:
    http://www.possibility.com/Cpp/CppCodingStandard.h tml

    1. Re:Per project by Anonymous Coward · · Score: 0

      I think it's more important to learn developers how to write 'elegant code', not to write a code standard for every project. The standard will probably change and it gives the developer more things to worry about.

      It's better to give them a quick reference on how to write and why it's good with 'elegant' code.

      + a IDE with refactoring is gold worth. (It's hard to come up with good variable and function names at all times.)

    2. Re:Per project by looseBits · · Score: 1

      That sounds great and all and I've been on several projects where they've tried to do that (one manager told a developer to write a program that validates the coding style - dumbass) but when you bring in coders that have developed a certain way of doing things over 5 or 10 years, it is near impossible to get them to adopt some rigid standard. It would be like asking 10 different poets to write like e.e. cummings.

      The best you can do is to ask the team to try and comment their code (of course, this means giving them time to do it) and make their stuff readable.

      --
      Lord, bless my users that they may stop being such fucking idiots!!
    3. Re:Per project by Euphonious+Coward · · Score: 2
      That coding standard has a phenomenal amount of bad advice. Some of it is outdated, some just thoughtless. The omissions are as bad as the mistakes. (Where is exception-handling policy?) It's unfortunate, because there's lots of good advice there too, and an inexperienced programmer can't tell which is which.

      I have my own compendium of significant omissions at http://cantrip.org/coding-standard.html.

  8. Timeless Prof D.Knuth says it best... by gmarceau · · Score: 2, Informative

    The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style. Such an author, with thesaurus in hand, chooses the names of variables carefully and explains what each variable means. He or she strives for a program that is comprehensible because its concepts have been introduced in an order that is best for human understanding, using a mixture of formal and informal methods that reinforce each other. Donald Knuth. "Literate Programming (1984)" in Literate Programming. CSLI, 1992, pg. 99.

    --
    This post was compiled with `% gec -O`. email me if you need the sources
    1. Re:Timeless Prof D.Knuth says it best... by AYeomans · · Score: 2, Informative
      Check out Knuth's CWEB:


      "CWEB is a version of WEB for documenting C, C++, and Java programs. ... If you are in the software industry and do not use CWEB but your competitors do, your competitors will soon overtake you---and you'll miss out on a lot of fun besides."


      The CWEB page also includes example programs, but you will have to run them through CWEB to get the hyperlinked PDF files.

      --
      Andrew Yeomans
    2. Re:Timeless Prof D.Knuth says it best... by Nyh · · Score: 1

      The practitioner of literate programming [literateprogramming.com] can be regarded as an essayist, whose main concern is with exposition and excellence of style.

      Yes, it is very nice, but try to find good programmers who are good essayists too. I am afraid there aren't many master Knuths around.

    3. Re:Timeless Prof D.Knuth says it best... by gmarceau · · Score: 1
      Indeed. For the optimistic I'll add, both Graduate schools I applied to, Rice and Brown, took pride in offering a communication-skill supplement to their students. Rice's Cain Project in particular was receiving hearthfelt praises from its students.


      There is hope of more Knuth!

      --
      This post was compiled with `% gec -O`. email me if you need the sources
    4. Re:Timeless Prof D.Knuth says it best... by tslarkin · · Score: 3, Insightful

      Literate programming is to comments what a high level language like Pascal is to assembly language.

      Programmers have the weakness of thinking that they are writing for a compiler. They should be imagining that they are writing for another human reader. This is the essence of literate programming, which is, in my opinion, the only good idea that anyone has ever had about program documentation.

      If the programmer is restricted to interspersing comment lines between lines of code, then the elaboration of the documentation must follow the sequence of the code. To use a simple example, if I write a class definition, then I must declare all the member variables within the block of text that begins "class foo" and ends with "};". However, that may not be the best way to explain the significance of those variables. Maybe it would make more sense (for the human reader) to delay the declaration of a member variable until the place where it is first used. This can easily be done with CWeb. This simple example is hardly sufficient to reveal the power of LP. It is well worth taking a serious look.

      After the literate program is written, it is processed by two other programs. One produces a file suitable for submission to a compiler. The other produces a TeX file, which outputs a properly formatter version to be read by a human.

      The code itself is never the best documentation. It's not documentation at all, except in the most trivial cases.

      Any programmer can write a literate program. It's just a matter of understanding who his audience is.

    5. Re:Timeless Prof D.Knuth says it best... by Anonymous Coward · · Score: 1, Interesting

      The trouble that I have with literate programming is that most of the examples I can think of turned out to be unreadable by anything *but* a compiler. Some people can do wonderful things with it, but the ones that need to be reached will just find new ways of being sloppy.

    6. Re:Timeless Prof D.Knuth says it best... by dvdeug · · Score: 2

      It's interesting that the literate programming tool I'm most familiar with, noweb (because it's not bound to any one programming language, and I don't usually program in C or Pascal), isn't itself a literate program, because a literate program was too much work according to the author. The only major literate programs I'm familiar with are those written by Donald Knuth.

  9. Good Commented Code by guinan · · Score: 1

    While I'm personally of the opinion that the level of comments that's acceptable depends a lot on the purpose of the application and the number of people working on the project, a friend of mine learned a very good ( if slightly anal retentive ) coding style from reading angband source code.

    Maybe not for everyone, but you may want to try it.

    1. Re:Good Commented Code by Anonymous Coward · · Score: 0

      Funny. For your viewing pleasure (l-ui.c)

      /* function: redraw_stuff */
      static int toluaI_ui_redraw_stuff00(lua_State* tolua_S)
      {
      if (
      !tolua_isnoobj(tolua_S,1)
      )
      goto tolua_lerror;
      else
      {
      {
      redraw_stuff();
      }
      }
      return 0;
      tolua_lerror:
      tolua_error(tolua_S,"#ferror in function 'redraw_stuff'.");
      return 0;
      }

      /* function: window_stuff */
      static int toluaI_ui_window_stuff00(lua_State* tolua_S)
      {
      if (
      !tolua_isnoobj(tolua_S,1)
      )
      goto tolua_lerror;
      else
      {
      {
      window_stuff();
      }
      }
      return 0;
      tolua_lerror:
      tolua_error(tolua_S,"#ferror in function 'window_stuff'.");
      return 0;
      }
    2. Re:Good Commented Code by DLWormwood · · Score: 1
      You've got an out of date link... Ol' Ben's been off of Angband for years.

      Here's a more recent site.

      The coding style's overboard for two historical reasons...
      1. Ben wanted Angband to become parameterizable, that is, he wanted as much of the game's monsters and world to be provided by external files. So, he wanted any future mantainers to understand what exactly is hardcoded and what is being read in dynamically.
      2. IIRC, the current code tree decended from an old Macintosh port of 2.4.frog-knows. Since most developers were used to the PC 1.4 and Unix 2.4 versions at the time, the coding style may have been too different for most C coders to grok easily. Ben made this decision, I believe, since the then current Mac port most abstracted/separated the game logic from the UI.
      --
      Those who complain about affect & effect on /. should be disemvoweled
  10. Just tell me what a section of code is for. by foniksonik · · Score: 2

    I only work with Perl. When I'm looking at someone else's code all I ask is that they outline the basic function of a particular section of code so when I need to change/enhance/debug something I can find the right area to start looking as quickly as possible.

    I've never had to deal with 'obfuscated' code so I don't know about onscure variables, etc.. or how much more complicating they could be to my task.

    Just point me in the right direction. Anything else is going to be too much or too little... and if I don't already know what the code is supposed to be doing I probably should be talking to someone who does before I sit down to work on the code itself.

    Obviously reverse engineering of software is a whole different beast.

    --
    A fool throws a stone into a well and a thousand sages can not remove it.
    1. Re:Just tell me what a section of code is for. by inflex · · Score: 2, Funny

      "I've never had to deal with 'obfuscated' code so I don't know about onscure variables, etc"

      I thought Perl was the most efficient self-obfusicating code ever.

    2. Re:Just tell me what a section of code is for. by Anonymous Coward · · Score: 0
      Huh you write in perl!

      You see nothing but obsfucated code

      #DUCKS#

      Rog.

  11. Good Comments by jamieo · · Score: 4, Insightful

    Good code comments should describe the intention of the code. Write them *before* you write the code in a function/method to describe it's purpose. This will make you think exactly what you want it to do, and will allow for others to find/fix bugs easier when the implementation doesn't meet the intention.

    I then write inline comments in the code describing it's flow. It's only then do I actually write the code.

    Comments at file/class level should describe what it does and is used for. It should also describe how it fits in with the big picture of it's packages and the classes around it - give a reader some architectual scope to what they're looking at.

    Get into a habit, even for trivial functions/methods and you'll soon not realized you're doing it.

    Some people say code shouldn't need commenting, and the code itself should be enough. In a perfect world of no bugs and only populated by wizard programmers, this is fine, but not in the world I live in. You write some code and someone else (maybe yourself) will have to debug it at some point - maybe 3-4 years down the line. Even with a "neat" language like Java, working out how things work is much more time consuming without comments.

    1. Re:Good Comments by reinterpret_cast · · Score: 1

      We have been using Doxygen at work for more than one year and it's great, nice HTML etc. but I find the problem not being in the way you document the code: the most important is to have people to realize that documentation is necessary both for them as well as future developers. Working cooperatively is not just to use CVS, is also to provide to your fellow developers means to understand what you write.

    2. Re:Good Comments by terminal.dk · · Score: 1

      I completely agree with you. I am also writing the comment before the code, and has been trying to teach it as well.

      The main problem with much programming today is, that people don't think before they code. Spending the little extra time clarifying and expressing your thoughts will help coding quality, as well as provide the comments.

    3. Re:Good Comments by S1ack3rThanThou · · Score: 0

      I agree, I write my code in comments and only then write the actual functionality beneath each comment. Every function should have a description. Also I tend to use the module name to precede any externally visible function, which makes tracking program flow easy. I preceed every pointer name with a P as well. Just my 2p.

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

      "Get into a habit, even for trivial functions/methods and you'll soon not realized you're doing it."

      Another tip: your code may be beautiful in its succinct, harmonious functionality, but resist the urge to use IRL language like a programmer.

    5. Re:Good Comments by Cederic · · Score: 4, Insightful


      Congrats, you've just described a maintenance nightmare.

      Every time someone has to change some code, you've just forced them to double their workload, and change some comments too.

      If they forget, or don't have time, or are lazy, or don't notice the comment (it's easy to blank them out) then the comment doesn't get updated.

      Now you have a comment that is wrong. And that is so so so much worse than having no comment at all.

      Comment sparsely. Do not sprinkle your code with comments. Especially do not use comments like

      // increment loop counter
      loopCounter++;

      That is adding zero value.

      Inline comments are a major headache - they're painful to write, painful to maintain, and dangerous if they aren't maintained.

      ~Cederic

    6. Re:Good Comments by MadAndy · · Score: 5, Insightful
      Changes have to be done twice? That's right, when they change the code, they must change the comment.

      I'll repeat that: they MUST change the comment. And it must make complete sense when they're done or they'll be out of a job!

      Why is this important? When you change the comment, you must think about the comment. You must think about the change you've done and how it fits in with the rest of the code, and what the rest of the code is trying to do. If a comment isn't up to date or doesn't make sense, that's a bug in the code, as bad as any other, and it needs to be fixed.

      It's not difficult to spot when the comments don't line up, so they're fairly easy to fix. While you're there fixing the comments you need to check the code, 'cos whoever the idiot was that wrote it, they obviously haven't checked it properly. Go and hit them with a Very Big Stick.

      Certainly you shouldn't whine about the extra typing. A little extra typing shouldn't hurt - and you should be able to type faster than you can think, so it shouldn't really slow you down. If it does, go take a typing class.

      And if your lame excuse is that you're in too much of a hurry to maintain comments, just make sure you're not in too much of a hurry to deal with the bug reports that come back because you haven't checked your code properly.

    7. Re:Good Comments by Simon+Brooke · · Score: 4, Insightful
      Every time someone has to change some code, you've just forced them to double their workload, and change some comments too... Inline comments are a major headache - they're painful to write, painful to maintain, and dangerous if they aren't maintained.

      ... and absolutely essential to the poor bastard who comes after you - without them he has zero chance. I spent some hours on the phone a couple of days ago talking some poor lad in the states through the trickier bits of one of my open source packages. Fortunately it is inline-commented, so I at least knew what I had been intending to do.

      I agree with everything you say about the nuisance of maintaining comments, and I agree with everything you say about the problems that happen when you fail adequately to maintain comments. It's a chore; but it's a vital chore. It's got to be done.

      --
      I'm old enough to remember when discussions on Slashdot were well informed.
    8. Re:Good Comments by locutus2k · · Score: 1

      Besides, if you have everything well commented... When it doesn't work, it's much easier to track down the problem.

      I generally add an explination at the end of every line of code (that actually does something)

    9. Re:Good Comments by G-funk · · Score: 2

      I'd like to expand on this. A technique I use is this (yes, when I'm being paid I write ASP, when I'm not it's php).

      I start with a function like this

      function checkBarIsFooable(objBar)

      'Check for condition a exit if true
      'Check for condition b exit if true
      'Get response data
      'clean data
      'compare with database
      'fallback if apple = kwyjibo

      end function

      And then once I've got the (almost psuedo code) comments, I flesh it out, but with an extra indentation for code (one more than the comments) so it's easy to skim over the function and see how it does it's thing.

      I try to have a comment every 5 to 15 lines of code. It's especially good when you're writing code to check permissions on certain object user relationships like I have been lately, give it a try - and if you have any better ideas I'm all ears!

      --
      Send lawyers, guns, and money!
    10. Re:Good Comments by ebbe11 · · Score: 1
      // increment loop counter
      loopCounter++;

      You might have chosen some other example. The variable name 'LoopCounter' says absolutely nothing about what is counted. If you eschew inline comments, at least let the variable names indicate the purpose of the variable.

      --

      My opinion? See above.
    11. Re:Good Comments by jamieo · · Score: 3, Interesting

      I agree with the "increment loop counter" comment, that isn't worthwhile at all - but that's the difference between good and bad comments ;)

      However, I completely disagree with your premise about this being a maintenance nightmare and doubling workload.

      It's the exact opposite of a maintenance nightmare - it helps maintenance (certainly for long running large projects with developer turnover).

      It's also very little overhead. If you are a professional developer, just count how many hours you really write code in a week of working. It's not a great deal really, and the added time to add good comments is very little. The rewards of doing it are far greater than any costs.

      This is a complete mindset thing, just like coding standards - if you get in the mindset, it's easy and no cost, if you moan and complain and fight them all the time it's a pain and loads of work.

    12. Re:Good Comments by ProlificSage · · Score: 1
      The best thing to do (IMHO) is to find a good middle ground between the posters who want to comment every little thing (annoying), and the posters who want the code to always be self-commenting, which is also annoying. At some point, you are going to move to a different department, company, or project and someone else is going to have to maintain your code.

      The best situation I have found so far is

      • Obvious, well-named methods/functions and variables are not commented.
      • Non-standard practice, for which there is a good reason, is commented (i.e. catching Throwable in Java - why?)
      • Complex algorithms are commented so that maintainers will no what's going on. Sometimes this is as simple as an RFC number.
      • Source code changes such as bug fixes should be documented with your source control tool. However, I will sometimes put a line in the code that says "fix for bug x" next to a change so that if the code needs changes it's less likely to reintroduce an old bug.
      • If you're in Java (sorry, I don't do C/C++), use Javadoc's @param, @see, @return, and @exception tags.

      Typing brief comments while coding is much more efficient than re-reading the code several times to remember what I was doing six months (or more) ago. Many of the programmers I know can't type to save their lives, so there is a lot of tendency to use short variable names and sparse comments. Which is fine, but make them meaningful, or learn how to type 50 wpm or more. Just don't give me code where nothing's commented and your variable names are oaa and oca.

      Large block comments at the top of a class or method tend to be useless after the first release of a product, because bug fixes and new features will change the code, while not all programmers will take care to change the comments. So keep your variables and method names meaningful, document why the code may break standard coding practice, and let me know what other modules/classes I need to look at (Javadoc's @see tag is very useful for this) to understand how this code interacts with the rest of the system.

      At least the above suggestions have worked well for our team. Your mileage may vary.

      --
      Real software engineers regret the existence of COBOL, FORTRAN and BASIC.
    13. Re:Good Comments by ClarkEvans · · Score: 3, Insightful

      Congrats, you've just described a maintenance nightmare. Every time someone has to change some code, you've just forced them to double their workload, and change some comments too.

      The comments should talk about _what_ the module dues, not _how_ it does it. Stick with this distinction and it'll be a bit easier. If your module changes so much that the _what_ changes... then you really should take the time to reconsider your comments... as they may point out what assumptions other code may be making and where compensating changes may be needed.

    14. Re:Good Comments by Anonymous Coward · · Score: 0

      Hear, hear. Design first, then code. Unless what you're doing is fairly trivial, write out a design first and then implement what you described.

      OTOH for small projects I tend to do a stepwise-refinement thing, in which I create a block, sketch its sequence of operations in comments, then go back and code what the comments say should be there. Nested block: repeat. BTW the comments remain to give an idea of how I was thinking at the time, to explain what the code was *meant* to do. It also helps me to keep my thoughs in order during coding.

    15. Re:Good Comments by Sanga · · Score: 1

      Yes comments are code. How many times have you seen source that looks like this:

      {
      .
      .
      .

      // the fooPtr will be released by the caller
      delete fooPtr;

      .
      .
      .
      }

    16. Re:Good Comments by stoothman · · Score: 1

      I do this on every new project I code. I find it makes it easy to explain code to the non-coder who has written the program specs. This way I can easily walk them through the steps the program will take. They can tell me if it will accomplish the result they want to see and it helps to identify early on any cases which might not have been covered in the original design document.

      As they say an ounce of prevention is worth a pound of cure.

    17. Re:Good Comments by ebyrob · · Score: 2

      Every time someone has to change some code, you've just forced them to double their workload, and change some comments too.

      Just think of all that time wasted finding requirements and writing specifications before coding can even begin!! Who can function with such a multiplied workload.

    18. Re:Good Comments by Anonymous Coward · · Score: 0

      A balance is needed. Typically when I code, I comment the module/file describing what it contains and for each class/data object I describe what values it is likely to contain. For each function, I describe the inputs, results, side effects and make miscellaneous notes so that I can refer to papers/books containing the algorithmic technique or software design tool that I used.

      Too many comments do not help, but too few and you'll never remember the code if you need to revise it.

    19. Re:Good Comments by Anonymous Coward · · Score: 0

      Do me some favors:

      1) Assume that I know the programming language at your proficency. This is after all why we are all professional programmers.

      2) Don't obfuscetate you code with comments.

      3) For GOD's sake, if you comment you code that heavily, make sure that the comments are 100% correct.

    20. Re:Good Comments by SlugLord · · Score: 1

      Well I'll have to argue with you about the speed of typing... I'm not sure how fast you think, but it seems to me that it would be impossible to type (or write or speak for that matter) as fast as I think. (I'm working on getting used to the dvorak keyboard for that)

      I do not disagree with you, especially about the must change comments part.

      Comments, however, should be succinct and not take very much space (unlike this comment). They should take significantly less time than the actual code and also much less time than thinking about your design. If you really are so lazy as not to change the comment, at least delete it if it is no longer correct...

    21. Re:Good Comments by Hotsphink · · Score: 1

      It may not be a maintenance nightmare -- but it'll become one. Unless it is extremely simple or will only be worked on by one person, and in either of those cases, maintenance isn't a big concern anyway.

      There are two problems: first, comments and code gradually diverge, no matter how well-disciplined the programmers are. Think of it this way: when you write code, you introduce bugs. Everyone does, no matter how good of a programmer they are. But those bugs have many ways of getting exposed and being fixed. Either the compiler will catch them, or the first run through the code will, or QA will. Now what's so different about comments? They are bound to contain bugs too. But the mechanisms for catching them (code reviews and the occasional poor sap who wanders through chasing after a bug) are much, much weaker. Result: buggy comments.

      Second, the assumed significance of a comment drops proportionally to the density of comments. If there are too many comments, a reader will naturally tune them out. When you read a book and the writer introduces a new character, she'll never tell you that the new guy is a human being with two arms and two legs and more crotch hair than knee hair. She'll tell you what's noteworthy about the person, the stuff that you wouldn't already assume. Comments should do the same. A big help here, already mentioned by another replier, is commenting the what rather than the how, since knowing the what gives you a set of reasonable expectations.

      A more concrete expression of this tip is to try to comment the data structures, not the algorithms. If you do a good job describing what your data is, then I'll be able to guess what most of your code is going to say without reading it. And the rest is what's worth commenting.

    22. Re:Good Comments by jamieo · · Score: 1


      It may not be a maintenance nightmare -- but it'll become one. Unless it is extremely simple or will only be worked on by one person, and in either of those cases, maintenance isn't a big concern anyway.


      Jeeze, how many of you guys have worked on a big or long running project? Comments avoid the maintenance nightmare here! Something extremely simple or only being worked on by one person needs a lot *less* comments.


      There are two problems: first, comments and code gradually diverge, no matter how well-disciplined the programmers are. Think of it this way: when you write code, you introduce bugs. Everyone does, no matter how good of a programmer they are. But those bugs have many ways of getting exposed and being fixed. Either the compiler will catch them, or the first run through the code will, or QA will. Now what's so different about comments? They are bound to contain bugs too. But the mechanisms for catching them (code reviews and the occasional poor sap who wanders through chasing after a bug) are much, much weaker. Result: buggy comments.


      Buggy comments are an issue (and so can't 100% by counted on - you need some thinking too!), but the reason there is a difference between comments and code is that the language the comment is in is natural to the programmer - they have expressed their ideas without thinking of the language constructs they are using. The same cannot be said for code (even for good programmers) - a lot more thought has to go into the code itself, hence there is a far greater chance you can communicate the meaning of something to another programmer through a comment.

      Try ordering your next pizza in C and see how far you get ;)


      Second, the assumed significance of a comment drops proportionally to the density of comments. If there are too many comments, a reader will naturally tune them out. When you read a book and the writer introduces a new character, she'll never tell you that the new guy is a human being with two arms and two legs and more crotch hair than knee hair. She'll tell you what's noteworthy about the person, the stuff that you wouldn't already assume. Comments should do the same. A big help here, already mentioned by another replier, is commenting the what rather than the how, since knowing the what gives you a set of reasonable expectations.


      My original posting said just that - don't comment how it works, comment the meaning of it. What you intended it to do.


      A more concrete expression of this tip is to try to comment the data structures, not the algorithms. If you do a good job describing what your data is, then I'll be able to guess what most of your code is going to say without reading it. And the rest is what's worth commenting.


      A reasonable point, but I wouldn't choose to not comment algorithms. If it's a well known algorithm, just name it in a comment. If it's one that's been made up, you really *do* need to comment it - again describe what it's supposed to do, the theory behind the algorithm and any assumptions (but not the implementation - that's the code!).

      It's funny when programming topics are discussed on /., it really brings out of the woodwork how many students, amature programmers and web programming weenies there are out there. They should try doing some real work for once.

    23. Re:Good Comments by Cederic · · Score: 2


      I'd agree with most of what you say.

      The code I delivered last week contains a Javadoc comment for each public method, and also describing the classes. Those comments focus on what the parameters need to be, what the returns can be, and what error conditions may occur. Even this I'm worried will become obsolete if people change (for instance) the returns from a method, but don't update the Javadocs.

      The rest of the code is mostly self-documenting - the one big exception being an Internal Rate of Return algorithm, which I have used inline comments for.

      I disagree with you regarding comments about bugs - I delivered my code with a full suite of JUnit unit tests - they all pass. If a bug is found, I will replicate that bug in another unit test, and get that test to pass. Should somebody subsequently re-introduce that bug, the test will immediately fail. So I don't need to comment it, I'm actually regression testing it every time I run the test suite (approx. once every 2-10 minutes while coding).

      I do know how to code properly, I do put into practise what I know, and I still don't believe inline comments help - they distract when people are trying to read the code, they invariably become out of date and inaccurate and they seldom add value.

      ~Cederic

    24. Re:Good Comments by Cederic · · Score: 2


      Hmm, fair point.

      In practise, I tend to use descriptive names, and avoid 'loopCount', 'count', 'obj', etc. I also didn't want to quote 'n' as a variable name in my original post, as I don't use single letter variable names.

      However, the example I quoted was of the stupidity of commenting the incrementation of a loop counter, and thus loopCounter was actually entirely descriptive and correct :)

      ~Cederic

    25. Re:Good Comments by Cederic · · Score: 1


      Hmm. Comments written for users of your code should say what it does. Comments written for maintainers of your code should say why it does it.

      ~Ced

    26. Re:Good Comments by Cederic · · Score: 2

      >> Jeeze, how many of you guys have worked on a big or long running project? Comments avoid the maintenance nightmare here! Something extremely simple or only being worked on by one person needs a lot *less* comments.

      Hmm. How about a $5m project last year (plus ongoing maintenance), another project this year that has 8 people tied up for 6 months..

      Comments do not avoid the maintenance nightmare. Comments are a crutch for people who can't write proper code to begin with. Something written properly, with well factored code, descriptive method and variable and class names (java bias here if you hadn't noticed) does not require inline comments every other line of code.

      As the parent to your post mentioned, if you have a lot of comments, people will ignore them. If they are adding very little value, they'll be ignored even more. Which means the few parts of the code that really don't do what you'd expect, and so do need to comment, don't get noticed. And hello, here's a bug..

      >> It's funny when programming topics are discussed on /., it really brings out of the woodwork how many students, amature programmers and web programming weenies there are out there. They should try doing some real work for once.

      It's also impressive how closed-minded allegedly experienced programmers can be to adopting new practices or considering a point of view that challenges conventional wisdom.

      I have a reasonable amount of programming experience. I don't have as much as (e.g.) Martin Fowler, Kent Beck, Steve McConnell, the Gang of Four. So I read their books, I listen to what they are saying, and I try and change how I work to use the advanced techniques that make them so damn good at what they do.

      Since a lot of the literature I read suggested "If you need a comment, your code needs to be re-written such that the comment is no longer needed" I decided to try out that technique. And it works. I have clearer, more readable code, and it's more maintainable - the maintainer knows what's happening, and isn't being misled by comments that don't add value.

      Don't get me wrong, I do sometimes use comments. I hate having to, but sometimes I'm just not good enough at programming to refactor some code enough for it to be clear.

      Do not assume that because I don't like comments, I am a gung-ho cowboy coder. It just means I'm not a sheep, I do attempt to improve the quality of what I do, and feedback around me suggests that I usually succeed.

      Incidentally, I'd usually comment a complex algorithm rather than a data object - the data object usually gets a class level javadoc along the lines of "This object represents a row from the X table" and a certain amount of domain knowledge is assumed - there is adequate supporting documentation (requirements, architecture, design) to give maintainers that domain experience.

      ~Cederic

    27. Re:Good Comments by plumby · · Score: 1

      Try ordering your next pizza in C and see how far you get ;)

      Hopefully, you won't be getting the pizza delivery guy to edit your code.

      If you are having to explain what the code is doing, then either you've written the code badly, or the person reading it has not got enough language skill to be touching it. You may need to explain why a function is doing something, but never how. The code does that.

    28. Re:Good Comments by hey! · · Score: 2

      I don't quite do it this way. Instead I break down each function by series of statements that accomplish some task (not worthy of its own function). Comments focus on how the state of variables and such have been changed.

      So, my code tends to look like a series of pieces like this:

      // Next we need to accomplish foo.
      code; // usually 5 - 10 lines of code
      code; // loops generally form a unit like this.
      code;
      code;
      code;
      // Foo is done; at this point either A,B, or C is true.

      In other words, I try to use comments to guide the reader to the part he should be interested in; if he is not interested in the part that does Foo, he can go to the part below it knowing that A, B, or C is true.

      --
      Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
    29. Re:Good Comments by God!+Awful · · Score: 2


      Changes have to be done twice? That's right, when they change the code, they must change the comment.
      I'll repeat that: they MUST change the comment. And it must make complete sense when they're done or they'll be out of a job!

      Pay attention to what the guy is saying before you reply. If you write good comments, then it shouldn't be too burdensome for someone to change the comments when they change the code. If you write lots of useless comments then it does become a burden.

      A few years back, I was a newcomer on a project where the incumbent programmer had already established some coding standards. These included "declare all variables at the top of the function" (which I refused to do), use Hungarian notation (which I don't mind, but use only sparsely), and put large comment blocks at the top of the function which basically reiterate everything you see in the function signature (e.g. name of function, class, inputs, outputs).

      I found this very burdensome, so I eventually created a macro to generate the function header and I only added extra details where it seemed necessary. Over time I noticed that these comment blocks were very often wrong. He would change the signature of a virtual function, and this would require changes to a billion files. Do you think he is really going to update the useless header comment on each of these functions? Not a chance in hell.

      I agree with an earlier thread. Buy Code Complete and follow its advice. Comments should either:

      1. Explain what a block (>1 line) of code does as a whole.
      2. Explain why a specific design decision was made.
      3. Explain a potential pitfall that might catch the code maintainer off-guard.

      -a

    30. Re:Good Comments by ahde · · Score: 2

      If the pro-comment advocates can't even be bothered to read and understand the comments they want to reply to on Slashdot, how can we expect you to read comments in the code. Dude gives several valid arguemnt and you talk about ordering a pizza.

    31. Re:Good Comments by Meshach · · Score: 1

      How often when you debug code do you actually change the objective of a function enough that you actually have to change the comment? Usually then you are writing a new function and have to write new comments anyway Caleb

      --
      "Maybe this world is another planet's hell"
      Aldous Huxley
  12. my work by drDugan · · Score: 2

    I use doxygen++ for C++; it's great

    about 1/4 of my lines are comments -- most all of which are incorporated into doxygen descriptions -- and the rest only appear in the sourse listings

    see http://www.doxygen.org/

    1. Re:my work by David+Kennedy · · Score: 2

      Agreed - the best form of commenting is peer-reviewed
      JavaDoc or Doxygen. I've used both and used to love
      Doxygen, it's superbly flexible and easy to use.

      It helps to gather up the real things people should be commenting; pre-conditions, post-conditions etc
      and not "Infinite loop".

      Plus it looks nice presenting your docs on a
      website as part of the nightly build, or printed
      out as a (huge) pdf book. All for no hassle.

    2. Re:my work by magi · · Score: 1
      I like the reversed documentation order that Doxygen supports. For example:

      int IODevice::readBlock (char* data, /**< Data buffer */
      uint maxlen /**< Length of the buffer. */ )
      {
    3. Re:my work by Anonymous Coward · · Score: 0

      Ah what a good little programmer, want a cookie?m

    4. Re:my work by Anonymous Coward · · Score: 0

      Even if there're no (Doxygen) comments in the source, Doxygen is a great tool to find your way around a largish C++ project. It'll automatically generate skeleton reference pages for all objects and function.

      Absolutely everything in the HTML output is cross-linked with everything else. One feature I like especially is the option to generate syntax highlighted HTML pages of the source and headers. These are of course cross-linked as well, so the details of implementation are never more then a few clicks away.

      If you're working on a largish C++ (or java, or C, I guess) project with other people, you should definately check out Doxygen.

  13. Use plenty of expletives by oingoboingo · · Score: 5, Funny

    Well commented code should definitely contain a liberal smattering of four-letter expletives, eg:


    // no fucking idea how this works
    obj.doMagic();


    or...


    //bet those fucking lazy cunts in the QA team don't pick this up
    fileSystem.delete();


    When your code is released as open source and becomes famous, people can amuse themselves by searching through the source code to find all the hidden expletives, sort of like easter eggs. If you work for a commercial organisation, you can sit back and enjoy the panic as the QA and release teams sweat it out trying to track down every last filthy utterance before shipping to a fucker...errr..customer.

    1. Re:Use plenty of expletives by laserjet · · Score: 2

      My favorite is:

      //fucking piss drunk... not sure why this works, but will fix later.

      --
      Moon Macrosystems. Sun's biggest competitor.
    2. Re:Use plenty of expletives by Zocalo · · Score: 3, Funny
      Well the linux kernel certainly qualifies then...

      [admin@frodo linux-2.4.9-31]# grep -r [Ff][us]ck * | wc
      134 1327 10723
      Detection of the other expletives is left as an exercise for the reader...
      --
      UNIX? They're not even circumcised! Savages!
    3. Re:Use plenty of expletives by Tim · · Score: 2

      Uhh...use [us] and you'll get a bunch of fscks, which may actually be legit.

      I counted 26 legitimate guns n' roses references in the linux-2.4.2 source.

      --
      Let's try not to let fact interfere with our speculation here, OK?
    4. Re:Use plenty of expletives by Anonymous Coward · · Score: 4, Funny

      Until someone runs nm on your executable and finds some "funny" variable names.
      Funny variable names are sometimes related to say specific bugfixes a certain individual or customer has demanded.

      I know one person where very large customer demanded a specific and very idiotic new feature to the software, due to the customer being an idiot.

      Executable was not stripped.

      The variable name to control this feature in certain functions was thus called IsAFuckingIdiot .

      Customer by convention always ran nm on all new executables they installed.

      Customer got very upset.

    5. Re:Use plenty of expletives by Anonymous Coward · · Score: 0

      This should have read :
      The variable name to control this feature in certain functions was thus called _customername_IsAFuckingIdiot

    6. Re:Use plenty of expletives by jsse · · Score: 1

      When your code is released as open source and becomes famous, people can amuse themselves by searching through the source code to find all the hidden expletives, sort of like easter eggs.

      rgrep -i fuck /usr/src/linux

      Talking about the trouble installing Linux server for a local church. :)

    7. Re:Use plenty of expletives by russx2 · · Score: 1

      I always thought the compiler removed such things as variables names as they're a waste of space when everything can just be renamed a, b, c etc. etc. Afterall, the operating system doesn't NEED descriptive names.

      I've been known to be wrong however... ;-)

    8. Re:Use plenty of expletives by Anonymous Coward · · Score: 0

      But in this case the symbols weren't stripped so full debug info (inc. var names) would be available.

      So this time... You're wrong. Sorry ;)

    9. Re:Use plenty of expletives by Anonymous Coward · · Score: 0
      I counted 26 legitimate guns n' roses references in the linux-2.4.2 source.

      And the Linux zealots want their OS to be taken seriously! Sheesh!

    10. Re:Use plenty of expletives by Anonymous Coward · · Score: 0

      Don't poke holes in his little FOAF story. Now he has to come up with a post explaining why for some reason why the symbols were left in the production release. Though I bet he doesn't explain why this "idiot" knows how or is inclined to peruse the symbols in the executable.

    11. Re:Use plenty of expletives by Anonymous Coward · · Score: 0

      int Xinsert_your_nameXIsAFuckingIdiotThatDoesntKnowShi t =1;
      int main(void){return 0;}

      1, compile with normal options.
      2, do not run strip on generated executable
      3, run nm on generated executable.

      Answer question: Do I look stupid now?

    12. Re:Use plenty of expletives by Anonymous Coward · · Score: 0

      Because the symbols ARE left in the executable. Always has, always will be.
      Try 'man strip' and become learn something.

    13. Re:Use plenty of expletives by Anonymous Coward · · Score: 0

      Removal of variable names and other debugging info is not done by the linker.
      This task is done by the binutils tool called strip.

      Unless you run strip afterwards, thus stripping the executable, all variable names will remain in your compiled and linked executable.

      Try and learn something:
      [ronnie@DTM ronnie]$ echo "int IDontReallyHaveAClueDoI; int main(void){return 0
      ;}" >foo.c
      [ronnie@DTM ronnie]$ gcc foo.c -o foo
      [ronnie@DTM ronnie]$ nm foo
      08049528 B IDontReallyHaveAClueDoI
      08049470 ? _DYNAMIC
      08049454 ? _GLOBAL_OFFSET_TABLE_
      08048430 R _IO_stdin_used
      08049448 ? __CTOR_END__
      08049444 ? __CTOR_LIST__
      08049450 ? __DTOR_END__
      0804944c ? __DTOR_LIST__
      08049440 ? __EH_FRAME_BEGIN__
      08049440 ? __FRAME_END__
      08049510 A __bss_start
      08049434 D __data_start
      w __deregister_frame_info@@GLIBC_2.0
      080483d0 t __do_global_ctors_aux
      08048320 t __do_global_dtors_aux
      w __gmon_start__
      U __libc_start_main@@GLIBC_2.0
      w __register_frame_info@@GLIBC_2.0
      08049510 A _edata
      0804952c A _end
      0804840c ? _fini
      U _fp_hw
      08048274 ? _init
      080482f0 T _start
      0804943c d completed.4
      08049434 W data_start
      08048370 t fini_dummy
      08049440 d force_to_data
      08049440 d force_to_data
      08048380 t frame_dummy
      08048314 t gcc2_compiled.
      08048320 t gcc2_compiled.
      080483d0 t gcc2_compiled.
      0804840c t gcc2_compiled.
      080483c0 t gcc2_compiled.
      080483b0 t init_dummy
      08048400 t init_dummy
      080483c0 T main
      08049510 b object.11
      08049438 d p.3
      [ronnie@DTM ronnie]$

      for further study, try 'man nm' 'man strip'

    14. Re:Use plenty of expletives by Mr.+Slippery · · Score: 1
      Afterall, the operating system doesn't NEED descriptive names.

      But the debugger does.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    15. Re:Use plenty of expletives by BlowCat · · Score: 2

      But how did the customer know whether IsAFuckingIdiot is 0 or 1 in their environment? It looks like they were upset about their own assumption.

    16. Re:Use plenty of expletives by hughk · · Score: 2

      A good one to leave for QA is 'FIXME:'. At some point I sprinkle a few of these during development whilst I'm sortuing things out. Of course, I scan through and remove them. On one occasiion, I forgot to remove the comment though - whoops!! QA were not amused

      --
      See my journal, I write things there
    17. Re:Use plenty of expletives by markmoss · · Score: 2

      "//FIXME" is a pretty good way to flag sections that aren't complete yet, so a simple search will find them later. Just don't forget to remove these comments. 8-)

    18. Re:Use plenty of expletives by catfood · · Score: 2

      Years ago. Death March project. I'm the subcontractor. Client is out of control, has unacknowledged turf war between factions that want totally different features. Client management refuses to settle the dispute. Specs change wildly. Primary contractor goes along with client. Many fifteen-hour days ensue. Wife threatens to move in with parents.

      I get my part of the code into a decent state, document where I'd fulfilled specs in contract, document where I'd agreed to go beyond original contract, document where some stuff wasn't perfect but was agreed to be out of scope and not to be relied upon.

      Another contractor takes a crack at a different part of the system, different set of features. But it's spaghetti code; the other contractor has some need to make changes in my code and does so.

      Finally I get the system back again for further features. I see the other contractor's changes in my code. I find reasonably good code... with variable names like "IdiotCatfood" and "CatfoodSucks". Apparently the other contractor doesn't appreciate what I'd left him. (Nobody had told the poor guy that the spaghetti-nature long predated my involvement. He blamed me.)

      Anyway, the chosen implementation language doesn't have an option to strip debugging information.

      Oops. Other contractor got a talking-to. Heh.

    19. Re:Use plenty of expletives by jeremyp · · Score: 2

      //TODO: what needs to be done

      has a more neutral sound. It doesn't imply that there is a bug needing to be fixed that the coder couldn't be bothered with.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    20. Re:Use plenty of expletives by Anonymous Coward · · Score: 0

      Regarding FIXME: yes!!! I plop down a FIXME comment whenever something is missing or not the way I want it, but I need to complete a higher-level thought first. My code doesn't escape my clutches until all of the FIXMEs are gone.

    21. Re:Use plenty of expletives by MrFredBloggs · · Score: 1

      The release version has debugging info?

  14. Programming Style by Anonymous Coward · · Score: 0

    My style mini-guide

    Essential items of any source code:

    * Easily readable function and variable names
    * Functional comments, expressing intent
    * Large indent, making blocks obvious
    Opening statement and closing brace of a block are on the same column for fast correlation.
    * Consistant naming, all lower-case, _ for space.

    Some of these are contentious at the moment, see the link above for further details on why I believe in these. Regarding comments strictly, as I said it is commenting *intent* that is important. Commenting function is pointless, if you need to comment function your CODE is broken. The commenting of function is one of the leading cause of "lies" within code, that is, some aspect oor another that leads a reading programmer to assume to code operates in a manner which it does not. Examples of this are incorrect comments, badly named variables, and to a lesser extent badly scoped variables.

    So, commenting is not just a positive, it can cost you more than no comment at all if it is incorrect, sending the maintenance coder on a wild goose-chase through perfectly fine code looking for a bug that is overshadowed by an incorrect comment.

  15. Doxygen, etc by Stary · · Score: 5, Informative

    Tools like javadoc, or maybe better in your case doxygen can really help when it comes to commenting code... the idea is pretty much that you place a documentation comment before each function, or class, and so on, which usually makes the entire thing much easier. Having done that, I've found that only a few more non-obvious parts have to be commented within the actual functions.

    --
    Tomorrow will be cancelled due to lack of interest
    1. Re:Doxygen, etc by Ronnie+Coote · · Score: 1

      This is _exactly_ why I moved to VisualStudio.NET, for the commenting features.

      --
      Candygram for Mongo!
    2. Re:Doxygen, etc by eulevik · · Score: 1

      Doxygen, in my experience, is not worth the effort.

      Sure, if your project requires that you generate a stack of documentation, doxygen is better than the alternatives.

      But the best documentation is well-written code. Comments should only be used when absolutely necessary, which is maybe 10% of what doxygen requires. Search on Refactoring for more details.

    3. Re:Doxygen, etc by CynicTheHedgehog · · Score: 2

      Javadoc is a godsend. If you do object-oriented code correctly, all of your methods will be a manageable size and shouldn't need a lot of documentation. And unless you're actually modifying a class, all you really need to know are what methods are available, what their arguments are, and what their return values mean. Javadoc handles this wonderfully.

      The biggest problem I see, however, is with procedural programming. When people do things like use complicated loop logic to avoid recursive algorithms it can be a pain to decipher. But if things are properly broken out into modules and given meaningful names I have found that I can usually handle it.

    4. Re:Doxygen, etc by Twylite · · Score: 1

      <FLAME>

      Enough is enough. You are the sort of abject reprobate responsible for the vast amount of useless, redundant shit that pervades open/free software, and obscures the relatively small number of projects of real value.

      Here's the short & sweet version: no docs means no interfaces/contracts on your functions, means no forethought, no checking, and buggy software which no-one else can use because they don't have a fucking clue what the thing does unless they read the entire fucking file to decipher the cryptic shit which YOU think is well written code.

      A one-line description of WHAT a function does, coupled with assumptions about each parameter and what you can expect the function to return in normal and error conditions, is worth a shitload more than the implementation, which any kode kiddie can write.

      It also means that you can read 20 lines and have an EXCELLENT knowledge of the entire capability of a 1000 line file, and how you may be able to reuse the code. Or that Joe Maintainer knows what the function is supposed to be doing instead of having to know the entire goddamn codebase and guess at the intended usage.

      Or that kode kiddie #203987 on SourceForge doesn't have to start ANOTHER project to create a library when there are 80 already that (s)he doesn't understand how to use.

      </FLAME>

      --
      i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
    5. Re:Doxygen, etc by arkanes · · Score: 2

      Hear hear! Here's an example - someone wrote up a delphi module wrapper to zlib. It's a great, nicely written piece of code, but theres not a scrap of documentation. By the time I finished reading the source, figuring out what the new methods for the new streams did, which object I needed for my project, etc, I could have writting my own library. I probably should jot down what I worked up and send it back to the author....

    6. Re:Doxygen, etc by slamb · · Score: 2
      Comments should only be used when absolutely necessary, which is maybe 10% of what doxygen requires.

      What gave you the idea that doxygen requires you to add a fixed number of comments? If you set EXTRACT_ALL in the doxygen configuration file, then it will generate output for all classes/functions/#defines/whatevers, whether they are documented or not.

      In fact, I find doxygen is useful even for libraries which do not use its documentation comments at all. It generates other helpful things, like inheritance/collaboration/dependency diagrams(*) and quick summaries of the members of a given class.

      So simply turn on that option and make the 10% of comments you feel are necessary. Run doxygen. I think you will be pleasantly surprised at the results.

      (*) - If you don't see all these diagrams in your doxygen, you probably haven't installed AT&T's graphviz or haven't told doxygen that it is present. And I think each can be toggled in the config file individually. Take the time to download this software and turn on the options.

  16. How to write unmaintainable code by xmda · · Score: 1

    I guess most of you have seen this page on how to writing unmaintainable code before, but I'll post the link anyways:

    click me

  17. Rule of thumb by Overcoat · · Score: 1
    Isn't the rule of thumb" "don't just explain what a given block of code does, instead explain why you put that block of code in there"?

    A little simplistic, but a good start, IMHO

    1. Re:Rule of thumb by caca_phony · · Score: 1
      Isn't the rule of thumb" "don't just explain what a given block of code does, instead explain why you put that block of code in there"?

      As far as I am concerned, apart from exceptional circumstances, the code should make clear what it does (well designed data structures help alot with this). Explaining what well written code does in anything but assembler should be redundant to anyone but a novice reader of code. Why is another matter, why it is being done should be explained in your comments as clearly and concisely as possible.

      --
      ...and this lie crawls out of its mouth: 'I, the state, am the people.'
    2. Re:Rule of thumb by ObviousGuy · · Score: 1

      Those readers of your code will be novices at some point in their career. Comment and code as if all your readers were novices.

      --
      I have been pwned because my /. password was too easy to guess.
    3. Re:Rule of thumb by Anonymous Coward · · Score: 0

      Also a good idea is to include references to the language standard for each feature of the language you are using in a particular section of code.

    4. Re:Rule of thumb by johnw · · Score: 1

      Not just simplistic but utterly useless. If you make a rule specifying the quantity of comments then what you'll get is the required quantity of utterly useless verbiage. Like those Windows programs where someone has clearly been told that they must write a help page for every input field. You get to a field labelled "Throoble quotient", hit F1 and up pops a help thingy saying, "In this field you should enter the throoble quotient".

    5. Re:Rule of thumb by WeedMonkey · · Score: 1

      caca_phony has won the Slashdot .sig award 2002 (the prize: a date with Jon Katz).

      Everyone please wipe your .sigs until Jan 1st 2003, when the fun begins again!

    6. Re:Rule of thumb by Anonymous Coward · · Score: 0

      The AC flames you --More--

      -----
      |@.T|
      |A..|
      -.---
      ##

      The troll reads a Scroll of Katz!

    7. Re:Rule of thumb by johnw · · Score: 1

      I must apologise - I attached that comment to the wrong parent. It was meant to be a comment on the idea of judging comments by their volume.

  18. Simple rule of thumb by nagora · · Score: 1
    The documentation should be longer than the code. If that's enforced then most people can hardly help but actually explain what's going on.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
    1. Re:Simple rule of thumb by Anonymous Coward · · Score: 0

      This is stupid. Not only do you have to maintain the code. You also must maintain and keep the long documentation up to date. Write code that is easy to understand and comment about wierd / unusual sections (like bugfix code).

    2. Re:Simple rule of thumb by your_name · · Score: 0

      That's not a good idea at all. That encourages rambling pointless text, not quick precise explanations. Lose your rule of thumb.

    3. Re:Simple rule of thumb by nagora · · Score: 4, Interesting
      Write code that is easy to understand and comment about wierd / unusual sections

      Nice idea; never works in practice. The reason is that what you think is easy to understand is not always what other people think is easy to understand.

      The code you are writing now might have to be modified in the future by someone just out of university which means, generally, someone with very little experience. Your red-black binary tree might be "easy to understand" for you and a novelty to them.

      Also, mature highly-factored, optimised code that has been improved over several years can be very hard to follow even when the original code was quite straight-forward (but perhaps too slow).

      Finally, as a philosophical point, source code is supposed to be terse in comparison to natural language so it should take longer to describe the code in your own language than in the programming language.

      TWW

      --
      "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
    4. Re:Simple rule of thumb by nagora · · Score: 2
      That's not a good idea at all. That encourages rambling pointless text, not quick precise explanations.

      Quick explanations are rarely precise explanations when programmers are involved.

      Anyway, keeping documentation longer than the code encourages shorter code more than it encourages rambling text, unless you know programmers that like typing more than I do.

      Short code with a good explanation is always better than long code with poor explanation. In fact, short code is always better, period. Every line of code beyond what is needed for the task should be rooted out; it is a source of bugs and inefficiency.

      TWW

      --
      "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
    5. Re:Simple rule of thumb by Anonymous Coward · · Score: 0

      If you have to explain what a linked list is every time you use it (or what Quicksort is or memoization or a finite state machine or whatever) than you'll never get anything done. If any kid off the street can understand how slashcode works, they wouldn't need to offer CS degrees anymore.

    6. Re:Simple rule of thumb by FatAlb3rt · · Score: 1

      The documentation should be longer than the code. If that's enforced then most people can hardly help but actually explain what's going on.

      I DON'T agree on that one. We've got some Fortran still floating around here that was developed with auto-commenting utility putting
      c {If
      before each if and c }end if
      after each one, plus a mess of other stuff similar. It was so UNreadable that when it came my turn to make a change to that code, I removed all the comments in my development version, making it fully 1/3 of the original size.

      It may have made it a little more difficult to understand what the code was doing, but proper indentation made it MUCH easier to understand the overall structure and function.

      Too much commenting is a bad thing, and rules regarding length of documentation versus code are simply short-minded. Software developers are paid to think. Granted, some do a better job at it than others, but you gotsta use common sense.

      The best way to learn to comment is by example. Work with well-commented and poorly-commented code - probably the best way to learn.

    7. Re:Simple rule of thumb by nagora · · Score: 2
      I think this shows one problem: people mix the documentation and the code. Long comments in code make life difficult/anoying for people that know the code. Comments in the code itself should be short and consist mainly of hints.

      The documentation should ideally be in a separate document which explains each subroutine/function. But this much discipline is way beyond most programmers!

      One of the reasons I like Forth is that any decent Forth system allots an equal amount of space for comments as code but in a way which does not interfere with the code. A Forth editor can then display a block of code with the corresponding block of comments beside it. Also, since the comment block is assigned anyway you feel you should put something in it so I find I comment Forth programs quite well as I go along.

      TWW

      --
      "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
    8. Re:Simple rule of thumb by Anonymous Coward · · Score: 0

      But the fact that many ideals crumble, sometimes quickly, sometimes slowly, under the pressure of 'real life' is no excuse for not starting out with them, nor for not expending effort to preserve them.

      At the very least, be systematic. Pick a style ( or learn the house style ) and apply it consistently across all the work you do on the project. It won't be perfect, you can't see into the future or read minds, but it will probably be better than nothing.

      And on the philosophical track, who is it that makes this 'supposition' regarding terseness ? I can't see that there's a strict requirement for a programming language to be terse - programming languages need to be unambiguous, but this is not necessarily the same thing even if it gives rise to terseness as a second order effect.

      Sometimes the redundancy of natural written languages is pointed at as a reason for large comment volume vs code volume ( strip the vowels and punctuation from a piece of English text - ts ftn stll qt ndrstndbl ). Taken together with the fact that there are code constructs that have no direct relationship to the 'natural' world that languages have evolved to handle ( what's the 'natural' analogy for a parameterised function call ?), then I think I find this a better explanation of why it takes longer to write a comment that says what a piece of code does than any argument that assumes a requirement for code to be terse.

  19. The Comment Mantra by rob-fu · · Score: 0

    Taken from a Slashdot reader:

    Real programmers don't comment. It was hard to write. It should be hard to read.

  20. Overload whitespace to something meaningful! by Lt.Hawkins · · Score: 1
    --
    -- My Sig is a P228.
    1. Re:Overload whitespace to something meaningful! by ranulf · · Score: 1
      After the ridiculous interview a few years ago where Stroustrup claimed that C++ was a practical joke designed to keep software engineers, he really has made things a bit too obviously stupid with this one. Having an important block of code reduced to two characters that you can't even type (without using a tool to insert special characters) seems frankly ridiculous.

      The double backslash - everything before this is a comment - is particularly amusing.

      In fact, I even started looking for a date of April 1 whilst reading this document.

    2. Re:Overload whitespace to something meaningful! by Anonymous Coward · · Score: 0

      I hope that this paper was written on April 1st

      I now understand why C++ is such a mess.

    3. Re:Overload whitespace to something meaningful! by Anonymous Coward · · Score: 0

      They are all april fools... tch.

    4. Re:Overload whitespace to something meaningful! by Anonymous Coward · · Score: 0

      its there. right at the very end of the document. :)

      also, if you look at stroustrops list of publishings, this article is dated 4/1/98.

      - hawkins, who's hard drive died last night and doesn't remember his /. password to actually log on at the moment on this crappy temp computer.

    5. Re:Overload whitespace to something meaningful! by Anonymous Coward · · Score: 0

      You know you're in too deep when you recognize that as humor ;)

  21. a set of standards is the key by potcrackpot · · Score: 1
    The secret here (I believe), is that if you are involved in a group effort where you have to read (and correct) other people's code, you have to have a two-fold practice.

    • Develop a set of rules (coding standards), setting out not only comment style but variable naming conventions (e.g. capitals for constants, mixed for locals etc.). Ban things which make the source code several characters shorter but otherwise have no benefit. Make the rules as rigid and as specific as possible, and update them regularly. Then enforce them.
    • Develop a development cycle - design, code, review, test. The only one that really needs expanding on here is review - ensure that the code meets the coding standards and that it should work. Apart from appearance and conformance with the design, check for things like tight-looping, etc. Don't bother compiling and testing it (the coder should have made sure it compiles and done preliminary testing to make sure it doesn't crash straight away). Just eyeball it. DO NOT BE AFRAID TO BE AS PEDANTIC AS HELL. Whatever grief you'll be giving them they'll give back - as you should review each other's code in the same team (this also makes life easier when it comes to you, the reviewer, fixing a bug in the code at a later date).

    With 50 people all writing code for the same project going through this process, you shouldn't be able to tell who wrote which bit.

    The disadvantages to this are that it makes coding a bit robot-like - but hell, all the work was done is design anyway. People might also say that typing comments takes too long - but so does having to work out what the code does every time you look at it - instead of it staring you in the face. If this isn't what you want to hear, then try simply having a block comment for every code block, and a header at the top of every source code file. You should this way have as many lines of comments as lines of actual code. This is not, despite what others may say, a bad thing.

  22. K&P's "Practice of programming" by Anonymous Coward · · Score: 1, Interesting

    This book is a must-read on programming style. It also contains a perfect chapter on how to comment the code clearly.

  23. Coding Standards by benjymous · · Score: 1

    Company wide coding standards are implemented where I work, and whilst many people see them as an affront (i.e. "I'm already a good programmer - why should someone else tell me how to program) it does mean that code from other people is usually pretty easy to understand.

    Here are some of the key points in ours:

    function headers:
    put a description of the function, and what its inputs/outputs are/do, the original author and the date of creation. Anyone who modifies this function in the future (beyond very basic changes) should add their name and the current date, plus a quick description of what they changed

    variable naming:
    adopt a standardised and logical hungarian notation for the variables, and try to avoid abbreviating when the full word would do. "nCount" is far more descriptive than "cnt"

    Other things, such as always including { and } in C, and putting them alone on their own line makes the code much easier to read (though longer, but I'd rather read long meaningful code to compact confusing code) and putting plenty of bracketing in equations

    --
    Help me! I'm turning into a grapefruit!
    1. Re:Coding Standards by GigsVT · · Score: 3, Funny

      Other things, such as always including { and } in C, and putting them alone on their own line

      Phew, I thought I was alone. I'm glad it makes sense to someone other than myself to actually have the braces line up vertically.

      --
      I've had enough abrasive sigs. Kittens are cute and fuzzy.
  24. Over commenting by lpwuk · · Score: 0

    When I was at Uni, I got marked down in a class once for over commenting my code!!!

    I include a variable definition block at the top of each function describing what each variable was for.

    Each function got its own description and then comments were in the code when I was say, performing some test.

    Still, that is University for you :-)

  25. commenting code by caca_phony · · Score: 1

    I was most impressed by the advice Rob Pike gives on commenting code. If I remember correctly, his main points are: write code so that it is uncluttered and acts as it's own comment, never paraphrase the code itself, but rather explain metastructures and relations (otherwise you are more likely to have outdated comments that were redundant in the first place; a line is more likely to change than the overal logic). Keep both comments and code concise and clear. And call it complex_multi_word_variable, not ComplexMultiWordVariable, for readability's sake.

    --
    ...and this lie crawls out of its mouth: 'I, the state, am the people.'
    1. Re:Commenting Code by eulevik · · Score: 1

      It's function headers like these that give commenting a bad name.

      The first TEN lines of the function header and the first sentence of the description add NO additional information over the actual function header. All of this is worthless.

      The second and third sentences have some meaning.

      Suggested rewrite:

      bool openFile(string const fileName, ifstream

    2. Re:Commenting Code by lemkebeth · · Score: 1

      :sigh:

      Take a Programming class.

      I had to reformat due to the idiot filter.

      Your wrote:

      bool openFile(string const fileName, ifstream

      This wouldn't work (and isn't a comment).

      bool openFile(string aFileName, ifstream & iFile)
      {
      //Do stuff
      }

      The header itself (not a prototype) is for OTHER PEOPLE so they can understand your code later and should be readable.

      The compiler does not care how many lines of white space there are as comments aren't code themselves.

  26. CRC please... by shic · · Score: 1

    My vote is that everyone should use a CRC (Class Responsibility and Collaboration) style (wherever sensible). I want to know why a class exists and where it is to be used and what is its purpose - down to the level of detail of behaviours of individual methods. Thereafter I prefer to see concise and compact code and shy away from comments reading as if a chatty soliloquy (which often bears little or no correlation to the code - especially after it has been "maintained" by a few people!)

    Coding standards, to me however, seem to be quite a red herring... all code should be correct, coherent, compact and with a similarly crystal-clear specification. Most "coding standards" I've encountered have concentrated on fine-grained stylistic issues while ignoring the wider goal of concise clarity.

    1. Re:CRC please... by Anonymous Coward · · Score: 0
      all code should be correct, coherent, compact and with a similarly crystal-clear specification.

      You need to define what this means.

      Most "coding standards" I've encountered have concentrated on fine-grained stylistic issues while ignoring the wider goal of concise clarity.

      These are the attempts to define what is "correct, coherent, compact...". You cannot simply dictate "Your code will be concise and clear".

      Please try it.

      I'd love to be in that room when you stand up in front of 50 coders and say "Your code will be concise and clear!"

    2. Re:CRC please... by shic · · Score: 1

      I'd rather be in that room making my (admittedly open-ended) statement than trying to justify some half-baked anally retentive series of burdensome constraints, which seemed appropriate for some completely dissimilar project.

      Good code, like good art is very hard to define, though like with art, a group of professionals are likely to be able to distinguish wheat from chaff. In a simplistic manner, you can think of art as "good" if the target audience appreciate it. Similarly, I consider code and specifications "good" if the target audience are of the opinion that they are clear and concise. I personally don't think there is a recipe one can blindly apply to all projects. The game should be "does this change make the source more or less 'clear and compact'?" The trade off between adding comments (increasing verbosity) and eliminating them (increasing brevity) can only be made when you understand the target audience - i.e. everyone who will ever want to read the source!

  27. Make each comment count. by Anonymous Coward · · Score: 0

    a bad comment would be something like

    for(i=0; i

    Obviously anyone who understands the language itself understands what the standard statements do, and anyone who doesn't understand the language probably doesn't have much reason to follow the program flow line by line.

    Good comments are a level or two more abstract, and cover the medium-to-big picture of what functions and chunks of code are there to accomplish. Comment any *unusual* pieces of code, and any code that is doing something tricky, "clever", or simply less than obvious. Use code as a sort of "caulk" to fill in the holes of understanding in your code. Don't narrate the entire program line by line, but also don't hesitate to comment where the code is unclear.

    If the code is consistently unclear, it may be an indication that your code should be more readable overall.

    1. Re:Make each comment count. by Anonymous Coward · · Score: 0

      Whoops.

      Should've previewed. "Plain Old Text" apparently still snarfs "<" signs.

      The "bad comment" line was just an example of a perfectly clear line of code being subsequently "narrated"; ignore it, since it didn't come out right.

  28. Different parts of the brain by heretic108 · · Score: 2, Informative

    I also have seen my share of other people's code.
    Quality of comments varies.
    I've seen code from the 'hardcore hacker', who believes that the statements themselves suffice as comments - 'the code is intuitively obvious, and it comments itself'.
    I've also seen code from complete lamers, who dilute the code terribly with irrelevant shit:

    i++; // increment i

    Over the years, I've noticed that composition of code, and commenting/documentation of code, tend to draw on two different parts of the brain.
    Often, I find myself in a 'zone', where the code flows freely, and where commenting code feels like a total distraction.
    Other times - for instance, when I'm hunting an elusive bug, I find a different part of the brain kicking in - and at that stage, I find it easier, even pleasurable, to add meaningful comments, to change indenting, variable names etc, as if I'm narrating the code to someone else.
    I guess it's a matter of balance, and using the right mental faculties at the right time.
    A good rule of thumb is to imagine that someone else is sitting beside you, someone less acquainted with the task than yourself (eg a non-technical manager). Imagine you're explaining to him/her how the code works, and put these explanations in the code as succinct yet clear comments. Imagine this person asking you, 'what's that variable'. Don't be afraid of global search'n'replace of identifier names across all the applicable files. And imagine this person sometimes getting up and leaving you in peace, so you can have those precious moments to hack to your heart's content.
    In conclusion, I feel that much of a person's personality can be read from one's code. Is someone fundamentally easygoing and helpful, and caring about others? Or is someone a complete egotist, emotionally shut down almost to the point of autism? In my mind, the ability of code to communicate its intent and methods to other programmers is almost as important as the code successfully performing its task, since its communicability directly affects the ability and interest of others in working on it, and thus its openness to manpower leverage.

    --
    -- In the beginning was the WORD, and the WORD was UNSIGNED, and the main(){} was without form and void...
    1. Re:Different parts of the brain by inflex · · Score: 1
      "I find a different part of the brain kicking in - and at that stage, I find it easier, even pleasurable, to add meaningful comments, to change indenting, variable names etc, as if I'm narrating the code to someone else.
      I guess it's a matter of balance, and using the right mental faculties at the right time."


      Hail! Yes indeed, in chasing a bug I often fix it without noticing simply by doing as you have mentioned, going through, cleaning up, as though doing a multipass on source code makes it clearer like an interlaced JPEG :-)

    2. Re:Different parts of the brain by Anonymous Coward · · Score: 0

      Your 'increment i' example seems a bit simple, but let me give you something to think about.

      Sometimes you're not quite sure how something is going to work, so you have to lay it down as a series of steps in comments first.

      /* open the device */
      /* flip through the table looking for foos */
      /* track how many we got */
      /* shut it down */

      Then you come back and stick the code to do all that junk in between the comments. A year later, you may cringe for documenting something so obvious, but the fact is, you HAD to have it to get started.

      People who bitch about comments being too obvious probably don't realize that they may have been used as scaffolding to get the function built.

      Now, if you have lusers who rabidily comment everything after the fact using that kind of braindead obvious notation, you have a genuine problem. The trick is telling one from the other.

    3. Re:Different parts of the brain by benhaha · · Score: 1

      I'm with you there. That's my standard operating procedure.

      I do my classes the same way, copying the headings from my design document as comments for the functions I need and then filling them in as I get to them.

      It saves referring to the design document all the time since the headings are descriptive, and since I include the section numbers, it speeds up referring to them when I need to.

      Cheers,
      Ben Liddicott

      --
      NO ID: BEING FREE MEANS NOT HAVING TO PROVE IT
    4. Re:Different parts of the brain by nelziq · · Score: 1

      A good rule of thumb is to imagine that someone else is sitting beside you, someone less acquainted with the task than yourself (eg a non-technical manager). Imagine you're explaining to him/her how the code works, and put these explanations in the code as succinct yet clear comments. Imagine this person asking you, 'what's that variable'. Don't be afraid of global search'n'replace of identifier names across all the applicable files. And imagine this person sometimes getting up and leaving you in peace, so you can have those precious moments to hack to your heart's content.

      Ah yeah. Better than pretend that someone is next to you to whom you are explainin the code, actually have a person there. Thats right, Pair programming is fun and good for you too. It forces you to write readable code (at least its readable to one other person). Plus if one person gets hit by a truck then there is at least one other person who understands the code.

  29. It's been a long time but.. by NewtonsLaw · · Score: 5, Interesting

    It's been quite a while since I wrote any significant amount of code but after spending far too many years cutting code too early in the development process I eventually woke up to the fact that coding is the *last* thing you do (apart from testing and debugging that is).

    First-up you need a good spec -- and the spec should include the user-interface details to the extent that you could actually write the user-manual from that spec.

    Indeed -- if you can't write the user-manual from the spec then the spec is incomplete.

    From the spec the programmer should develop the structure of the code in another document.

    That structure document is repeatedly refined in a top-down process until you (eventually) reach a point where you're actually cutting code.

    I was always surprised just how much easier it was when the code was written as the lowest level of the structure documentation.

    Not only could you comment out the program structure document so that the compiler would ignore it -- but you ended up with absolutely accurate and comprehensive documentation built into that source.

    Project managers love this technique (and when I was in a project management role I demanded it of my team) -- it ensures that technical and end-user documentation are no longer the bits that get left until last and thus are either very shoddily thrown together or, if the project goes really over-budget, not produced at all.

    Of course, as we all know, there's a huge amount of temptation to just leap into coding at the earliest possible stage and leave the documentation until later -- because some stupid managers use number of code-lines completed as a metric of project performance -- duh!

    If you're smart and use good tools you can selectively collapse and expand the in-source documentation so that when you're trying to get familiar with a module that someone else has written, you can descend down the structure tree one level at a time without the meaning being diluted by stuff that is at a lower level.

    Unlike the days of interpreted BASIC, there's very little overhead involved in integrating documentation and code these days -- so there's no excuse not to do it.

    If required, the documentation can be automatically extracted from the source -- but by keeping the master copy in the code it becomes easier to ensure synchronization as changes and updates are made during the lifecycle of the project.

    1. Re:It's been a long time but.. by emag · · Score: 3, Interesting

      This is a technique I hope to follow with a few "personal" projects that I'm about to start. I'm refusing to write any code until I get down at least a spec for what each section is supposed to be doing.

      Alas, since the UI is wholly divorced from the back-end (I discovered I'd designed in my head an n-tier system just by seeing what I hated about both similar and unrelated software I've been forced to work with), I'm not sure I could follow everything precisely the way you suggest. After all, in the overall design, there will actually be several clients, each displaying data appropriate to its interface (web vs. fat client vs. text vs. scripted API vs. ???). I know what I can, and in fact must, do is define just how the "back end" (in terms of the clients) tells the clients what to display, what to get from the user, etc.

      I've also got to point out that in the past, I've been guilty of the "jump right in and code immediately" method of development. Unfortunately, I didn't have much in the way of control, since we were under pressure from both upper management and the customer (they have a lot of boats and guns...) to produce code for testing immediately.

      Even though this was for a "next generation" of a system already in place, it was a complete rewrite in a language the customer wasn't all that familiar with (C++), and so they were concerned that we wouldn't be able to guarantee anything would even work, let alone within the tight timing constraints required by parts of the overall system that weren't being changed.

      We had to deal with collecting all sorts of assinine metrics, such as the SLOC (Source Lines of Code) you've mentioned. Of course, the number of comments was also a metric that needed to be collected, and so we somehow had to find time to do those while frantically trying to keep pace with specs that seemed to change arbitrarily on a weekly or monthly schedule. Assinine? Yes. Real life? Yes. The only saving graces were that we'd managed to convince everyone who made decisions that some ridiculously low SLOC count was what we were responsible for in terms of monthly performance (giving us some breathing room to do intelligent design), and regular (weekly) code reviews amongst all the developers, spec writers, and the customer, to verify that what we were doing was, in fact, correct. (Though it seemed at times that we spent the majority of the meetings teaching all of the non-developers how to code in C++)

      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
    2. Re:It's been a long time but.. by Cederic · · Score: 3, Insightful


      Yes, we can tell it's been quite a while.

      Right now, businesses go to their IT teams and say "We need software that does X. Deliver it in 8 weeks."

      It would take 8 weeks to write a structure document in the manner you are describing (especially going through the various top-down iterations to reach code).

      Instead we have to write the basic framework of the solution, get that ready in four weeks, and then change and tweak all the little pieces of functionality that have changed in the requirements since we started. Because businesses don't know what they want, and all that is definite is the go live date (usually because the Marketing team have a fixed launch date)

      How are you meant to pre-document a requirement that arrives three days before go-live? With a suitable methodology you can add it, test it, and regression test the rest of the system to be sure you haven't broken it. But then generating user documentation too? Dream on, that's going to have to wait.

      ~Cederic

    3. Re:It's been a long time but.. by Pfhreakaz0id · · Score: 2

      I been in programming for 5 years in business enviroments (and some time at a software house) and have never seen a spec even close to what you describe. You're lucky if you get a generic "business case" statement, let alone a description of the UI.

    4. Re:It's been a long time but.. by Anonymous Coward · · Score: 0
      The problem with specs is that you often don't have them and won't get them, and if you do then they change while you're writing code. What you say may be true in an ideal(ized) world but life at the codeface is rarely like that.

      The term 'spec' is misleading too, your comment about the User manual implies you're referring to a Human Interface specification, what I'd also like (and won't get) is a Systems External specification, a Systems Internal Specification etc. etc. Throw in a few Use Cases and then snow me under with spec changes (any flavour) so that I could spend my entire time revising specs and not solving problems.
      I'm lucky if I get the back of a fag packet (cigarettes to those in the US).

      In reality I consider myself lucky if I get a clue about what the users want and half an entity model, so don't let me even catch you thinking that the comments (if there were any) should be up to date.

      Once a system's live the documentation is in the code that's live and the db schema (where relevant) anything else is a snare and delusion to seduce the novice from the One True Path and forgetting the First Rule - Code is King and all else is maya. If you would see the reality of the universe you must ignore the glamorous distraction of comments and documentation and learn that the only Truth is in the Code, know the Code and the Code shall set you free.

    5. Re:It's been a long time but.. by noom · · Score: 3, Interesting


      That style of programming leads to unreadable and unmaintainable code. The problem is that, in many cases, the programmer that required reams of documentation in order to write the code also requires that documentation in order to read it. The system-level become inappropriate to the evironment and language being used since the design was done "in your head" instead of "in the code.

      IMHO, detailed specs should only be done when there can be a GAURANTEE that it won't change for at least 2 years. The is is the usually the case with specs produced by groups like W3C, IETF, or the OMG, and a lot of programmers think they should copy the activities of these beauricratic organizations in their own work, where requirements can be expected to change continuously. In this environment, maintaining a detailed specification that is separate from the code is far too impractical. It's better that programmers make the code and the focus of their attention and make sure their code *deserves* to be the focus of attention (i.e. it's well written, elegant, easy on the eyes and mind, fun to take walks on the beach with, etc...).

      -n00m

    6. Re:It's been a long time but.. by sbeitzel · · Score: 3, Interesting
      Well, it sort of depends on what kind of code you're writing, doesn't it? In applications development, the dev cycle can be 1 year long or longer, with support cycles that run about 3 to 6 months.

      In web development, your dev cycle is often 3 months or fewer, with support cycles measured in days or even hours. The practice of shifting requirements up until the ship date is one that we, as professionals, have a duty to curb. If you're implementing new requirements during the final 10% of the project, then you're allowing the customer to break the project and blame you.

      Unfortunately, the nature of programming doesn't really change between those extremes: it's still a question of figuring out what the problem (the product requirements) is, designing a solution to the problem (writing a spec and, hopefully, designing it so that three cycles from now when you get a requirement to change the product, you can), and then writing the code that implements the design.

      The comments we always see in these discussions along the lines of, "comments are for the weak; real programmers don't use comments..." don't take into consideration the fact that the odds are very good that you won't be supporting your own code in a year, you'll be dealing with someone else's crap. As professionals, it behooves us to provide as many clues as we can to the poor sods who'll follow after us -- because what goes around, comes around.

      When I'm doing really fast web development, the spec is often a drawing on a white board -- so I take a picture. The design is often a doodle in a notebook -- which I label and keep on my bookshelf. And when I start banging out code, the first thing I do is pseudocode in comments, then interleave the real thing. That way, when I'm interrupted in the process, I can pick up again quite easily.

      I've handed off a lot of code to other people, and I've never gotten any complaints about too many comments (or about useless ones). I have gotten comments about how easy it is to follow what I'm doing, and that's enough. Do what you need to do to get the job done, but keep in mind that the job doesn't stop with getting the thing to compile and link.

      --
      Oh, go on, check out my job.
    7. Re:It's been a long time but.. by mrdlinux · · Score: 3, Informative

      What you are describing (and quite well) is the top-down programming practice. There's a big problem with it, though: in the real world, things change. As others have pointed out, you can't be guarenteed to be able to hammer down a specification that will be satisfactory for a year, or a month, sometimes even a week or a day. Some customer, some manager, or whoever, will demand a change in the final product. What will you do then? You will have to change your entire structure around and that can be extremely difficult.

      Fortunately there are other ways of approaching the problem. One of them is called the bottom-up approach. The basic idea is to create a mini-language that one can better formulate your problem in, and then start putting the pieces together. This is complimented by dynamic semantics that languages such as Common Lisp or Smalltalk have. Incremental, interactive compilation and development is well supported by these environments. The code winds up being self-documenting because you wrote it in a mini-language! Weirdly obfuscated--but necessary--as well as commonly used pieces of code can be abstracted with Lisp macros. Changing your data-structures is no problem, already in-use data-structures can be dynamically updated (and you can control how it happens). Errors are handled by the exceptional condition system (no pun intended) and the program can be continued from where you left off, after being fixed. Always you have a working, running codebase.

      --
      Those who do not know the past are doomed to reimplement it, poorly.
    8. Re:It's been a long time but.. by Bastian · · Score: 2

      The practice of shifting requirements up until the ship date is one that we, as professionals, have a duty to curb.

      This seems like an area where software engineers could take a hint from building contractors. Once the construction begins, they aren't too willing to change the architecture. The customer had their chance to set the requirements when the plans were being drawn out, and if they can't make up their minds, tough shit.

    9. Re:It's been a long time but.. by tpv · · Score: 1
      you're allowing the customer to break the project and blame you.

      There is a terrible attitude that is common amongst developers (including me), that suggests that the purpose of the project is to produce the software.
      It's not. (At least, not in the field I work in - in house development for a bank)

      The purpose of the project is to support the business need.
      If I deliver a project that fully meets the stated requirements, but doesn't actually serve the business need, then it's useless. You can play the blame-game all you like, but it's irrelevant. We're working together to produce a tool to allow the company to improve its business - that's the goal.
      I will drop/alter/add any requirement at any stage of the project, if I we agree that it is necessary to deliver proper functionality. My job is to make it clear to everyone what the cost/risks are of making that change - how much the project will slip by, whether the change actually makes sense, whether the system will be stable and supportable - but in the end, I work for them, and if they want it, and understand the risks, then I'll do it.

      --
      Read more of this story at Slashdot.Read more of this story at Slashdot.Read more of this story at Slashdot.
    10. Re:It's been a long time but.. by Anonymous Coward · · Score: 0

      Complete specification first works when you have written something extremely similar before, but breaks down when there are many new aspects to the project. You need actual code and prototyping to familiarize yourself with the new problem areas and to figure out how you actually want to do things.

      Because almost no software projects actually give you enough time to actually rewrite everything, you need to implement the prototype with the assumption that it'll be used in production (it'll eventually evolve into the finished product)...

    11. Re:It's been a long time but.. by Cederic · · Score: 2


      Total agreement - well said!

    12. Re:It's been a long time but.. by plumby · · Score: 1

      The comments we always see in these discussions along the lines of, "comments are for the weak; real programmers don't use comments..." don't take into consideration the fact that the odds are very good that you won't be supporting your own code in a year, you'll be dealing with someone else's crap. As professionals, it behooves us to provide as many clues as we can to the poor sods who'll follow after us -- because what goes around, comes around.

      I agree entirely that it's important to make code as simple as possible for whoever is going to maintain it. However, this is one of the reasons why I normally avoid commenting except where absolutely needed.

      How many times have you seen out of date comments in code, because the person changing the code didn't bother updating the comment? You may be dilligent in updating the comments, but most people I know aren't. If, instead of putting a comment in to describe what you are doing, you broke that piece of code into a separate function with a clear and accurate function name, then you've still got something that tells you what the code is doing. However, a function name is, in my experience, much more likely to be updated if the meaning of the function changes. This seems to be because, depending on what you are doing with code, and how well you know it, most people either see the code or the comment, not both. If you are skimming the code to see what it is doing, the chances are that you will read the comments if they are there, but once you've dived into the code, you no longer see the comments - you become blind to them, so you don't notice that they are now out of step, whereas the function name is part of the code and something that you are reading while you are editing it, so you'll notice that it's now wrong.

      I'm not against all comments - they do have their place (e.g., usage details on public methods to tell other people how to call the class), but very rarely to detail the internals of what your code is doing - clear, well named code should do that for you. In my view, most comments are just a poor substitute for badly named/written code.

      I've handed off a lot of code to other people, and I've never gotten any complaints about too many comments (or about useless ones). I, too, have spent many years handing code to other people, and rarely have I ever had any complaints about lack of comments.

    13. Re:It's been a long time but.. by ahde · · Score: 2

      That's fine when you're doing cookie cutter coding (like business logic) but if you're doing something new, or more accurately, outside your area of experience, coding has to be done before hand to "learn" the right algorithms, UI design, etc. before you can commit to a final design.

  30. UML and RUP by mikolajl · · Score: 1

    For big projects (and only big projects) using the Unified Modelling Language and especially the Rational Unified Process is very useful.

    Rational has quite a few tools which (when used correctly) allow to trace what class is responsible for which business case.

    1. Re:UML and RUP by Anonymous Coward · · Score: 0

      Rational is expensive. Too expensive for Opensource projects as an example. Check ArgoUML.

  31. Good coding method by dybdahl · · Score: 1

    Having done coding and commenting for more than 20 years, the most successful I've found is this one:

    Group several lines of code and comment them together with one or more lines of comments before the code. Example:

    // This is an example of how to
    // comment in an easy way
    function doSomething (String s) {
    // Initialize for the loop
    int i=0;
    int j=0;

    // Set all characters in
    // parameter s to space
    while (condition) {
    s[i] = " ";
    i++;
    }
    }

    1. Re:Good coding method by Anonymous Coward · · Score: 0

      I would have done like this:

      function setAllCharactersToWhiteSpace(string s)
      {
      int i=0;

      while (condition) {
      s[i] = " ";
      i++;
      }
      }

      Comments are bad. The code should speak for itself.

    2. Re:Good coding method by Anonymous Coward · · Score: 0

      > Comments are bad. The code should speak for itself.

      Utter nonsense. Code by definition CANNOT tell everything you need to know about itself. For something to tell about itself, you need CONTEXT. Code can't contain it's own context. It can tell you the what, but it can't tell you who, when, where, why, or how. (Yes, a reference to good old elementary school english, something most coders could use a refresher course in...)

      Taking your example slightly further, you might have something like this:

      /****
      * void obscureString(s)
      * char *s; - C String to be obscured
      *
      * This function takes a NUL terminated C string and replaces
      * each character in the string with a '*' character. This is
      * typically used by password input methods, where the obscured
      * string is displayed to the user and the actual password kept
      * internally.
      *
      * Since this overwrites the input string, you should make a copy
      * of your original string before calling this function.
      *
      * Returns: none (contents of s are modified)
      *
      * Usage Notes: This is not multi-byte aware, and may result in
      * a string of incorrect length when using a multi-byte character
      * set.
      *
      *****/
      void obscureString(char *s)
      {

      /* Loop through the string until we reach the terminating NUL,
      * replacing each character with a '*';
      */
      while (*s != '\0')
      *s++ = '*';
      }

      Notice it explains who uses it (password input methods), what it does (replaces the contents of the string with stars), when it is done (when entering a password), where the results get displayed (in place of the password string), and why it is used (so the password isn't displayed on screen). It also covers how to use it (make a copy of the string then call the function), and has additional information about it's limitations.

      Seems excessive for a 2 line function, but then again, this probably would normally be done inline (with a shorter inline comment more to the point). By making it a function, you *must* consider that people may want to use it for something other than it's original purpose, and should comment it so those other coders know how to use it.

      (BTW - The indentation and commenting style above is something we've been using inhouse for C for nearly 20 years now, and it works *very* well. More readable than anything else I've encountered.)

      (Correction - the commenting style above is close, but I've cut off most of the comment start/end bars, which usually run 72 characters wide - good for visibility and for keeping the comment block formatting from going way offscreen - above the function because Slashdot's lame lameness detector doesn't understand the idea of a proper seperator line...)

  32. Commenting standards by Anonymous Coward · · Score: 0



    The coding team I work with have some standards that the analysts and other code reviewers try to stick with.

    At the top of each 'significant' method, we whack a comment block such as this:

    Name :
    Description :
    Date :
    Pre :
    Post :
    Input Params :
    Output Params :
    Returns :

    ( and obviously fill it out ). One beauty of this is the description. If you can't describe your unction in a line or two, then your function probably needs to be broken down a bit further. It makes it a bit easier to follow the code if there's a nice header block to describe each function.

    A naming standard for variables is good too.

    We tend to follow a variant of the Hungarian notation ( ?? ) which has a single character to define scope ( local, module, global ) plus a character to denote variable type ( s for string, l for long, i for integer, o for object )

    So, you get a variable like liCounter ( a locally declared integer for counting ) or goCounter ( a global Counter object )

    Anyways, everyone has their own standard, the trick is, come up with a standard, and stick to it. Try to enforce ( encourage! ) the use of the standard. Even if no one else wants to, stick with it yourself, if you tend to maintain the code you write ( as opposed to someone else ) at least you'll be able to follow it !

  33. Document the function's contract by IvyMike · · Score: 5, Interesting

    Take a look at this function, and tell me if there's a bug:

    void foo(void) {
    int* x = 0;
    int y = *x;
    }

    Easy, the bug's the SEGV, right? Take a look at the same function, this time with comments:

    // Function: cause_segv
    // Description: Causes a SEGV for testing purposes
    void cause_segv(void) {
    int* x = 0;
    int y = *x;
    }

    The point? A bug is unwanted behaviorm, but that only makes sense if you've defined what the correct behavior is. My example is trivial, but often this is a real concern. Function "bar(int,int)" returns null whenever one of the arguments is negative--is that a bug or a feature? Your function has a goal in life, a contractual obligation to do something; make sure it's clear what that something is.

    Note that if you choose good function and good variable names, a simple one or two line comment at the beginning is usually sufficient to document whe function's intended behavior.

    I also find that an "assert()" or two on the arguments at the top of the function makes it clear what values the function accepts, and which one the function doesn't handle. It's an easy way to document the contractual obligations of the function.

    Stuff not to put in comments is stuff that's easily devised from the code. Check this out:

    // Function: square
    // Inputs: int x
    // Outputs: int
    // Used by: pythagorean(int,int)
    // Description: returns x squared
    int square(int x) { return x*x; }

    Did the "Inputs" or "Outputs" add any value? That information appears again, two lines below in the function definition, and it's guaranteed to be correct there (unlike the comment which will be out-of-date and wrong when we change "square" to work on longs). The "Used by" might have added some value, if it was correct, but as it turns out it's out of date, and 15 other functions now use "square". Any information better derived looking at the code should be left off. Any information which can be better found using "grep" or "find in files" should be left off. Any information that will probably be out of date at some point should be left off. Heck, in this situation even the description is probably extra verbiage, since it doesn't really help anyone. (I'd probably put it in out of habit anyway, though...so sue me:)

    1. Re:Document the function's contract by awol · · Score: 1

      The thing that is more troublesome than no comments is wrong comments. There are all sorts of reasons why it might be good to put a comment in, but the big problem is that they are essentially narrative with no impact on the correctness of the code. In the circumstances where comment says X and code does Y which is correct. Well the only way to work it out is to go back to the functional spec. What, none such detail is provided in your FS? Then you have to go and find the expected behaviour of the system. And determine if the functionality or the comment is correct.

      For these reasons there is something to be said for the structured commenting of formal systems like doxygen or autoduck.

      However, there are two types of "bug" a legitimate "bug bug" where the code as typed does not perform as intended and a "design flaw" where what is implemented does not fully implement the problem domain. The latter will never be helped by even accurate comments since by definition the comment describes the flawed design. In the event of a "bug bug" the helpfulness of comments is even less since the flaw will almost certainly be an unintended side effect or a typo and only analysing the code will help.

      I think that many of the descriptions in these posts (and probably not the author of the post to which this is a reply) are comments in lieu of design documentation (or even design :-). In these cases, I think the only justification is structured commenting where the comments are the design spec in situ, and can be extracted to form the formal design documentation.

      In the event that the code is illuminated by the existence of comments then the variable/functon names/algorithm implementation should be revisited to make the intention of the code clear in the source itself. There is one exception to this, and that is where a performance optimisation neccesarily pollutes the "self describing" nature of the code. Such enhancements need to be commented so that subsequent maintainers do not "clean" up the ugly code.

      The other exception of course is literate programming. But that is a different story altogether

      --
      "The first thing to do when you find yourself in a hole is stop digging."
    2. Re:Document the function's contract by natmsincome.com · · Score: 1

      While this is good:

      // Function: square
      // Inputs: int x
      // Outputs: int
      // Used by: pythagorean(int,int)
      // Description: returns x squared
      int square(int x) { return x*x; }

      I would recommend using a coding standard such as either the Qt or JavaDoc coding standard. The reason for this is that it is much easy to find documentation generators such as deoxygen that will generate documentation for your code. If you used the JavaDoc standard with the above then you would get:

      /** Returns x squared
      * @param x A valid integer
      * @return The square of the value passed in
      * @see pythagorean(int,int)
      */
      int square(int x) { return x*x; }

    3. Re:Document the function's contract by Darth_Burrito · · Score: 2

      Did the "Inputs" or "Outputs" add any value?

      Yes, peace of mind. I regard comments like this as a sort of promise between me and the guy who comes later. My way of saying, whatever it is, it will have the standard function header. ("used by" is silly though)

      Besides, who knows if some yahoo is gonna go modify the x squared function to do something more complicated? If there is a full function header there, the coder is much more likely to comment his change. Where I work, nobody uses function headers and comments are far and few between. I started putting headers in everything I wrote with a changelog section at the bottom. A few months later I noticed people (who almost never wrote comments) were actually putting entries in the function changelogs when they made a modification.

    4. Re:Document the function's contract by JBHemlock · · Score: 1

      IvyMike is spot on with this. I'm going to go even farther and suggest that this sort of commenting should be the default, with inline comments sprinkled sparingly, and only where really needed.

      I know lots of people consider inline commenting the way to go, but they can be hellish during maintenance. If you're going to maintain a piece of code more than a couple of years old, you want to know that the comments are germane to the code. If the code is part of a consumer application (i.e.: it changes every year like the wind, yet includes code from version 1.0), chances are most of the code has been changed several times as the apps feature set or feature behavior has changed. Sure, you can "expect" programmers to change the comments to reflect the code changes, but this isn't realistic. It's bad enough to expect someone who really understands a piece of code to keep the comments up to date with it. If you have someone who has never seen a particular piece of code before going in to make a change - especially an inexperienced programmer, possibly under severe time constraints, they're not going to take the time to make sure all the comments reflect the code. It sure would be nice, but it's just not going to happen. At least, it's not going to happen often enough to give later maintainers a sense that they can trust the comments.

      However, if a programmer approaches a piece of code with an understanding of what it is doing, then they won't need a bunch of inline comments to follow along. Especially if the code is written for clarity. Traditionally, if you're going to work on an unfamiliar piece of code and you really don't know what it is doing, you'll find someone who does to give you a brain dump. That's the purpose of a block comment in front of the code. Functions rarely change their purpose enough to invalidate a general brain dump about the function, while the internals can change quite radically over time. Put a nice, clear block comment in front of the function (or chunk of code), and it will still be useful in the future.

  34. Folding helps by AlecC · · Score: 1

    I find that the use of a folding editor which demands fold comments (i.e. nopt JEDit style) very valuable. If you get used to folding up your code, then you are forced to put enough comments in the body to make it readable.

    There should be Javadoc-style header commments on any function more than five lines long (and most shorter).

    If you have both of those, you won't get much better for commenting.

    Projects should have coding standards, and people ought to conform to them even if they don't personally agree with them. Code written to one standard and modified to another is worse than either. If you can get automated formatters, tune them to your house style then use them.

    It is possible to be too verbose, but it is much easier to be too terse. Err on the side of verbosity.

    Standardise abbreviations. Is "Length" given in full, abbreviated to "len" or to "ln"? Whichever you do, always do the same thing.

    --
    Consciousness is an illusion caused by an excess of self consciousness.
  35. Examples.. by popeyethesailor · · Score: 5, Funny
    # all of these will also get moved elsewhere

    # this is the worst damned warning ever, so SHUT UP ALREADY!

    # Keep your friends close but your enemies closer.
    # Or ignore them, we don't care.

    # You know, we do assume comments are linear -Brian
    Refer here for further details:)
  36. from /usr/src/linux/Documentation/CodingStyle by mav[LAG] · · Score: 2, Informative

    comes this advice:

    Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to
    write the code so that the _working_ is obvious, and it's a waste of time to explain badly written code.

    Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the
    function is so complex that you need to separately comment parts of it, you should probably go back to chapter 4 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head
    of the function, telling people what it does, and possibly WHY it does it.


    --
    --- Hot Shot City is particularly good.
    1. Re:from /usr/src/linux/Documentation/CodingStyle by Anonymous Coward · · Score: 0

      Writing obvious code is a good idea if that coding style doesn't interfere with the problem. If your code needs to do its job in a very limited timeframe (or under other constraints), then it's possible that the "understandable" code isn't fast enough. Now: Is it better to write a comment in natural language or add an understandable implementation (like what was there before optimization or before moving to a harder to understand but more efficient algorithm) in a comment?

    2. Re:from /usr/src/linux/Documentation/CodingStyle by mav[LAG] · · Score: 2

      Writing obvious code is a good idea if that coding style doesn't interfere with the problem. If your code needs to do its job in a very limited timeframe (or under other constraints), then it's possible that the "understandable" code isn't fast enough.

      This is a very good point, although bear in mind that the advice is from the source distribution of the Linux kernel which does tend to have to do its job in a limited timeframe :)

      I find when writing assembly that it's always a good idea to include a snippet of (debugged and tested) C in the comment header to a function if the code is anyway unclear. It can be read and comprehended almost instantly compared with say, a page of asm code.

      --
      --- Hot Shot City is particularly good.
  37. Multiple passes to your code by fractaltiger · · Score: 4, Insightful

    are the best way to comment it all.

    One day you're commenting on what variables do, the next you try to explain functions, etc.

    I just switched to Java from C++ and neatness is the most important thing I've acquired, not in code per se, but in variable naming. I've gotten used to doingThisWithVariableNames and DoingThisWithClassNames, while keeping THE_CONSTANTS capitalized. Ok, this isn't comments? But you'll be surprised at how much better it is to browse a new language like Java and see the norms of style in it, because old languages use too many confusing double_StandardslikeWritingThis_way.

    Comments go at the top of a page, with the coder's name and date, as well as a small bug report and if you can, a brief function list for those without a visual IDE like JBuilder. You then put a like with PRE: and POST conditions in your code and try to keep one liner comments to a min.

    I learned to comment the end of if structures and function blocks to make the code easier to follow... just add " } //end if" or something.

    Comments should be a paragraph long so that they make some sense. And comments, since they look different from the code sections, should be embelished with ===============, stars, and some
    nice spacing and vertical bars.

    Good comments to me mean good-looking comments, even if they don't have that much substance. Just my 2 cents. They're better than no comments at all.

    --
    "Wireless : LAN :: Laptop : Desktop"
    1. Re:Multiple passes to your code by inflex · · Score: 1

      "I learned to comment the end of if structures and function blocks to make the code easier to follow... just add " } //end if" or something"

      I agree, often that's a really good way of saving a few moments flicking up/down trying to determine which 'terminator' belongs to which block, things like } //end of "while (foobar...)" enhance it more.

    2. Re:Multiple passes to your code by plumby · · Score: 1

      If you need to be flicking up and down the code to figure out which block you are closing, then you've probably got too big a block. Try rewriting the contents of your loop as a separate function with a name that describes what it's doing. This gives several benefits - small loops, self-documenting code (as the function name describes the content) and a function that it may be possible to reuse elsewhere in the code. See Refactoring for more details.

    3. Re:Multiple passes to your code by Anonymous Coward · · Score: 0

      I agree, often that's a really good way of saving a few moments flicking up/down trying to determine which 'terminator' belongs to which block, things like } //end of "while (foobar...)" enhance it more.

      of course, using a half decent editor you can jump to/from the matching open/close braces by hitting the % key.

    4. Re:Multiple passes to your code by stevey · · Score: 1
      just add " } //end if" or something.

      I find most of your suggestions very good, and fairly standard - but the idea of adding comments to the end of closures seems a little .. pedantic.

      Surely most coders use a decent editor - to make comments like that entirely superfluous?

      I use DOC++ on my C++ code, after falling in love with JavaDoc several years ago. You can see an example of a fairly complex application documented :

    5. Re:Multiple passes to your code by joto · · Score: 2

      Well, if it's like a 20 page nested if/switch-statement, then comments like that are not superflous, even if you use a good editor. Of course, I don't think 20 page nested if/switch-statements are a good thing, but I have encountered them before. (I had to use indent, a printer and a ruler to see the program-flow). And sometimes you don't have the time or energy to refactor it all (although I would refactor the things I was working on). In that case, adding a few comments like that can really help the people who have to look at the code after you (now you just have to hope that people will not invalidate those comments when they are adding more cruft, because there is hardly a more confusing thing then comments out of date, or simply misleading comments).

    6. Re:Multiple passes to your code by inflex · · Score: 1

      That's a bit hard on my ZX80 sinclair with BASIC.

    7. Re:Multiple passes to your code by Anonymous Coward · · Score: 1, Insightful
      I learned to comment the end of if structures and function blocks to make the code easier to follow... just add " } //end if" or something.

      Yuck. I had to take some code over from someone who did that. It might be appropriate for your system, but it was the silliest thing I ever saw. It would have been better if the code I saw had kept the braces lined up. The original code had braces all over the place, and //end if statements to try to fix the problem

      void myRoutine(void) {
      ...
      if (idx == 5)
      {
      ...

      } //end if
      }

      With properly aligned braces, putting //end if just clutters it up.

    8. Re:Multiple passes to your code by Anonymous Coward · · Score: 1, Insightful

      "I learned to comment the end of if structures and function blocks to make the code easier to follow... just add " } //end if" or something."

      I agree with most of your comments (pun intended). The above quoted text is the only place in which I strongly disagree. The world of source code would be a vastly better place if people would simply drop the K
      do yet more code;
      }
      }

      There is no need for commenting the ending brace in this style since it is much easier to see where the braces match up. It's also cleaner and much better looking than:

      if (someCondition) {
      while (someCondition) {{
      do more code;
      do yet more code;
      }
      }

      The K&R style requires significantly more effort to unmangle, even when there are only a couple levels of indentation. For example, how many of you caught that double opening brace? No doubt several of you caught of, and no doubt several of you had to go back at least once to find it. Now imagine having to do that for a much longer piece of code.

      Of course, lining up your braces is not a cure for inattention, but it greatly increases your chances of picking up such a common syntax error. It's also incalculably easier for new programmers to read.

    9. Re:Multiple passes to your code by Anonymous Coward · · Score: 0

      I quite agree, smaller blocks make figuring out the code much easier.

      Sometimes it is better to break up a long routine into smaller blocks in the same routine though. I support a palm program for my current client, and the size of the compiled code is very important. This may be obvious to most people, but I discovered the hard way that sometimes a call to a routine is actually larger that the code for the routine itself, at least using code warrior for the palm.

      I tried to compress the code by making some common calls to lock and open a record. Passing enough parameters to the routine (database, record #, lock handle, and record handle) actually was larger in the result than just locking the record and opening the record.

      Unfortunately, locking and opening isn't pretty when the code for it is duplicated 20 gazillion times.

      Some of the other code was rather long though. Where I couldn't shrink large routines, I could break the code in the routine into blocked segments in that routine.

    10. Re:Multiple passes to your code by mder · · Score: 1

      I kind-of agree with the multiple-pass idea, but from a different POV.

      There are two important 'comment passes'. The first is when the code first gets written. At this point you should be able to say what it is the code should do, because you're working from some sort of spec., even if it's been written on the tip of one of Cowboy Neal's spurs.

      Now, the critical point is that you revisit the comments *after you've got it working*. Only *now* can you write what the code is actually doing and justify how it's doing it. Plus, the seperation in time between initial code creation and this comment review gives you a little of the feeling of someone coming to your code cold - nobody is better placed to comment those 'WTF' code moments than the author, i.e. you.

      I'm not saying don't write any comments to start with - I usually base my initial code drafts around a roughed-out design written as comment - but it's only when you come back to it as described above that the comment process can be completed.

      --
      Speak now. Peace is overrated.
    11. Re:Multiple passes to your code by Anonymous Coward · · Score: 0

      I agree that pathological commenting of the end-block brace can be "pedantic" and "cluttering", but if you're writing code that takes more than one screen (I know, some will say "then it's too long"), it makes sense to add those comments - Especially if you're creating (necessary) nested IF or other blocks (another one of my pet peeves: nesting to the point of having to scroll your editor horizontally to see the #$%! code).

      As in all things - moderation. Obviously, poorly indented code is inexcusable. If your excuse is "I had to use notepad" (believe me, I see it too often), then you need to get a decent editor.

    12. Re:Multiple passes to your code by DrPascal · · Score: 1

      Sometimes both works out the best. If you have ever had instances where there were at least 4 or so nested blocks, sometimes the spacing in the code makes that "} //while" really helpful. I do agree that lined up brackets are important (I for one do not like it when the brackets appear immediately after the conditional statement; personal coding style).

      --
      DrPascal: Not the language, the mathematician.
  38. PDL it is good no? by ZanshinWedge · · Score: 3, Interesting

    Personally, I like documenting backwards. Start with the requirements, work to the architecture, then get into writing PDL (Program Design Language). Essentially, you write out as detailed instructions on what the routine does as you can, without getting to the nitty gritty. It describes the intent of the code, not the code itself. It morphs into excellent comments when you expand it out into full code, and it also has the nice little advantage that it's at a high enough level that it's applicable to multiple languages (if you should desire to switch).

  39. Offtopc(-1) by jgp · · Score: 1

    WannaBeGeek*Girl*? Girl? What marvelous creature is this you speak of as "Girl"?

  40. Literate programming by awol · · Score: 1

    The best commented code is literate programming code. There is no better.

    --
    "The first thing to do when you find yourself in a hole is stop digging."
    1. Re:Literate programming by emag · · Score: 2

      Has this progressed much to supporting languages other than TeX, Pascal, and C?

      I have "Literate Programming" by Knuth, but there always seems to be something more important coming along that I need to read "first".

      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
  41. style(9) by RinkSpringer · · Score: 1

    You may want to check out FreeBSD's style(9) manual page. FreeBSD uses this in the kernel, and reading most kernel sources usually isn't a problem for me.

    1. Re:style(9) by Anonymous Coward · · Score: 0

      Amen! style(9) has improved my programming perhaps more than any other C programming guidelines I've ever studied.

      In particular, the prohibition against using 'typedef struct' has helped me more than anything else.

      The reasoning behind this prohibition is deep and as far-reaching positive effects on large-scale C software. Study it and benefit :-)

  42. Re:Code Complete - Something good from Seattle!! by Dillan · · Score: 1

    I'd second this, I started coding in FORTRAN/RAMBOTRAN many years ago and now use c/c++/php. The book is a very good read with some good anecdotes and worked examples. The best bit is that it is fairly language independent.

  43. Be political: No comments! by zloppy303 · · Score: 0

    Good code speaks for itself, so the best comment is a not written (ie. dead) one ;)

    --
    Beware of Programmers who carry screwdrivers. -- Leonard Brandwein
  44. Russian Programmer by serv0 · · Score: 0

    It all depends on the person's personaltity and such. Personally i comment code that has taken me a while to code or figure out. i figure if i can figure it out than others can, if not then i comment for my self and figure if others are smarted than they wont need my commments. /*/* This code explains the fundementals of my commenting process */ this is my explanation of my commenting */

    1. Re:Russian Programmer by serv0 · · Score: 0

      I jsut want to aplogize for my great speeling and my gooder english?

  45. type* var is evil by inflex · · Score: 1

    If we're in the mood to split hairs... then declaring variables as

    type* var1;

    is rather misleading in itself, ie: char* foo, bar;

    Whilst most people can instantly tell that it's meant to be a pointer to char and a char, it might not always be obvious if the programmer wanted two pointers, or a pointer and a char.

    Better to place the * with the variable name [imho ;)] ... char *foo, *bar;

    1. Re:type* var is evil by ObviousGuy · · Score: 1

      Mass variable declaration is evil.

      If you need to declare things, break them out to their own lines. That makes it easy to add comments to each one when necessary.

      char* foo; // This is our output buffer (we should have used a more descriptive name)
      char bar; // Descriptive comment here

      --
      I have been pwned because my /. password was too easy to guess.
    2. Re:type* var is evil by silvaran · · Score: 1
      Believe it or not, I use Microsoft's notation to make pointers to strings. While they use stuff like LPSTR (ugly - long pointer [32-bit] to a string), I do a
      typedef char* pstr;
      and
      typedef const char* pcstr;
      That solves the problem of your multiple-declarations. I suppose a lot of that is left over from C, where you had to declare all your data at the top of the block, but code like this is relatively clear (assuming you know what pstr is):
      pstr begin, end, other;
      and avoids the * notation, especially in a dynamic array of strings:
      pstr* some2darray = new pstr[12];
      some2darray[0] = new char[100];
      or whatever.
    3. Re:type* var is evil by Twylite · · Score: 2

      OTOH, char* foo is arguably more logical than char *foo. You are declaring foo as being of type "character pointer". You are not, in fact, declaring a char with a pointer to it named foo (you never declared the char, only the pointer), which is what is implied by your recommended form.

      --
      i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
    4. Re:type* var is evil by emag · · Score: 5, Insightful
      Oh, you've really touched on a sore spot. At a company I worked for once, there was a group of managers and developers who were working on coding standards for the entire division. Somehow, since *my* manager knew I was a fairly proficient coder, and wanted to make sure our group had input, I ended up on the panel. I remember telling a manager for another project point blank that he was an idiot for insisting that:

      char* foo, bar;

      was good coding practice, while

      char *foo, bar;

      wasn't, because the code was declaring two pointers, and so the * should be with the type and not the variable name.

      Even pulling out K&R, and writing sample code showing the sizeof(foo); vs the sizeof(bar); wouldn't convince him that he was wrong.

      Unfortunately, I don't think it was ever "officially" settled. Nor were several of the other corrections that I immediately made to his "proposed" coding standards document he handed out at the first meeting.

      Thankfully, my manager at the time listened to me (and also, helpfully, knew C and C++), so when we got the coding standards, they were filed with the rest of the useless paperwork we got, and we kept on writing things properly, including:
      • comment blocks before each function describing usage, parameters, expected range of return values, and error conditions
      • comments describing thee amount and type of testing done to verify things worked
      • comments about who had done what with what code and when
      • comments preceeding anything non-obvious about the code itself


      Three guesses as to which project was ahead of schedule. (Of course, not entirely fair, since we also didn't force code generation via Rational Rose. We instead reverse-engineered all of our final UML from the code we'd written and tested, and knew worked the way it was supposed to...)
      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
    5. Re:type* var is evil by Tony-A · · Score: 2

      If it takes splitting hairs to get the scopes right, then better split hairs.
      char* foo, bar;
      looks like: (char*) ((foo),( bar));
      behaves like: (char)((* foo),( bar));

      You get the same effect from:
      y = x * a+b;

    6. Re:type* var is evil by ingvar · · Score: 1

      What "char *foo;" says is that "*foo" is a character. Since "*" is the value of what points to, "foo" is a pointer to a character.

    7. Re:type* var is evil by tal197 · · Score: 3, Informative
      OTOH, char* foo is arguably more logical than char *foo. You are declaring foo as being of type "character pointer". You are not, in fact, declaring a char with a pointer to it named foo (you never declared the char, only the pointer), which is what is implied by your recommended form.

      *foo means 'foo dereferenced'. In a type declaration, 'int foo' means 'foo is an int', so 'int *foo' means 'foo dereferenced is an int'. And, therefore, foo is a pointer to an int.

      So, it's actually quite logical. In this: 'char foo, *bar', we declare that two things have type 'char': foo, and the thing that bar points to.

    8. Re:type* var is evil by Ed+Avis · · Score: 2

      There was once an article linked from Slashdot ('tips for C programmers' or the like) which explained this clearly - but I can't find the link now :-(. Essentially, you have to consider the C declaration syntax as a kind of logical puzzle.

      Take 'char *c'. This says that *c is a char. So what is the type of c? Working backwards, it must be pointer to char. Or with 'char (*c(int))' you can see that *c(int) has type char, so *c must be a function taking int and returning char, so c is a pointer to such a function. The cdecl tool can help with figuring out the more complex cases :-).

      --
      -- Ed Avis ed@membled.com
    9. Re:type* var is evil by plumby · · Score: 1

      If you find yourself having to comment the variable, it is extremely likely that you've not used a descriptive enough name. Why not describe it in the name, rather than with a comment? There are circumstances where this would lead to ridiculously long variable names, but very few. Normally, the context of the function that it sits in, along with a short name, are enough to describe it clearly - especially if you keep your functions short.

      On the odd occasion where your function name cannot easily describe its purpose, then the comment that you add will stand out more because it's not surrounded by pointless comments.

    10. Re:type* var is evil by Anonymous Coward · · Score: 0

      So if you know C, its readable. If you don't, it could be confusing.

    11. Re:type* var is evil by Twylite · · Score: 2

      You missed my point entirely. *foo is not a character. *foo is a pointer, and under ideal circumstances it is going to point to a character. *foo is not a character because you are not declaring a char variable, you are declaring a pointer variable.

      Saying that *foo is a character implies that you can do something like *foo = 'A';. Which, surprising as it may seem, you can't. This is usually referred to as a "segfault" or "bug". But if you first assign a value to the pointer so that it actually points to something, then you can access a character at *foo.

      --
      i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
    12. Re:type* var is evil by Twylite · · Score: 2

      I would argue that int *foo means foo dereferenced is a segfault unless you've assigned a meaningful value to the pointer foo.

      Or, to take your conclusion: In this: 'char foo, *bar', we declare that two things have type 'char': foo, and the thing that bar points to. Wrong, you haven't declared the thing that bar points to as type char. You haven't declared it at all. Which is precisely the sort of misunderstanding that I'm saying your style of declaration leads to.

      In char *bar you have declared a pointer, and some assumptions about the pointer. You have not declared a char. There is no memory allocated to that char, nor any type checking implied about the value that bar may point to unless accessing it through bar. In other words, you have declared nothing at all about what bar points to, but rather a constraint on the use of the pointer bar.

      In other words, char* foo clearly declared foo as a pointer, whereas char *foo defines *foo as a char, and by implication foo as a pointer, but no char is every actually declared.

      --
      i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
    13. Re:type* var is evil by LegendLength · · Score: 0
      [...] so *c must be a function taking int and returning char, so c is a pointer to such a function. [...]

      I thought there was no difference between a 'function' and a function pointer?
    14. Re:type* var is evil by tal197 · · Score: 2
      I would argue that int *foo means foo dereferenced is a segfault unless you've assigned a meaningful value to the pointer foo.

      We only care about the type of *foo, not its value. We can talk about the type of *foo even if foo doesn't point to a valid address, just as we can do sizeof(*foo) without causing a segfault.

      • The type of *foo is char.
      • Stack space is allocated for foo (not *foo). It wouldn't make sense to allocate space for the thing pointed to.

      You could argue that it's confusing to specify the type of one thing and the storage of another, but this model has the advantage that it actually gives the correct answer. Unlike 'char* foo, bar', which the other model fails to cope with.

    15. Re:type* var is evil by Ed+Avis · · Score: 1

      C has some special syntax so that if you have a function pointer c, you can call it as just c(). The more longwinded (*c)() also works. But this syntactic sugar doesn't mean they are the same - clearly you can assign a new value to c(), but a function defined as foo() cannot be 'assigned to'.

      --
      -- Ed Avis ed@membled.com
    16. Re:type* var is evil by Anonymous+Brave+Guy · · Score: 2
      You missed my point entirely. *foo is not a character.

      That's clutching at straws. You may not have defined what it means yet, but the type of *foo is char.

      Saying that *foo is a character implies that you can do something like *foo = 'A';. Which, surprising as it may seem, you can't.

      As opposed to, say, writing

      char a;
      char b = a;

      where because a is a char, it automatically has a value that makes sense, right? Oh. Oops. :-(

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    17. Re:type* var is evil by Anonymous+Brave+Guy · · Score: 2
      OTOH, char* foo is arguably more logical than char *foo.

      Not at all. According to the grammar of C and C++, char *foo is the natural form of the declaration. According to the interpretation of others here, that *foo has type char, this also makes sense. The char* foo form is horrible, because it encourages you to think that char* foo, bar would be two pointers-to-char.

      Why is everyone here ignoring the analogous C++ case of references, where char &x does not imply that &x is a char, though? That sinks the most popular argument here for using *foo. The sounder argument is based simply on the grammar of the languages.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    18. Re:type* var is evil by bjb · · Score: 1
      char* foo, bar;

      was good coding practice, while

      char *foo, bar;

      wasn't

      I have had teams that preferred the char* format before, and personally I like it myself since the type of variable you're describing is a char*, and you're calling it foo. Now what I don't like is the idea of putting more than one variable on the same line. That is where my specs (and personal style) resolves your issue. I define ONLY ONE variable per line. Heck, source code space can be verbose; I believe that if someone writes really small code in source, then they're usually just trying to show off.

      My belief is that compilers are pretty good, and the optimizers are always improving. Write the code legible and clear, and let the compiler/optimizer make it small and tight for you. Besides, when you only define one variable per line, you've got the rest of the line for a comment on what that variable's use is!

      --
      Never hit your grandmother with a shovel, for it leaves a bad impression on her mind...
    19. Re:type* var is evil by Twylite · · Score: 1

      Wrong. The type of *foo could be absolutely anything. You happen to be forcing whatever it is to be viewed as being of type char. The only reason you get away with this is that you are using C/C++, which is not a strongly typed language.

      --
      i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
    20. Re:type* var is evil by Anonymous Coward · · Score: 0

      Isn't reverse engineering UML from code a bit silly? Since the UML is normally supposed to be used as a start to build your code from.

    21. Re:type* var is evil by Anonymous Coward · · Score: 0

      Bravo!

    22. Re:type* var is evil by himi · · Score: 2

      Ummmm . . . No, the type of *foo in char *foo; is a char, and foo is a pointer to a char. There's no notion of forcing anything here - you're /declaring/ the variable, not dereferencing it.

      In any case, even when you /are/ actually dereferencing, unless you explicitly cast the variable to a different type somewhere along the line the compiler will pick up the mismatched type error. Since C isn't strongly typed, this often gets you a warning and nothing else, but that reflects the fact that C lets you treat a chunk of memory however you want, because it was designed as an OS implementation language where you need direct manipulation of memory. But the language itself /does/ have a strong notion of the type of variables - strong enough that you can do a lot of static analysis. It breaks down around pointers and typecasts because you can throw away information if you choose, but again, the language's notion of types is well defined, with loopholes that make playing games with memory easier.

      I could compile C to Caml (a strongly typed language) if I wanted to, and the only difficult bit would be providing generalised typecasts (Caml doesn't allow casting in the general case, only for things like ints to floats or chars to ints, where there are clear, well defined conversions). Most of the type handling would pass straight through untouched.

      Don't make the mistake of looking at the runtime behaviour of a language and thinking that defines it's semantics. In this case, a construct that's entirely meaningful will cause a runtime error if some other stuff isn't done, but that doesn't change the fact that it /is/ meaningful, and that the language properly defines that meaning.

      himi

      --

      My very own DeCSS mirror.
    23. Re:type* var is evil by markmoss · · Score: 2

      Robert Pirsig in Zen and the Art of Motorcycle Maintenance commented on how as a tech writer assigned to write user manuals, usually the guy assigned to teach him how the thing worked was the least competent and knowledgeable on the whole team. Nobody minded _him_ being taken away from his work to do documentation....

      I suspect coding or documentation standards are often the victim of this same practice, squared.

    24. Re:type* var is evil by mr3038 · · Score: 2
      char* foo, bar;
      char *foo, bar;

      IMO, the syntax used to define two pointers on a single line in the C is broken. I'd guess that it's a mistake in the original spec and simply hasn't been corrected because the fix would break some code.

      Think about it, the real type is "char*" "bar" not "char" "*bar". This can be easily demonstrated with the type casting syntax: you write "(char*)(foo)" instead of (char)(*foo) -- and notice how those mean different things. I always write "char* foo;" and define only one pointer per line. I define loop counters like i, j, k, m and n on a single line, though.

      --
      _________________________
      Spelling and grammar mistakes left as an exercise for the reader.
    25. Re:type* var is evil by IvyMike · · Score: 2

      I tend not to use multiple declarations per line; the problems outweigh the positives (With multiple declarations: You cannot comment variable usage later, it's (slightly) more typing to refactor code by removing or changing variables, and there's the problem you bring up).

      Once you've adopted that rule, it's a lot clearer (and closer to the truth) to use "type*", since the actual type of "var1" in your example is "pointer to type", not "type".

      It's also the style Bjarne uses in his code, if that makes any difference to you.

    26. Re:type* var is evil by Jaeger · · Score: 2
      If you find yourself having to comment the variable...
      then you might be in a freshman-level cs course.

      (it was long ago, but I'm still bitter.)

    27. Re:type* var is evil by emag · · Score: 2

      Unfortunately, the precedence tables for operators says you're wrong.

      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
    28. Re:type* var is evil by Anomie-ous+Cow-ard · · Score: 1
      Saying that *foo is a character implies that you can do something like *foo = 'A';. Which, surprising as it may seem, you can't.

      Yes you can. The segfault you're getting is because you happen not to be allowed to write to the particular char that *foo refers to at that point in the code. If you were allowed to write to that memory location, it would work exactly as it's supposed to.

      --

      --
      perl -e'$_=shift;die eval' '"$^X $0\047\$_=shift;die eval\047 \047$_\047"' at -e line 1.

    29. Re:type* var is evil by Anonymous Coward · · Score: 0

      I hope you havent stir too many people the wrong way.

      char* foo, foo2;

      foo will be a char* while foo2 will be a char. I assume you were joking and just wanted to see if anyone would catch it.

      [static@leeloo static]$ more charptr.c
      #include

      int main ( int argc, char *argv[] )
      {
      char* foo, foo2;
      printf( "foo=%d foo2=%d\n", sizeof(foo), sizeof(foo2) );
      return(0);
      }
      [static@leeloo static]$ make charptr
      cc charptr.c -o charptr
      [static@leeloo static]$ ./charptr
      foo=4 foo2=1

      As you can see... foo is a char* while foo2 is just a measly little char. I guess what do you expect from slashdot foos.

    30. Re:type* var is evil by Bytenik · · Score: 1

      His point is that the star changes the type, so the star should, therefore, be placed with type. I absolutely agree with this.

      Anyway, if you just declare one variable per line (as any C or C++ coder with even a modicum of experience would) you won't run into a problem.

      --

      "Scientists prove we were never here."
      -- Devo

    31. Re:type* var is evil by robhancock · · Score: 1
      This is something that Bjarne Stroustrup has weighed in on, he views it as a difference between the C and C++ philosophy:
      A ``typical C++ programmer'' writes ``int* p;'' and explains it ``p is a pointer to an int'' emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.
      I agree with his point that while multiple declarations of variables on the same line can cause confusion with this scheme, there is a simple solution to this: Don't declare multiple variables on the same line.
    32. Re:type* var is evil by Einar+Rune+Haugnes · · Score: 1
      emag wrote :
      (...) and we kept on writing things properly, including:
      (...) comments about who had done what with what code and when
      Tracking code changes is the job of the SCM system.

      Such comments, if you really think they are needed, can be generated by most SCM tools. It is not necessary and, in my experience, not very realistic to demand that developers manually maintain separate changelog block comments in each and every code file.

      In my opinion, changelog comments add nothing but noise.

    33. Re:type* var is evil by Chris+Mattern · · Score: 2

      > You missed my point entirely. *foo is not a character. *foo is a pointer,

      No, foo is a pointer. *foo is a dereferenced pointer, which means, since foo is defined as a pointer to char, it is a char. The fact that the pointer must be properly defined before it can be dereferenced does not change that.

      > Saying that *foo is a character implies that you can do something like *foo = 'A';

      No, it doesn't imply that. Saying that *foo is a static character variable implies that, but of course, it isn't, and we never said it was.

      Chris Mattern

    34. Re:type* var is evil by Sri+Lumpa · · Score: 1

      No, his manager was saying that and he corrected him doing what you did, using sizeof(), but even so, the manager didn't believe him.

      The mistake he made in his post was that you thought (and so did I at firtst) that:

      " because the code was declaring two pointers, and so the * should be with the type and not the variable name."

      Was him speaking, whereas it was his manager speaking it to justify using char*.

      --
      "The obvious mathematical breakthrough would be development of an easy way to factor large prime numbers." Bill Gates,
    35. Re:type* var is evil by Anonymous Coward · · Score: 0

      Actually, I usually type "char& x", because it makes more sense (type-specifier, then varname). I also type char* x.

      For the record, I simply don't use multiple variable declarations together... I never type "char& x,y" or "int* foo,bar".

  46. Linux and other things. by jon_c · · Score: 4, Insightful

    Personally I think the linux kernel is very well documented, at least the scheduling part, which is what I've looked at. Linus has a style of inserting huge comment blocks that explain exactly what's going on, then he'll have a page of code that does it, with little or no comments.

    A style suggested in Code Complete (I forget what they call it) is to write a method completely in pseudo code, make sure it's correct, then insert the actual programming code under each line of pseudo code. This technique, while clever I find leads to many useless comments like "loop through the employee records" and "increment the counter".

    A good test to see if the comments are working is through a code review, people will very often not know what's going on, or point out confusing comments or code that needs a better explanation. Code Reviews really improves your idea of what good comments are and teaches you what works and what doesn't.

    --
    this is my sig.
    1. Re:Linux and other things. by rnd() · · Score: 2

      It depends on your target audience. As a spectator, a page of comments before each function is fine. But if you are a novice programmer and you want to straightforwardly understand the techniques used, more of a line by line approach would be more useful. I personally like a bit of high level as well as some low level commentary to make the code easy to read quickly.

      --

      Amazing magic tricks

  47. I better choose my examples by inflex · · Score: 1

    Sheesh, so much for examples... the code was not intended of course to be specific... rather it was to act as glue to the comments.

    Now, where's my dictionary.

  48. Braces by Kwil · · Score: 1
    I'm curious, but why do people place the braces where they do, is there any stylistic reason beyond tradition?

    For instance, the code above has the following:
    void cause_segv(void) {
    int* x = 0;
    int y = *x;
    }
    sprintf("Did it work?");
    Yet personally, I like code formatted in this style:
    void cause_segv(void)
    { int* x = 0;
    int y = *x;
    }

    sprintf("Did it work?");
    I find that when you get a bunch of nested blocks it becomes easier to follow.

    When I see an opening brace as the first character, it's a reminder of the start of a nested block and I know I can skip to the close brace if I don't need to go into that block, with the blank line helping to easily spot the closing brace.

    --

    That Jesus Christ guy is getting some terrible lag... it took him 3 days to respawn! -NJ CoolBreeze

    1. Re:Braces by ObviousGuy · · Score: 1

      Whichever way you choose, you eventually get used to it.

      Personally, I change the bracing style depending upon the language.

      C and C++ get the One True Style:

      int foo(bar)
      {
      if (something)
      {
      // code
      }
      else
      {
      // more code
      }
      }

      Perl gets the cuddled style:

      sub foo {
      if ($something) {
      // code
      } elsif {
      // more code
      }
      }

      --
      I have been pwned because my /. password was too easy to guess.
    2. Re:Braces by Ed+Avis · · Score: 2

      The best practice, IMHO, is just to follow whatever the language's author prefers. He or she is likely to have quite a bit of experience, right? And presumably if you like the language then you already agree that its designer has some degree of good taste.

      This means: for C, follow the style in K for C++ get a copy of Stroustrup's book and follow the style he uses; for Perl read the perlstyle(1) manual page; and for Java follow Sun's conventions. This gives you the best chance of interoperating with other people's code.

      Of course, if you're doing development within a larger project, such as adding code to an existing program or writing a new utility to add to OpenBSD, then you should follow the local style conventions. Just find what the local 'source of authority' is, and follow that.

      --
      -- Ed Avis ed@membled.com
    3. Re:Braces by thogard · · Score: 2

      The one true brace style as defined by K&R puts the braces on the same line as the else and if statements since they control the flow and the braces are just there for grouping.

      int foo(bar)
      {
      if (something) {
      // code
      } else {
      // more code
      }
      }

      Thats 8 spaces to the tab for older stuff and 4
      for newer stuff.

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

      I disagree with this because it's inconsistent. Stick to one style, don't mix different styles!

      e.g.

      int foo(int bar)
      {
      if (something)
      {
      }
      else
      {
      }
      }

      this code is more readable as you can visually match braces and are instantly (from glancing at the code) aware of the creation a new scope.

    5. Re:Braces by himi · · Score: 2

      Go read K&R on this.

      And use 8 space tabs - that makes code blocks more obvious than anything else, and it even warns you when you're getting ridiculously deeply nested control structures.

      Another good thing to read is the Linux kernel coding style documentation (Documentation/CodingStyle). It's a good discussion of a lot of this stuff.

      himi

      --

      My very own DeCSS mirror.
    6. Re:Braces by thogard · · Score: 1

      In the days before Ansi C it was done like this:
      int foo(bar)
      int bar;
      {

    7. Re:Braces by IvyMike · · Score: 2

      I can only blame the fact that I was posting to slashdot late at night, and also not in the enivronment of an editor, because I would really format functions like this (at least in C++):

      int
      function_name(int x, int y)
      {
      int* z;
      printf("hello\n");
      return 99;
      }

      Briefly, the important points are this:

      • The return type has a newline after it, so the function name is rammed up against the left side. This way, the regexp "^function_name" will only appear one place in all of the code, at the function definition. Now you can type "egrep ^function_name *.C" and get what you were looking for.
      • The braces are rammed up against the left wall. In vi (which I don't use often) you can easily jump to such braces (I belive "[[" and "]]", though I could be wrong), making function navigation easier.
      • Four spaces for indent. Yeah, Gnu uses two and Linux uses eight (or is it a tab?); however, in my opinion, two isn't visually distinctive enough, and eight is excessive and wastes screen space. I know the Gnu people and the Linux people can both justify their decision, but to me, four just looks better. (If it's not clear to you why non-power-of-two indents are aesthetically unappealing, you should reconsider being a programmer.)
      • Spaces for indent, never tabs. See JWZ's document "Tabs vs. Spaces" to see why. He also explains how to set up emacs and vi to do the right thing for indent.
      • Eighty columns, unless you really can't fit it in. It's much easier to print code formatted to eighty. If you never print code, then it's much easier to merge code side-by-side if it's formatted to eighty. In this day and age of reallyLengthyVariableNamesAndAPIS, it can be tough, so if you have to break this rule in rare cases, it's ok, but only if you tried your hardest.

      I've been programming in Java a lot recently, though, where all your functions are in a class scope and therefore the "ram it up against the left" set of tricks doesn't really work. In this case, I tend to format like my original example. Mostly, I think, just to save vertical space.

    8. Re:Braces by Anomie-ous+Cow-ard · · Score: 1
      The original example was 'Allman style' or 'BSD style', i believe. At least, that's what The Jargon File seems to indicate.

      I've always thought 1TBS was more or less like this, though. Maybe i'm wrong, i don't really care if my style has a name.

      int foo(bar) {
      if (something) {
      // code
      } else {
      // more code
      }
      }

      Anyway, I use the above. My main oddity is with case labels, i half-indent them to set them off better from the code within the case.

      switch(foo){
      case 0:
      // Code
      break;

      case 1:
      // More code
      /* Fall through */

      default:
      // More code
      break;
      }

      --

      --
      perl -e'$_=shift;die eval' '"$^X $0\047\$_=shift;die eval\047 \047$_\047"' at -e line 1.

    9. Re:Braces by Finagle's+Friend · · Score: 1
      If your programming in C++ why aren't you searching for "::function_name" or "class_name::function_name" instead of "^function_name"?
      Personally I put a single space between the function name and '(' when declaring it (source and header) but not when calling it. This works for methods as well as static functions - it also works with class headers and template declarations where good indentation will typically mean there are leading whitespaces that blow away your technique anyway.

      Also if the return type is on the same line then the pattern "[A-Za-z0-9_] function_name" will only find the declaration - unless you do strange things with macros.

      I agree with "four spaces good, two spaces bad" though (and eight are a waste).

    10. Re:Braces by IvyMike · · Score: 1

      If your programming in C++ why aren't you searching for "::function_name" or "class_name::function_name" instead of "^function_name"?

      It's a matter of semantics, but I tend to think of the class name as part of the function name. So I do grep for "^class_name::member_function_name" all the time.

      If you mention the function name in comments, it's easy to have "[A-Za-z0-9_] function_name" show up. I suspect I'd have problems enforcing the "space between the function name and the paren only in the definition", because it involves vigilance everywhere. (In other words, people who's natural instinct to put in that space when calling the function have to change their habit everywhere.) But if you can enforce it, it's probably not a bad rule. I still like the "^function_name" rule because it takes effort only when initially writing the function, and it isn't going to show up in comments (unless you really indent your comments weird).

  49. Don't write complex functions! by alek202 · · Score: 1

    In order to keep a project simple, I follow a few guidelines:

    - Avoid complex functions. If your function seems to be too complex, try to swap out some code into another function.

    - Document the function's parameters and the values it return.

    - Flame/Kill/Bitch me for that, but I tend to create some nice graphics which show the complete project with abstract components, so you get an impression of the whole project BEFORE YOU START CODING. This makes it easier to decide which objects/functions belong to which module. See http://www.monday-rec.com/timo/rs404/rs404.html (hope that works on every browser :)

    Hope that helped a bit.

    -Timo

    --
    Every problem has a solution, but every solution creates new problems.
  50. Amazing grammer correctness! by Anonymous Coward · · Score: 0

    "What exactly is well-commented code anyway?

    Wow, this is like the first time I've seen some make the right anyway/anyways word choice at the end of the sentence. This just made my day. Now if people would start making the correct its/it's choice, I could die happy at the end of my life!

  51. Screw comments by firegate · · Score: 1

    Screw comments.. if they can't understand my code, they don't deserve to edit it.. It goes both ways.. Hail the spaghetti coders!

    --
    "Make it idiot proof, and someone will make a better idiot."
  52. Why not what by joss · · Score: 2

    It's real simple. If the reader can't tell what the code does from reading it, either it's written badly, or the reader is incompetent. In either case, comments won't help. If I see too many obvious comments, it's a clue that the author was clueless and I should probably just throw the code away because it will cause more trouble than it fixes.

    When comments are useful is to fill in information that is obvious to the author but not obvious to anyone else reading the code. When the author wrote the class/function he knew why he was doing it, why the function was needed at all, this kind of information allows a new developer to get an overall understanding of the project much faster.

    --
    http://rareformnewmedia.com/
    1. Re:Why not what by Anonymous Coward · · Score: 0

      I guess you don't program much or when you do it is nothing beyond a "Hello World" program

    2. Re:WHY not WHAT by cr@ckwhore · · Score: 2

      I agree with that! Not only for the benefit of others, I usually find the WHY in my comments to be beneficial to myself when I go back to a piece of code 6 months later.

      --
      Skiers and Riders -- http://www.snowjournal.com
    3. Re:Why not what by Anonymous Coward · · Score: 0

      Well, I'm an RF engineer & I've written some code that -- I'm sorry -- without comments, I wouldn't even be able to program the equasions properly. & no, it wouldn't help to abstract the equasions into a function... as these would still need to have the theory explained -- but the explaination would be more difficult as it would be out of context.

      You need to comment to show the theory behind your code -- the code will not be able to do this by itself. There are times that no matter what you do, the code is going to be technically challenging to the reader (and the writer for that matter).

  53. code comments by VonKruel · · Score: 2, Insightful

    If the code is well structured, variables, classes, methods, etc. well-named and well-conceived, it will explain itself to a large degree, and won't require an English play-by-play of every friggin detail. Generally, it's a good idea to have high-level comments that say "this chunk of code does X", but lower-level comments are often a waste of time, and only serve to clutter the code. Having said that, sometimes code is unavoidably hairy, and you have to recognize cases where the code needs some lower-level explanation, and provide it. First, avoid complexity, failing that, manage it. Generally speaking, I think code comments serve the purpose of helping s/w people to develop a mental map of the code. Code should have as few comments as possible, but no fewer :-)

  54. Tools matter by wray · · Score: 1

    One thing that is hard to do is find a reasonable balance between commenting code, and bloating the file so that it is hard to find the code. Anyone else have this problem? For instance, sometimes even with syntax highlighting, getting through all that wordy commentary is like trudging through the haystack looking for the needle. Here is where tools matter.

    First, use a good documentation program like doxygen or doc++ (C/C++) specific. Then a user can see the highlights of the code functionality in html, away from the code. This solves much of the overview type of code reading.

    Second, use well-thought out function names and variable names and be consistent. This is often at the cost of space, but even if you are writing code just for yourself, I found it helps tremendously.

    Third, use short, descriptive, comments to point out algorithm purpose, especially when it took you time to think through it. Try your best to not interrupt the flow of the code by putting comments on the end of the line.

    Fourth, on my wish list is a tool that I have not seen. That would be some kind of comment compressor, like you do with expanding directories into trees on a GUI file manipulation program. Emacs programmers -- are you listening? :-)

    Finally laying out code in a consistent manner (the right tool is indent here) really helps. Many styles have evolved because they provide visual feedback and cues about what you are seeing. Having and using a consistent style helps future mainters use those visual cues as they parse through your code. These cues can be more effective than comments because they are succinct.

    --
    Guess what? I got a fever! And the only prescription.. is more cowbell!
    1. Re:Tools matter by getek · · Score: 1

      So everyone hates MS OSes, but they have a decent IDE in VS.NET. It has that compressible comment feature you want. Also a really nice feature that allows you to define regions of code which are collapsable.

      there is an open source C# IDE, with the above features here. Of course if you want to develop for linux your going to have to wait on the Mono project.

      While this currently only applies to C#, it could obviously be implemented in other languages.

    2. Re:Tools matter by Finagle's+Friend · · Score: 1

      One thing I've done in both Emacs and DevStudio in the past is set the comment text to display in grey, this causes the actual code to stand out more, while leaving the comments readable. (I use black text on a white background)

      Another advantage of DOxygen is that it can show you which classes are derived from a class, this helps when maintaining code as you can check that some planned changes won't break one of these classes. Not something you can easily see from the code.

      If your using a version control system (you probably should be!), don't mix changes together - If your fixing 2 bugs in the same file, checkin the changes for one bug, then checkin the changes for the second bug. Later on it will be easier to see what changes were made for each bug and to spot any mistakes.
      (I used to work with a guy who would change variable and function names in existing code while making other changes. When you tried to 'diff' versions of the file to see what he'd done, it was obscured by lines that had changed because of renaming)

      Your "comment compressor" has been done in the past, I think it was called a "folding editor" because it let you "fold up" blocks of text - never used one though, but surely emacs has a mode for this?

      Other 'tools' I've used in the past were the function menu (func-menu.el ?) in emacs/xemacs which lets you jump quickly between functions within a file. Also some home grown lisp that could take class name and open either the header or source file. Both of these things reduced the time it took to get to grips with other peoples code.
      DevStudio and KDevelop have these features built in.

  55. Jutil.org documentation by MarkoNo5 · · Score: 1

    Good documentation contains formal specifications. Although most "programmers" will not agree, formal specifications provide the best way to document your code. First of all, they tell the user exactly what the software should do or should not. Secondly, writing formal specifications forces you to think about what you're doing, and prevent most bugs and design errors, even before you write the actual code. Another advantage is that once the specification is written, the code and the test classes can be written independently, which should result in better tests because the specification says what a method should do, so you don't have to guess it.

    On top of that, it should contain a description of what it (a class, package or whatever) should do, and class diagrams (a picture can say more than ....).

    For an example, look at the org.jutil.java.collections package of the Jutil.org project. The math package doesn't contain formal specifications yet because not all functionality is present to write them (numerical mathematics ...).

    If you want to write object-oriented software, read "Object Oriented Software Construction" by Bertrand Meyer, it's a must read.

  56. CWEB by D.E.Knuth by hobbes75 · · Score: 1

    Have a look at CWEB by D.E.Knuth. It shows a way of writing C / C++ / Java code that can really be understood.
    Apart from that, the use of syntactically more rigid programming languages like Oberon reduce the chance of obfuscated code in the beginning.

  57. Structure by Anonymous Coward · · Score: 0

    I find the best way of commenting is to keep it sparse. Functions or blocks that do things in an unusual way get a thorough explanation on top - by 'thorough' I don't mean 'every detail' but rather the purpose, the algorithm and why I did it this way.

    Other than that, keep a rigorous indentation structure, use short, simple names and don't make 'cute' code: no MixedCaseNamesForGodsSake, and no unnecessary white space (like 'for ( i = 1 ; ...'). Those two pratices are amongst the vilest Microsoftisms, and they make the code next to illegible.

  58. Pseudo code and formatting by silentbozo · · Score: 2

    I explain what each function is supposed to do, along with any assumptions I'm making and any desired side-effects that the coder should expect. If I'm using algorithms beyond a basic for loop, I'll stick pseudo code with example inputs and outputs in the comments as well.

    Function and variable names that make sense go without saying - they may be a pain to type in, but in the end they don't hamper code efficency, so make them as self-explanatory as possible (with exceptions like using i and j for a 5 line for loop.) Remember, whitespace and good, CONSISTENT formatting is just as important as good commenting. Funky, inconsistent formatting pisses me off just as badly as cryptic commenting and 6-character all-capital variable and function names.

    I comment under the assumption that the next time I look at this code, it will be years later and I'll have forgotten much of the programming language I originally wrote the code in (basically, I assume the next time I look at the code, I'll need to port it.) In instances like this, basic descriptions of what a function is supposed to do, along with pseudocode of the alogrithm with sample inputs and outputs are EXACTLY what I need - not to mention, they serve as a road map for when I'm writing and debugging the code the first time. Typically, I'll have just as much commenting as actual code for simple stuff, for anything beyond that I'll have double as much commenting as code (readable english is less efficient than clean code, so what do you expect?)

    You should always look over and polish both your code and your comments before you shelve your code. If you're leading a team, it should be your code that sets the bar for good logic, commenting and formatting style. Even if you're not, good maintainable code is what they're paying you do write (I hope.) Of course, if they aren't paying you enough to write clean, commented code, then they get what they're paying for...

  59. Proper Commenting of Code by joe52 · · Score: 2

    I thought that commenting was only supported to prevent a block of code from being compiled (or even better, dozens of little fragments of code).

    What is all this about using comments to document what you are doing?

    1. Re:Proper Commenting of Code by silentbozo · · Score: 2

      Nah, that's what if statement blocks with conditions that never will be met are for. That way you preserve the bulk of your unused code when you compile your binary, so you can bloat your release and have it shipped on a couple of CDs. Not to mention it confuses the hell out of the Q&A guys.

    2. Re:Proper Commenting of Code by rtaylor · · Score: 2

      There is nothing wrong with:
      if (true == false)
      printf("World Ending");

      --
      Rod Taylor
    3. Re:Proper Commenting of Code by viperstyx · · Score: 1

      //this lets us know the world will never end if(true==false) printf("World Endling"); //thats the reason you use comments //you will notice this makes more sense now //you can also use it to comment out code //but usually its for a coders convience //its good to take the trash out before you //bring your date home //-aroon

  60. Have a standard by Paul+Johnson · · Score: 2
    On a large project a key to getting anything done right is to have a standard and check that people stick to it. Code reviews are a Good Thing in any case. Checking that the comments say useful stuff should be part of this.

    Every file should start with a preamble giving module name, version, author, and maybe revision history. Most of this can be generated automatically by your version control system.

    Then there should be anything from a few sentences to a few paragraphs saying what problem this module solves and how it does it. Refer to any other documentation (e.g. UML diagrams, textbook for the algorithm) that might help illuminate what is going on.

    Each function or data structure should have a similar comment explaining what it does.

    Avoid comments that say "this routine is used by the Foo Function to update the Bar structure". Instead just say "This routine updates the Bar structure such that...". If the routine makes no sense on its own then it probably shouldn't be on its own.

    Paul.

    --
    You are lost in a twisty maze of little standards, all different.
  61. A Sense of Style by America+Uber+Alles · · Score: 0

    The chapter on style, from Bertrand Meyer's book Object Oriented Software construction, is available for download in PDF. It has some good, general rules for readablity and format.

  62. Comment the data structures. by davec · · Score: 1

    I like to see comments describing the data structures. If I know what variables mean it's usually not too hard to figure out what a piece of code does. It's much harder to do it the other way around.

  63. Location, location, location by ralphbecket · · Score: 2, Insightful
    Such words of wisdom as I've been able to muster in two decades of experience:

    Comments are vital, but like all programming tools require judicious use to be effective.

    It is easy for large comments to fall out of sync. with the code, so large comments should generally be reserved for high-level documentation of the kind one would expect to find in a literate program. Prefer a pointer (say, a URL) to a document explaining an algorithm than a block of text explaining the algorithm.

    Brief comments on types and data constructors are vital where their use is not obvious. The same goes for functions, methods and procedures.

    Function bodies should be small: it is better to have several small, easily understood functions (with names that clearly convey what they do) than one large block of code.

    Use of formal language in comments keeps them short and clear. Compare the following:
    • take(N, Xs) is the first min(N, length(Xs)) members of the list Xs;

    • take(N, Xs) returns the first N members of the list Xs or the entire list if there are fewer than N members of Xs.


    The term 'list' can be omitted if the function has an explicit type signature (even if your language is untyped, specifying types somewhere is invaluable documentation.) Another point to note is that these comments make clear what happens when N > length(Xs) - you should specify what happens in all circumstances, even if that just means saying "if these conditions are not met then the behaviour is unspecified."

    Including sanity checks in code is a useful alternative to documentation.

    It is a very good idea to annotate code with the invariants that should obtain at key points.

    Eschew clever code. Nobody will be impressed and it's a maintenance nightmare. And you'd better be very sure you got it right...

    Don't cut corners. Include *all* the error checks. Learning how to write elegant robust code is what distinguishes real programmers from cowboys. Managing both is an acquired skill.

    Avoid globals. Seriously.

    State and mutable update lead to unreusability, bugs, madness and divorce. Learn a functional programming language (add smiley if that helps).

    Someone once said words to the effect that if you find yourself writing a bulky comment, ask yourself if you could restructure your code so as to make the comment unnecessary.

    - Ralph
  64. Re:CWEB by D.E.Knuth by SWroclawski · · Score: 1

    There are other, simpler WEB variants as well.

    Nuweb works with basically any language.

    Noweb is a bit older and written in ICON.

    The main advantage of these WEB variants is that they use LaTeX rather than TeX, and TeX is far too complicated. The disadvatage is that WEB and CWEB "know" about the language and can give more information about things like the variables and functions, where in a generic literate programming system, this is either not possible or must be done manually.

    - Serge Wroclawski

  65. Hungarian Notation (Ugh!) by caveman · · Score: 2, Insightful
    I work in a coding shop where our company coding standard insists on some microsoft plot called 'Hungarian Notation'.

    For the unitiated, this means that all variable names have to be prefixed with letters that indicate it's type. i for int, f for float, ch for char, etc.

    The linux CodingStyle file (in the Documentation directory in every kernel source kit since who knows when) slates hungarian notation thus:
    Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged - the compiler knows the types anyway and can check those, and it only confuses the programmer. No wonder MicroSoft makes buggy programs.

    If you don't have Linux kernel sources on your machine, you can get a copy of CodingStyle here (from the 2.0 kernels).

    As a result of all this mucking about, because I tend to look after most of the dynamic memory, linked lists, and low level bit and byte-bashing operations, I end up with variable names with more prefix letters than letters in the name. I really detest this coding standard (which for some reason also forbids the underscore character on the grounds that it looks like a minus. Do you get foo_bar and foo - bar confused? I don't.

    I don't agree with all parts of the Linux CodingStyle, especially the bit about brace placement, but it's a good starting point for any C coding standard. Unfortunately, ours was designed by microsoft-centric folk who think that // is the start of a comment.

    Ayhow, back to topic, the Linux CodingStyle also contains the distilled wisdom:

    Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to write the code so that the _working_ is obvious, and it's a waste of time to explain badly written code.
    1. Re:Hungarian Notation (Ugh!) by JKR · · Score: 2, Insightful
      Hungarian notation is a bit more involved that that, and is actually extremely useful when not taken to extremes. That bit of kernel documentation is opinion, not some God-given truth handed down from the prophets to the great unwashed.

      For example, Hungarian can encompass scope in the variable name, which makes (a small number of) file & project scope globals just about bearable.

      The real win is that it makes pointers obvious - and in a language that encourages pointer arithmetic, that's invaluable for easy reading of code.

      I've used a variant of Hungarian for Java, that uses "m" for member, "a" for function parameter, "s" for class static. It works pretty well, too.

      Try it, you might like it. It's all about personal preference, and I find Hungarian-style prefixs plus InterCapitalisation more readable than some all_lower_case alternative.

      Oh, and "//" is a valid single line comment in ISO C '99. HTH. HAND.

      Jon.

    2. Re:Hungarian Notation (Ugh!) by caveman · · Score: 1

      Unfortunately, 'taken to extremes' is just how some high-ranking people around here like it. (The sort of people that complain about code, but never write it). Another thing I particularly dislike is the insistence of putting { and } around every branch of every if, while, for, etc.
      This makes the function longer, in terms of lines, (because we also insist on braces lining up and being on their own lines) than it needs to be, and consequently I lose declarations off the top of the screen (although I declare stuff as close to where it's used as possible).

      My point about // instead of /* and */ is that the latter is portable when you have to support and update some very old systems with quirky compilers. True story: One enterprising induhvidual here once used #ifdef's around two different style, but otherwise identical comments. Duh!. (Work experience/placement students thrown into the deep end of a critical project where nobody has the time to review their work).

      We used to have a very good company coding standard, but it only applied to FORTRAN, and helped us avoid the pitfalls of those platforms where compilers would, for instance, allow identifiers with more than six characters, but only actually used the first six (so WIDGET and WIDGET_LENGTH were the same variable). It also rammed home the importance of not relying on implicit declarations (GOD is real, unless declared integer) and all of the INTEGER*2, and INTEGER*4 length related problems that still bug some braindead C implementations today (where 'int' == 'short' or 'int' = 32bits and 'long' is longer. (I know what the standard says, but I've found that many programmers never read the standard)

  66. Check out how not to do it. by chrestomanci · · Score: 2, Interesting

    See: How To Write Unmaintainable Code by Roedy Green

    Every time I read it, I laugh from all the crazy examples of how not to do things:

    eg:

    16: Names From Mathematics:
    Choose variable names that masquerade as mathematical operators, e.g.:
    openParen = (slash + asterix) / equals;

    1. Re:Check out how not to do it. by Amazing+Quantum+Man · · Score: 2

      my contribution was...

      Abuse the preprocessor! Use global variables everywhere, and write the entire code in macros that manipulate those global variables!

      Disclaimer -- I once inherited code from a jerk who did this. First thing I did was run the preprocessor and essentially rewrite the code.

      --
      Fascism starts when the efficiency of the government becomes more important than the rights of the people.
  67. more isn't necessarily better by g4dget · · Score: 1
    Well written code should not require a lot of comments. It should use clear, self-explanatory variable, argument, and method names. It should also use well-known programming patterns and document those patterns in the class names (ServerConnectionFactory, EmployeeAdapter, etc.). When code is written in such a style, it will not require a lot of comments.

    If code has a lot of comments, that is either an indication that it isn't clearly written, or that it contains unnecessary comments. The first is an indication that there is a problem with the code itself, the second impedes readability (but can usually be remedied by hiding the comments in the editor).

  68. Comments Considered Harmful by Bazzargh · · Score: 3, Interesting

    This has come up before - in Martin Fowler's book, "Refactoring", he makes the controversial claim that sometimes comments are indicative of a need to change the code.

    Consider the different types of comment:
    - boilerplate comment at the top of a file: helps noone but lawyers.
    - change history comment: better use your source control tool to maintain this.
    - comment before a class: does this mean the class is badly named, or too complex?
    - comment before a method: ditto.
    - comment inside a method: could be a smaller method screaming to get out.
    Also heavily commented code is quite commonly just explaining away stupid code tricks.

    Nobody's suggesting that all comments are bad, just that a lot of the time adding comments is a poor substitute for fixing whats wrong with the code. Of course sometimes its the language thats the problem :)

    -Baz

    1. Re:Comments Considered Harmful by shess · · Score: 1

      This is pretty much why I prefer to limit to only two types of comments. One type describes how the code fits into the overall system, so you can relatively easily figure out how the component was intended to fit into things (when debugging someone else's 500klines of code, you want to tenatively omit big chunks of code as quickly as possible).

      The other type of comment documents the non-obvious aspects of what's going on. First, assume that the reader is perfectly capable of rewriting the code, and that they're 75-90% as intelligent as you are (which perfectly describes the delta between when I'm writing the comment and six months later when I'm reading it :-). They'll have certain assumptions about how it should work, which assumptions generally derive from proven past techniques. So you need a quick description of how things want to work, followed by a description of what you couldn't get to work that way, and why.

      BTW, most comments suck because they document WHAT the code does, instead of WHY it does it. Telling me that this code implements/uses a linked list is worthless - I can see that. But if I run across a linked list with no explanation why a linked list rather than something else, my first question is whether I can make the code simpler or faster by using something more appropriate. [No, I usually try not to *act* on that unless I have to refactor the code anyhow. It's just the first thing that comes to mind.]

    2. Re:Comments Considered Harmful by scrytch · · Score: 2

      Yunno, I'm really getting sick of Fowler's "worse is better" nonsense trying to win back the day for "cowboy coders" who can't handle any discpline at all and want to treat critical production code as a playground. I'm starting to think that projects are succeeding in spite of his "methodology" , and not because of it.

      - boilerplate comment at the top of a file: helps noone but lawyers.

      Meaninglessly vague. Is javadoc boilerplate? I don't like a stupid compiler that isn't self-documenting (hint, emacs is) but until then, we have this.

      - change history comment: better use your source control tool to maintain this.

      This guy must have a massively cool source control tool that actually shows him the changelog on a per-function basis, and automatically senses and shows only the changes that are significant, like an interface change. Or should every developer memorize today's changelog?

      - comment before a class: does this mean the class is badly named, or too complex?
      - comment before a method: ditto.


      The latter. We don't always get to write everything from scratch. Much less rewrite it 10 times a day for fun.

      - comment inside a method: could be a smaller method screaming to get out.

      Another smaller, uncommented method, no doubt.

      --
      I've finally had it: until slashdot gets article moderation, I am not coming back.
    3. Re:Comments Considered Harmful by Sajma · · Score: 2, Interesting
      Actually, I've found Fowler's technique for extracting methods pretty useful for clarifying code. Basically, he says that if a block of code is preceded by a comment, extract that block into a method whose name is the same as that comment, and remove the comment.

      This works pretty well, and leaves you with two kinds of methods: top-level ones that look like simple lists of tasks (enqueueEvent, sendReply, etc.), and small lower-level methods that do only a specific task. And yes, these small methods usually don't need to be commented, because the method name serves as the comment.

      This technique also works well for replacing ugly boolean formulas in if-statements. Compare

      // check if message is late, and if so, do blah
      if (System.currentTimeMillis() > (message.timestamp() + Message.TIMEOUT) {
      // blah
      }

      to

      if (message.isLate()) {
      // blah
      }

      I'd argute that the latter doesn't really need a comment.
    4. Re:Comments Considered Harmful by Anonymous Coward · · Score: 0

      While i can partly agree with his argumentation, i still prefer the comments. I absolutely love api documentation like javadoc.

      Besides, some methods just can't be too obvious without giving them annoyingly long names. Of course you could then make them do less and instead make more methods, but if it is an operation you do often then that will end up being annoying too.

      So i think he is right in theory, but i don't think it works out in reality. Autogenerated api documentation have saved me countless hours of work by letting me read a few paragraphs of english instead of reading the source code.

    5. Re:Comments Considered Harmful by scrytch · · Score: 2

      Good explanation ... I stand corrected. mod parent up. I'm not fond of comments in general either -- I'm a fan of the SCID (source code in database) concept that would allow for cleaner separation of code and comment, such that boilerplate need not be inlined, leaving inline comments for only critical things. However, while we're stuck with flat files, it's never a good idea to eschew stuff like javadoc/doxygen "boilerplate" for any public method except perhaps simple accessors (and a setter should still document expected input).

      --
      I've finally had it: until slashdot gets article moderation, I am not coming back.
    6. Re:Comments Considered Harmful by smallstepforman · · Score: 2

      You're obviously one of the group of people who just dont get it. After 'seeing the light', I organised a quick presentation at work to introduce my collegues with Fowler's wisdom, even prepared a few pages as a presentation. I even asked my boss to get a copy of the book for every developer. I must be a bad presenter, because only 2 other people (out of 13) saw the benefits Refactoring brings, and decided to study the book. The other 11 thought (just like you) that Refactoring was bollocks. Out of curiosity, what do you think of the 'Gang of Four' book?

      As I said, I must be a bad presenter.

      --
      Revolution = Evolution
    7. Re:Comments Considered Harmful by TimMann · · Score: 1

      "Comments Considered Harmful" and "sometimes comments are indicative of a need to change the
      code" are not at all the same thing.

      Although I could nitpick the examples, yes, sometimes if you read the comments on a piece of code perceptively, they will help you pick up something that needs to be changed in the code. Does that mean the comment was harmful? Certainly not! It was helpful -- it raised a red flag that helped you see the problem. Deleting the comment would not fix the problem; it would only obscure it.

      Other times, of course, comments can be trivial or plain wrong and would be better deleted. A good comment is one that describes what's being done more compactly and at a higher level of abstraction than the code. If you like, it describes the "what" rather than the "how".

    8. Re:Comments Considered Harmful by Bazzargh · · Score: 3, Interesting
      I see you've gone back on the post a little later but its worth answering some of your points.

      Yunno, I'm really getting sick of Fowler's "worse is better" nonsense trying to win back the day for "cowboy coders" who can't handle any discpline at all and want to treat critical production code as a playground.

      Fowler's stuff isnt cowboy at all. It actually takes a lot of discipline to follow what he actually says in his book (writing tests to ensure that each refactoring is safe). His book is a series of recipes for how to introduce changes safely, not a rally call for changing code because you feel like it today. The Refactoring book can help people working in any methodology (except perhaps the 'Personal Software Process' and its variants, which want you to learn to write code right first time, and are less realistic for code maintenance). XP gets a mention but its not an XP book.

      Meaninglessly vague. Is javadoc boilerplate?

      Meaning 1 on wordnet is "a standard formulation of legal documents or news stories". Now look at this (code from Tomcat). See the boilerplate comment at the top? Its NOT THE JAVADOC - its the license. There are tools like jalopy which help you maintain this cruft but like I say it helps noone but lawyers.

      This guy must have a massively cool source control tool that actually shows him the changelog on a per-function basis, and automatically senses and shows only the changes that are significant, like an interface change.

      The 'change history comment' is the old practice of writing in a history of changes at the top of the file (not on a function by function basis as you suggest) duplicating the comment recording in the source code control system, while not necessarily recording all changes because it isnt /driven/ by that system. VSS, CVS, etc can show you the changelog externally, or you can include a $Keyword$ to get the changelog included in the comment and maintained for you. As for knowing which change is significant - developers don't know this either. The change which breaks things is the significant one and they usually don't realise they've done it at the time. Interfaces changes, while high cost, are actually less significant causes of error since they are easily caught by static checks. It is the changes in behaviour that will get you.

      We don't always get to write everything from scratch...

      This is true. often you'll not get to rename the methods of some dumbly named third party interface. And in this case the comment is inevitable. Note I did say not all comments are bad. I'm asking you to question them.

      Another smaller, uncommented method no doubt.

      Yes, exactly. If the smaller method is 4 lines long, has a blindingly obvious name, and is in the private interface of the class (often the case for extracted methods like this), the comment is superfluous.

  69. Design by Contract by MosesJones · · Score: 2


    A couple of words, OCL

    This is in the interface, rather than an implementation, and you won't get the code to the impl, so what does it do ?

    /**
    * Get the Bug description for the given Id
    * @pre id must be > 0 and less than BugList.lastId(), the highest bug number
    * @post The return must not be null
    * @invariant does not change the number of bugs
    */

    Well that is the comment block, not all of it because there is some OCL in there, but I thought I'd leave something for Google. The point is that the description describes exactly what the method does, it also says what the caller must do or face the consequences, and what the caller can rely upon when the method returns.

    And for any one who says comments aren't required if you write the code well enough... you are a muppet. Interaction via interfaces is a basic tennent of coding, .h files anyone ? You shouldn't have to look at the code.

    --
    An Eye for an Eye will make the whole world blind - Gandhi
    1. Re:Design by Contract by binkley · · Score: 1

      There's a drawback to your example comment as presented: reflowing the block loses the leading @'s at the start of each line. Instead, you might consider a blank line between significant elements, thus:

      /**
      * Get the Bug description for the given Id
      *
      * @pre id must be > 0 and less than BugList.lastId(), the highest bug number
      *
      * @post The return must not be null
      *
      * @invariant does not change the number of bugs
      */

      --
      --binkley
  70. Taligent Rules and High Energy Physics by Anonymous Coward · · Score: 0

    In high energy physics, lots of code is written for very large experiments such as RHIC and LHC. A lot of it gets done using Root(root.cern.ch), which is a C++ framework for building stuff and also an interpreted interactive data analysis package. They use the Taligent rules for naming and the K&R rules for style:
    pcroot.cern.ch/TaligentDocs/TaligentOnline/Docum en tRoot/1.0/Docs/books/WM/WM_63.html#HEADING77

  71. Code for humans not machines by saphena · · Score: 1

    I have encountered lots of code, with and without comments, written by people who have mastered the finer points of their chosen programming language and, more often than not, their code is all but incomprehensible to us mere mortals.

    Some languages cope with this better than others. C/C++ lends itself to instant double-dutch in the hands of an "expert" coder whereas VB tends to make sense despite the efforts of the coder.

    My rule would be "code for the human reader". The machine will cope with the code however well or badly it's written but humans can be left clueless.

    I would also echo the comments above which call for comments denoting *why* you're doing something rather than *what* you're doing. I can almost always figure out the what from the code itself, why is a different matter.

  72. comment the data structures too by digital+labourer · · Score: 2, Informative

    It is not only executeable code that can benefit from comments. In particular any numeric fields should have a units comment (e.g. m or m/S). It can be quite time consuming to deduce the units from the code.

  73. Document abnormal behaviour by tve · · Score: 2, Funny

    1. Adopt some set of coding conventions. For instance, always return 0 on success/in the normal case.

    2. Use informative variable and functionnames. Short names are preferred, but make sure it's clear what you mean. If it's impractical to fit all the required info into the var- or functionname, add a comment explaining the intended purpose of the variable/function.

    3. Use small functions! Split actions up into logical steps. In combination with 2 this will help make your code a lot more readable, removing the need for many comments. Like Linus says: "The maximum length of a function is inversely proportional to the complexity and indentation level of that function."

    4. Document any abnormal behaviour. For instance, if you've adopted the convention that functions return -1 on errors and you have a function that differentiates between different errors by returning either -1 or -2, document what the abnormal return values mean.

    5. If the overall purpose of a group of functions (e.g. in one sourcefile) isn't obvious, add a general comment that explains the big picture. Code is much more readable if you know what it's trying to do.

    --

    If there is hope, it lies in the trolls.
  74. it is well commented code... by sirius_bbr · · Score: 1, Funny

    when you still know what is does after 6 months!

    --
    this sig has intentionally been left blank
  75. Great now I can write APL code by pommiekiwifruit · · Score: 1

    in C++... let's find some of those old IBM keyboards with all the symbols on them...

  76. Good Naming and Factoring are More Important by Anonymous Coward · · Score: 1, Informative

    Too many comments can be just as much a sign of bad code as too few. When a function or methodis filled with paragraph-long comments explaining what it does, that's often a sign that you should rename some variables, or factor out parts of the work into separate, well-named functions or methods.

    Don't be afraid of having long, descriptive names. They go a long way towards making the code more clear without using comments.

    Sometimes, even if you break a function into several subfunctions that it calls in order and which are called nowhere else, that can help readability, as long as you draw the boundaries intelligently.

  77. Work from the top down by Daetrin · · Score: 2, Interesting
    I recently ran into two functions in the code base I'm using that were titled "ObjectTrackDirection" and "ObjectTrackToDirection". The similarity in names was annoying, but the criminal part was that neither function had comments indicating what they did, or what the difference between the two was. In fact, the only comment in either section of code was on one line that was duplicated in both pieces of code, and which said "not sure why this is needed". This did not give me a great deal of confidence as I started out trying to decipher what exactly these functions were supposed to accomplish differently.

    No matter how clear you think you made the name of the function, there should be a comment explaining what the fuction is supposed to be doing. If the function accepts a lot of flags or variables you should briefly explain what they're each used for.

    Knowing what the function is supposed to accomplish is a big step forward, even if there are no other comments at all.

    If you're still willing to keep at it, start commenting the big blocks of code in the same manner. What are you trying to do with this loop? Why are you testing for these cases in this if statement, and if it succeeds, what are you trying to do inside of it?

    Always go in favor of more comments. I would rather have to skim by a dozen comments that I don't need to read than be left hanging for the lack of one comment when something goes wrong.

    And finally, always use whatever comment system your source control program uses! Even if it's just "I did some stuff to fix some problems with A," because if I later find out that a particular case of A is broken, I don't want to have to do a diff on every single code change made since the last time I knew that case of A worked.

    --
    This Space Intentionally Left Blank
  78. My favorite comments by bentini · · Score: 5, Funny
    I personally despise comments such as:

    i++; //increments the variable i

    I think that they are unclear and do not properly explain the situation. Remember, you're writing so people can UNDERSTAND the code, not so that you can impress them with how smart you are. Instead, strive for a comment like this:

    i++; /*changes the value stored in the space referred to by i to be the sum of the old value stored in the space referred to by i and the constant 1. Note: In C, this may cause what is known as a "silent overflow" if the value is too large, and go so far as to make a large positive value into a larger negative one. Oh my!

    This way, people who read your code not only understand your program, but all programs. I really think that each function you write should repeat a semester's worth of computer science theory and programming practice, so that anyone who reads your code will learn from it. Remember, not everyone knows idioms, and why should they? And since we all write open source on slashdot, many novices are going to have their introduction to any computing environment by looking at the code you write at any point.

    Your most humble and obedient servant,
    Dan

    1. Re:My favorite comments by Rik+Sweeney · · Score: 0

      Jesus, that's one hell of a comment. It never gets closed, I'm suprised your post appeared.

    2. Re:My favorite comments by mpsmps · · Score: 1

      The most famous comment I know of is "You are not expected to understand this code" in the Version 6 Unix Sources.

      I am not sure if it is a good comment or a bad comment. It certainly let me know that the lines needed careful examination.

    3. Re:My favorite comments by curunir · · Score: 2

      I like to take the opposite approach. I assume that any engineer reading my code is capable of understanding code. So I write my comments in code...even sprinkling comments in amongst my code. Take this, for example:

      int foo(int bar) {
      // report.print() if foo =~ /^[0123]$/
      if(0 == bar) // {
      printf("bar equals zero");
      /*} elsif(1 == bar) // {
      printf("bar equals one");
      } elsif(2 == bar) */ {
      printf("bar equals two");
      //} elsif(3 == bar) {
      printf("bar equals three");
      }
      }


      It should be immediately obvious to any engineer what foo(1) does.

      --
      "Don't blame me, I voted for Kodos!"
    4. Re:My favorite comments by bentini · · Score: 1

      Yeah. It's not foo(1). That's not going to be an application. It's just a function call.

  79. like a book on nutrition by g4dget · · Score: 3, Insightful
    Code Complete and similar books strikes me as being a bit like books on nutrition and dieting: they tell you what is good for you and they give you some tips on dieting. But most people who read them end up eating junk food anyway because they just don't have the time to do it right.

    By all means, read Code Complete--its suggestions are sensible. But the real culprit when it comes to poor software are time and resource pressures, feature creep, and other environmental factors. Maybe at least the book will let you recognize when your project is doomed and leave; McConnell seems to have done that--he isn't at Microsoft anymore.

    1. Re:like a book on nutrition by Anonymous Coward · · Score: 2, Insightful

      While you're true, somehow you are true "after the fact". What I mean is you can always find a programmer telling you that his code is a big mass of underdocumented shit not because his will but because time constrains and feature shifting from his boss/client.

      And they are usually rigth, *BUT* to-date I *NEVER* haven't seen the situation of a programmer being fired when it is obvious that he *is* productive *and* he has done his best and even then it has been imposible to achieve a goal (because stupid asumptions/time lines from management). This being said there *is* a real problem from the fact that programmers like the *most* programming, that is, writting down lines of code, not documenting, not commenting, not designing prior to code, no nothing but code. Under these circumnstances, when time forces them to cut down something they end up cutting down from the comments/desing side, *not* from the coding one.
      Now the difference results on...

      Case A (usual case)
      for(foo=0;foo=7;++foo)
      {
      bar=foo*2; pee=bar/3;
      }
      -BEEEEP TIME-LINE REACHED. IT'S THE WORK DONE?
      -Yes boss, it is.

      Case B (good way)
      /* Testing if current they of the week is workable, so subrutine playable_day is aplicable */
      for(weekday=SUNDAY;weekday=SATURDAY; ++weekday)
      {
      }
      -BEEEEP TIME-LINE REACHED. IT'S THE WORK DONE?
      -No boss, it isn't. Look at my code, I worked as much sensible code lines as anyone else but has been *IMPOSSIBLE* to finish. I told you this needed two days, not only one.
      -OK: if it *REALLY* can't be done, it can't be done. Continue, please.

      What I mean is that programmers themselves are as guilty as management because when management forces a stupid time-line, they stupidly do the wrong things so work seems to be rigthly done (like avoiding coding conventions, documenting and the like). If what can't be rigthly done is not done at all even management will make better asumptions next time.

      So:
      1/ Sensible variable-names; use name-sensible constant as much as you can too;
      2/ *What* the code does can be understood from the code itself; comments should focus on *why* (there are exceptions, of course... Perl's regular expresions are a good place about commenting not only why, but how too).
      3/ If at all possible COMMENT FIRST, THEN CODE. DON'T LEAVE COMMENTS TO THE END, or you will never write them down.
      4/ If at all possible use any autodocumenting tool (javadoc, doxygen, etc.) while they still need some discipline from your side it's usually far (psicologically) easier to maintain documentation up-to-date with them than if you're expected to go to an outlined document and do it.

      Well, my two cents.

    2. Re:like a book on nutrition by Aceticon · · Score: 2

      But the real culprit when it comes to poor software are time and resource pressures, feature creep, and other environmental factors.

      THAT explains the "This is a ugly hack" comments i keep finding when going through somebody else's code!!!

  80. blah.c by Ketnar · · Score: 1


    Seen in an actual program...

    "//This code is not commented so that you may
    //comment it to your own liking.
    //plz do not send me back commented code!"

    I don't know weather to laugh, or cry.

    --
    My new top secret key -> C>N|KB
  81. Design decisions by Anonymous Coward · · Score: 0

    Document the design decisions in the comments.

    Any time you code, you make many large and small decisions about why the code should be a particular way, and about why it must not be some other way. These are rarely deducible from the code itself and you need to write them down.

    Code is very fluid these days, because coding is cheap and easy compared to specification, testing and external documentation. People refactor because they can, not because they must, and because it usually improves things. Recording the design decisions and underlying reasoning protects your code from ill-informed refactoring.

  82. Some examples of bad comments by Dr.+Tom · · Score: 2

    i++; /* increment i */

    a = b; /* save the value of b */

    /* this function calculates theta. */
    float theta(char **p, int d, float *(*fn)(int))
    {
    ...
    }

  83. Two basic rules by edhall · · Score: 2

    1. The code should be written so that it is clear what it does from the code itself. Descriptive identifiers, well-focused classes and single-purpose functions all help. Careful use of white space (e.g. dividing code into "paragraphs") helps. If it isn't clear what the code does, rework it until it is clear.
    2. The code should be well-commented to explain why it does what it does. Explain how it fits into the overall scheme (and make sure you've explained that scheme).

    One way of doing this is to have a comment block introduce each class and each function. If these comments are not in a standardized format, at least make them consistant. If you're using a non-obvious algorithm, this is where you should describe it, in full. If it is spectacularly non-obvious, provide a reference to a separate doc. And if your project has created design documents prior to coding, provide references back to those docs.

    Obviously, the way code is "chunked" in item (1) has a lot to do with how it gets documented in item (2), and vice-versa; I put them in that order because it made it easier to explain, though in practice much of (2) is done before (1). But the two have to be taken as a whole and ultimately completed as a whole.

    I don't know how many times I've seen comment-as-you-go code where the comments disagreed with the code, and it wasn't clear just what a function was trying to accomplish. But if I understand the goals of a piece of code, and reasonable care has been taken in naming and organizing it, in-line comments just get in the way.

    -Ed
  84. External API by Snake · · Score: 1
    I am currently using a third party library with a badly designed API.

    It uses parameters in a way that does not make sense often.

    So, before calling one of those (more obscure) functions, I copy/paste the list of valid parameter just before it.

    This way, should I need to understand the intent of the call and wether it is valid or not, I just need to look the comment. [over the last two months, already saved me hours of debugging!]

    Caveat: This works only if the function is seldomly called in the code. If called often, you're better off memorizing it.

  85. Style. by NullStream · · Score: 1

    This page http://www.openbsd.org/cgi-bin/man.cgi?query=style &apropos=0&sektion=0&manpath=OpenBSD+Current&arch= i386&format=html is a good start.

    Any/all companies that write or edit code should have documents like this. Then again I also think all code should be peer reviewed and tested before it's considered stable for use. But then again I'm an idealist and know the world works exactly the opposite way.

    --
    "Survival of the fittest Max, and we've got the fucking gun!" - Pi
    1. Re:Style. by Anonymous Coward · · Score: 0

      no longer exists

      -Anonymous Troll says "fuck you jewish nigger fags- enfilade.org/pics"

  86. Formatting by Dr.+Tom · · Score: 2
    Sometimes you can use tools that help write docs based on specially formatted comments, but for most comments, all you want are:
    Paragraphs,
    written with complete sentences,
    using vanilla formatting.
    It is not widely recognized, but maintainability arguments apply to comments as well as code. When the code changes, the comments have to change too, and they should be easy to modify. That means no fancy boxes or other bizarre formatting. I don't care if your editor can handle automatic double column star boxes, not everybody's can, and to be portable (yes, comments have to be portable), you should use the absolute minimum formatting. For example:
    /* This is a block comment. It describes the block of code below. Notice that it uses no special formatting, and when I change the comment, I can hit the "reflow" button in the editor and it'll get reformatted like any other block of text. */
    Use inline comments sparingly. Write complete, descriptive sentences at the block level. It's also good to put blank lines before and after comment blocks.
  87. Commenting "null" code by Zocalo · · Score: 2
    There was a similar discussion here on /. not so long ago, and one post from it stuck in my mind as being perhaps the most worthy +5 post I'd read for a *long* time.

    Basically someone had been going through code and found an entire subroutine commented out with the rider "This doesn't work". The original poster went on to say (s)he'd initially missed the point and thought the commenter was dumb, until the penny dropped - this would be a massive time saver if someone else thought of the same routine.

    I have to admit, I'm not sure if this commenting practice would have occured to me - until I read this I'd always deleted broken code. It's definately something to bear in mind next to you waste a few hours working on a flawed algorithm.

    --
    UNIX? They're not even circumcised! Savages!
  88. You are not expected to understand this. by dc.wander · · Score: 1

    here's an example from an expert. Dennis Ritchie wrote the following code in the Sixth Edition of UNIX back in 1975:

    /*
    * Switch to stack of the new process and set up
    * his segmentation registers.
    */
    retu(rp->p_addr);
    sureg();
    /*
    * If the new process paused because it was
    * swapped out, set the stack level to the last call
    * to savu(u_ssav). This means that the return
    * which is executed immediately after the call to aretu
    * actually returns from the last routine which did
    * the savu.
    *
    * You are not expected to understand this. <------------ *ahem*
    */
    if(rp->p_flag&SSWAP) {
    rp->p_flag =& ~SSWAP;
    aretu(u.u_ssav);
    }
    /*
    * The value returned here has many subtle implications.
    * See the newproc comments.
    */
    return(1);
    but in all seriousness, i have found that the two most useful tips when commenting code are as follows:
    1. write comments for code in blocks, describing the function of the code to follow (ex: right before a nasty looking "for" loop, explain what it does)
    2. use variable names that communicate meaning; the code will end up commenting itself this way
  89. Experience many languages by RQ · · Score: 0

    Good commenting should describe your objectives and the algorithm (i.e. procedure) you will use to reach those objectives. So like algorithms it should be independent of any language (including C). If the comment is enough for someone to re-implement the procedure in another programming language, then it is spot on.

    To this end, having experiences with many languages helps. It also follows from this, that good comments will, in effect, teach someone how to program in a language. It also follows that comments should not include language dependent phrases like 'functions', 'pointers', 'int' or variable names. It also follows that blatent comments like

    // Increase the number of sales
    number_of_sales++;

    are not superfulous. Comments like these also make it convenient to someone jumping to the middle of code, see what the purpose of each Variable is, without having to search for the declaration, wherever it may be. This all flows from the tutorial nature of this kind of approach to commenting.

  90. Code Commenting by j_kenpo · · Score: 1

    An excerpt off of a web page from a old college professor of mine states:

    When should you comment.
    You should comment your code as you are writing it, when what you are doing is fresh in you mind.
    If you wait to comment it after everything is written, you may have forgotten why you did something a particular way or what a complicated section of code does.

    What should you comment.
    It is possible to over comment code. Every line of code does not need a comment.

    The key things you should comment are:

    Put identification comments at the beginning of every source code file.

    Each function, including main, should have a comment before it stating its purpose, even if it is a one line function.

    Anytime you are doing something complicated in your code. If you can't glance at it and know what it is doing, comment it.

    Anytime you are doing something new. I hate to learn things twice, so when I use a library function that I have never used before, I put some extra comments in the code, so I don't have to go look up the function the next time I need to use it.

    He is a wise man, so I still use his page as reference for other things as well. It contains tons of info on C++ coding style and C++ in general. If interested, his site is at http://home.satx.rr.com/rdevore/sac/

  91. Comments are only a part of the answer by PinglePongle · · Score: 2, Insightful
    In any development effort involving more than 1 person, comments are not enough.

    You should seriously consider :
    • coding standards outlining naming conventions, indentation, common usage, commenting requirements etc.
    • design and code reviews of all non-trivial work products
    • documentation standards (see the book review on agile modelling) - you should document the stuff that isn't obvious, and keep the documents up to date
    • automated unit tests which allow any changes to the code to be tested (yes, I stole that one from the eXtreme Programming guys).


    The problem with comments is that they explain what the code does, but all too often the "why" - the structure of the program - is not obvious by looking at the comments - it's like trying to work out a streetmap by looking at the names in the phonebook.

    I took over a large project from a major consulting firm; much of the code was immaculately commented, but the overall structure of the design was almost impossible to fathom; the documentation was out of date and incomplete, and everybody had a slightly different view of how things worked. Whenever we fixed a bug or made a trivial change, we'd hold our breath just in case the trivial change had unforeseen consequences somewhere else in the system. A simple class diagram and database schema would have been more useful than most of the comments. Unit tests would have saved us literally hundreds of hours of pain...

    Code Complete, a book by Steve McConnell is a great read on this subject; I also recommend "Agile Development" by Cockburn.
    --
    It's all very well in practice, but it will never work in theory.
  92. Tracing by slim · · Score: 2

    I write server code that will be run by another part of the organisation, on machines that I don't have access to. As a result it's useful to be able to turn on extremely detailed tracing so that the guys running the service can send us traces of sessions that didn't behave right.

    I find that the trace calls in the code are often as good as comments, in that someone browsing the code could use the traces to work out what's going on.

    e.g.
    for(lc=0;bytes_left>0;lc++)
    {
    trace("In main parsing loop, chunk %d, %d bytes remaining to process",lc,bytes_left);
    }

    ... tells us the purpose of the loop, and the purpose of two variables. Clearly putting a real /* comment */ next to the trace line would be redundant.

    I think even if I weren't tracing, I would place comments in pretty much the same places.Of course this isn't all the commenting I do -- there are certainly comments required above and beyond these, such as detailed descriptions of what a function should do above the declaration.

  93. Commenting Code by lemkebeth · · Score: 1

    Some advice.

    Use meaningful variable names:

    like:

    string iFileName;
    (Short of input file name)

    Comment your functions:

    For example put a header before all your functions that says what the function returns, its purpose and any arguments.

    Don't explain how the code works in a comment but, what it does.

    An example of a funtion header:

    //inputFile Function
    //Arguments:
    //
    //string aFileName
    //ifstream iFile
    //
    //Returns: bool
    //
    //Description:
    //
    //The function inputFile takes a string as an
    //argument and an ifstream. The ifstream is
    //passed by reference and will contain the file
    //data once opened. Returns true if the file
    //was opened.

    Note: Use fewer 'junk' characters huh? Stupid submit form (especially with this subject).

  94. WHY not WHAT by mikehunt · · Score: 2, Insightful

    Certainly the most important comments are those that say WHY something
    is being done rather than WHAT is being done.

    If the code is written clearly, in sensible size functions and with
    meaninful variable and function names it is easy to see what is happening.
    It's the WHY that often escapes even the original author some
    years down the line.

  95. commenting bad. by Anonymous Coward · · Score: 0

    commenting code is bad, it ruins the beauty of a project. The need for commenting comes from bad design, carless metaphors, etc.. good source code needs no comments as 'code should show itself'

    ok, yeah.. a bit extreme, but i like to think this way.

    1. Re:commenting bad. by Fnagaton · · Score: 1

      That's an example of bad code though and shouldn't appear in a program anyway.

      --
      Martin Piper
      Owner - ReplicaNet and RNLobby
  96. bah by Anonymous Coward · · Score: 0

    what a bunch of nerdy whiners.

  97. The Code Dictator by Knacklappen · · Score: 1

    I have become somewhat a Code Dictator to me fellow workers because I strongly encourages them to write Beautiful Code (they will call it mobbing, though... ;-) nevermind).
    What I mean by this is the usual:
    - Clear names for all variables, functions, procedures (etc), commented if necessary
    - Comments, comments, comments
    - Avoid Spaghetti Code (tm)
    - Avoid recursive programming (the code maintainers will thank you)
    - Avoid fancy loops with stop criteria based on dubious flags
    The rule of thumb is: "Do not comment everything, you co-workers are not stupid. Comment that much that you, after not having worked with the code for at least a year, can at the second glance understand what it does and how you can modify it."
    This of course is hard for a beginner, but the more practice you get, the better you become. The key is to not just dropping in comments there and there, but to consistantly and consequently document your code.

    --


    Excellence: Moderate (mostly affected by comments on your karma)
  98. Well-commented code... by Serial+Troller · · Score: 0, Funny


    int main (int argc, char argv[][]) {
    int j;
    int i = 7; /* FIXME: should be 6? */
    char *h = argv[1]; /* FIXME: segfault if no argv[1] */

    for (j = 0; j < i; ++j) {
    /* TODO: Make this actually work */
    q[j] = malloc( sizeof( foo_t )); /* FIXME: often segfaults */
    }

    /* FIXME: too drunk to figure this one out now */
    memcpy( p, &((*((x+i)+k[i->e]).sin_addr),
    sizeof(&((*((x+i)+k[i->e]).sin_addr)));




    /* FIXME: too much whitespace */


    return 0; /* FIXME: always 0? */
    }

    --

    STOP ME BEFORE I POST AGAIN!

  99. Go read this book : by Anonymous Coward · · Score: 0

    The Pragmatic Programmer - by Andrew Hunt & Davis Thomas

  100. Things to bear in mind by Rogerborg · · Score: 5, Insightful
    • All modern compilers that I know of can handle symbol names of at least 256 characters, not the old 31 character limit.
    • The most widely understood naming convention is the English language.
    • If you feel that you have to comment the purpose of a method, function or variable when you declare/define it, why isn't it necessary to comment every use of it as well?
    • The time spend typing or reading characters of code is insignificant compared to the time spent comprehending it.
    • Whenever you write code that requires any interpretation at all, you cost yourself developer time, and that's a precious resource.
    • If you comment something that the language supports, you're not using the language.
    • People who slate you for using over-verbose naming are really saying "You shouldn't need long names to understand my code." That's a solipsistic ego trip, as the target audience isn't or your peers or anyone in a code review or with white box knowledge of the code or system. It's the poor contractor shmuck five, ten or fifteen years down the line who has to come to your code stone cold on to fix a critical bug with a deadline breathing down his neck and a hankering to get the hell out of the office and have some semblance of a life. Write for the benefit of that guy, because one day you'll probably become him.
    • Every time you write a comment, you introduce a potential headache for the maintainers. Ask yourself when the last time you updated a comment in production was, even when it contradicted the code.

    Here's the rules I use:

    • A function/method name is too long when it doesn't fit on a typical screen. 80 characters is about my limit.
    • If I find myself thinking that I'd better comment the purpose of a variable, I incorporate the comment in the variable name. As a side effect, that also tends to give a good feel for how important a variable is.
    • Yes, we all know that "i" is a counter, but what is it counting? It costs me perhaps five seconds to use a variable that describes what is being counted. Then it costs a reader an extra tenth of a second to read it, but that saves a quarter of a second to translate to what it actually means. Let people read your code, don't keep making them stutter and recap.
    • Describing the function and purpose of "input" and "output" parameters in a function description comment is a hell of a long winded way of typing "const WhatTheParameterIsActuallyUsedFor". You only have to type it once; that's what copy and paste is for. Don't comment expected values, assert(them).
    • Completely self commenting code is an unrealistic ideal. But get as close to that ideal as possible, and don't be afraid to change comments when you change the code during maintenance. If you're sure what the code deos, you should have no problems doing that. If you're not sure what the code does, then find out.
    --
    If you were blocking sigs, you wouldn't have to read this.
    1. Re:Things to bear in mind by Forkenhoppen · · Score: 1

      It's true that we do have 256 characters to play with these days, for variable names, but class names are a bit different. One shouldn't forget that if you're combining these in any way, using templates, then your variable length can double or triple quite easily.

      I'm currently using some code at work that consistently draws errors from the compiler because the code was written with long class names, and makes intense use of the stl. Visual C++ chokes on it occasionally, but the real bugger is that it's a pain to figure out what's actually going on during debugging whenever your variable types scroll across the screen a couple of times.

      Your suggestion concerning loop variable names is good, but I would suggest an exception to that rule. If the loop is smaller than six statements, then don't bother naming it something special; i is good enough. It can actually be more confusing at times to name it something else.

    2. Re:Things to bear in mind by Anonymous Coward · · Score: 0

      If you're going to use words like "solipsistic" perhaps you should add a comment to explain what it means. Don't want your comment to sounds like an ego trip, do you ?

      A function/method name is too long when it doesn't fit on a typical screen. 80 characters is about my limit.

      When this means that a reasonably complex 'if' or 'while' statement now extends over several lines, and less actual code can be displayed on the screen at any one time, this is hindering, not helping, the comprehension of that code. Did you mean you write code for people who have to use 80-character screens ? You should. You may have a better development environment, but the person debugging it later, perhaps on site, may have nothing better than a 80x24 console on which to view your code.

    3. Re:Things to bear in mind by Zaffle · · Score: 1

      Ah! I spot another information systems graduate.

      Do you ever find your coworkers planting explosives under your car due to your insane coding practices?

      > * A function/method name is too long when it doesn't fit on a typical screen. 80 characters is about my limit.

      Oh for fucks sake! I don't even code on with 80 char wrap, I use 76 chars! an 80 character function name?!? What do you write? Use_This_Function_If_You_Want_To_Increment_A_Varia ble?

      > # Describing the function and purpose of "input" and "output" parameters in a function description comment is a hell of a long winded way of typing "const WhatTheParameterIsActuallyUsedFor". You only have to type it once; that's what copy and paste is for. Don't comment expected values, assert(them).

      Right, now that sounds like fun. Lets take for example strtok (Yes, I know strtok is a bad function, but I'm proving a point). How are you going to explain, in a variable name, that strtok will screw with your input, so don't pass it a buffer you want?

      AS for your implication that comments are no good because they aren't changed, maybe *that* is something that needs to be changed. Personaly I find describing the purpose of the function at the top of it to be a good thing(tm). And if the purpose of the function changes, then of course you need to update the comments.

      You seem to be implying that the less comments you have, the better!? Self commenting code is not a way to avoid documenting the code. There are things that you can not convey with only variable names and function names.

      You want an example of why you need to comment your code. ~/src/undernet_ircd/src/channel.c:set_mode()
      Now *THATS* a function in badly need of commenting. It doesn't matter what you rename the variables, the function is inheriently complex. Yes, it needs a rewrite, but its also a good stop gap in the meantime to commment it.

      --

      I use to have a funny sig, but slash cut it off, and I forgot what the punchline was.
    4. Re:Things to bear in mind by rodac · · Score: 1

      Length of symbol names is not a matter for the compiler but it is something depending on the linker. Early ANSI C compilers/linkers used to have an 8 character limit on all symbols. Truncating anything after the first 8 characters. Thus foo45678 and foo456789 would be collapsed into the same symbol/object by the linker.

    5. Re:Things to bear in mind by rodac · · Score: 1

      >A function/method name is too long when it doesn't fit on a typical screen. 80 characters is about my limit 80 characters !!! [hand starts searching for device for rapid acceleration of metallic-semispheres by means of hasty expansion caused by chemical carbon-sulphur-nitrogen reaction] Please tell me that 80 characters is an exageration, or do you mean that there are actually decelleration-objects/misguided-programmers out there that actually use such abdominations? I thought hungarian notation was bad. You have enightened me.

    6. Re:Things to bear in mind by bluGill · · Score: 2

      Maybe YOU have 256 charicters to play with, but I still have to use old systems with only 6 unique charicters to play with. Please make sure your variables and functions are unique in the first 6 letters. This isn't as bad as it sounds, I can make my variables 1024 charicters if I want to, the compiler will just silently truncate them to 6, so I can still have the long names, I just have to be careful to make the first 6 charicters unique.

    7. Re:Things to bear in mind by maunleon · · Score: 1

      One other thing I like commenting in C/C++: Where blocks end. For example:

      ...loop1....
      {
      ...loop2...
      {

      } // loop2 ends here

      } // loop1 ends here

      This makes it so much easier to match brackets! I absolutely insist on this rule for my own benefit. When you have a loop, a switch statement, and a few ifs, it can be very helpful.

    8. Re:Things to bear in mind by Amazing+Quantum+Man · · Score: 2


      But then how can you use hungarian notation?

      char *lptstrSomeString, *lptstrTheOtherThing;
      </HUMOR>

      --
      Fascism starts when the efficiency of the government becomes more important than the rights of the people.
    9. Re:Things to bear in mind by metamatic · · Score: 1
      * Every time you write a comment, you introduce a potential headache for the maintainers. Ask yourself when the last time you updated a comment in production was, even when it contradicted the code.


      All the freakin' time. Sheesh, what kind of half-assed slipshod work do you turn in?
      --
      GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
    10. Re:Things to bear in mind by Anonymous Coward · · Score: 0

      Ask yourself when the last time you updated a comment in production was, even when it contradicted the code.



      I see a contradiction here. Here you are saying people are reluctant to change comments when code is maintained. So when code is maintained, the comments no longer are accurate. IMHO people are far less likely to change a variable name (or worse yet, a slew of them) whose purpose has changed than they would a comment. Just a thought.

    11. Re:Things to bear in mind by YourGarbageMan · · Score: 1

      I don't know about this long variable naming thing. Certainly unique and meaningful names are appropriate but I've seen this taken to an extreme and it was very cumbersome code to read and modify. We once had a contractor whose variable names were literally entire english sentences.

      Something like this:
      if (theUserHasRequestedToFaxTheDocumentAndThePrinterH asAFaxModem)
      {
      if(theUserHasRequestedNotificationAfterTheDocument Has BeenSuccessfullyTransmitted)
      {

      etc. I am not exaggerating. I probably wouldn't have believed it myself except that I saw it with my own eyes.

      I'll tell you why this sucks. You can't tell what the variable is at a glance, you have to read the whole dumb sentence. This makes analyzing the code a big pain in the ass especially when all of the variables are like this and some of them start or end with very similar phrases.

      Ex.
      theUserHasRequestedToFaxTheDocumentAndThePr interHa sAFaxModem
      theUserHasRequestedToFaxTheDocumentWit hTheStandard FaxHeader
      theUserHasRequestedNotificationAfterThe DocumentHas BeenSuccessfullyTransmitted

      Now imagine pages and pages and pages of code using names like this. Excruciatingly explicit does not necessarily mean easy to understand.

    12. Re:Things to bear in mind by ahde · · Score: 2

      never take away i
      it'll cost you too many enemies

      instead, do

      for (i = 0; i < LASTROW; i++)

      or if you need to compare complex datatypes:

      while (! isLastRowPopulated(myTable[i]))

      or

      while (! Table.isLastRowPopulated(i))

    13. Re:Things to bear in mind by Anonymous Coward · · Score: 0

      much preferable to

      for (rowOfMyTable = 0; rowOfMyTable < MAXROWS; rowOfMyTable++)

    14. Re:Things to bear in mind by Popocatepetl · · Score: 1

      i stands for "index". It is not appropriate to describe what the index is indexing in the index variable's name because the index is not the thing being indexed!

  101. My take on it by SashaM · · Score: 1
    I think it's pretty simple:
    • Class comments: describe the purpose of the class. If applicable, give sample usage.
    • Method comments: describe the purpose of the method. Describe how it behaves when given "interesting" (potentially bad) values (doing this one will also make sure that you are handling those values somehow).
    • In-code comments: If you don't want to break relatively unrelated parts of the code into different methods, put several empty lines between them and comment what each part does. Comment and explain anything that isn't obvious.
  102. No such thing as too obvious by Christopher+Bibbs · · Score: 2

    If a support developer doesn't know what a little used third party function does and I don't comment it, who loses? Short answer: everyone. Support development team loses, I lose, QA and/or tech support loses as they wait for a fix.

    Now, what if I (like so many other programmers and yourself apparently) have my head firmly up my ass so I think all my code is obvious in function and I only need to explain my intent? Well, after being humbled a few times, I'll figure out that it is more useful for everyone if I just use lots of comments, even things that may seem obvious once written, the role of support is vastly improved and my need to help with support is greatly reduced.

    Of course, maybe you like doing support programming, it takes all kinds I guess.

  103. Error handling makes the code hard to find? by fireboy1919 · · Score: 2

    I would say that this is part of the problem with code that you might create - you're hiding the implementation section.

    The best way to produce the code is to create a clear division between functional elements, a clear division of data elements, and a clear division of implementation and error checking. What I mean by "division" is very dependent upon the language. If you've got an OO language its clearly easier to define the difference between data types using objects than it is in a weakly typed functional language.

    However, all of these things can be done with any language. If error checking is taking a lot of space, put it in a separate function, or at the very least put some sort of divider that makes it obvious where the code begins and the debug stuff ends.

    The best comment is often well structured code. Comments only make it easier to understand those rare algorithms that can be explained in a non-algorithmic way. (Actually these aren't extremely rare. FFT comes to mind.)

    --
    Mod me down and I will become more powerful than you can possibly imagine!
  104. Re:reply by Serial+Troller · · Score: 0, Funny

    Didn't you mean:

    REM Since you are slow, you failed. Commit Hari-kari

    ...?

    --

    STOP ME BEFORE I POST AGAIN!

  105. Too many comments? by erpbridge · · Score: 2

    A couple years ago, I took a programming class at a local community college. The whole class got failing grades for the first few assignments, even though the program did what it was supposed to do and had 4 lines of comments per routine.

    Turns out no one got any higher than a C until they made a whole page of comments for each line of code. On top of that, the teacher demanded the code be printed out.... I remember that I ended up turning in a 100 page document once, whereas the program was only about 90 lines.

    I think that's a little too much commenting, but he still said more comments needed to be made. I understand where he was coming from (he used to program in Cobol, and this was in 1998, when everyone was scrambling for patching uncommented Y2K code), but there's such a thing as overcommenting.

  106. comments are extra by dollargonzo · · Score: 1

    code should be self explanatory. the variable names should dictat what you are doing, and also, the way the code is broken up is also important. Use comments sparingly, for example a nice one liner (terse but not cryptic) in front of very 5-10 lines block that does ONE(1) thing.

    another good time/place to put comments is things that you had a lot of trouble understand (like a description of a complex algorithm). in this specific case (algorithms) it is often useful to include a reference to the place you got the algorithm. oftentimes, if you link to a website (even if it is NOT there when others look at it) at least if it IS there, a good explanation exists (at least better than the one you hopefully gave).

    finally, put LONG explanatory comments in front of bugs that took you FOREVER to debug. by this i dont mean put a comment where you accidentally typed x instead of y! if there was an algorithmic problem, IOW a problem with your logic somewhere, and it took a while to figure out the RIGHT way to do it, the person reading it is probably going to have just as hard a time understanding what is there.

    QED

    --
    BSD is for people who love UNIX. Linux is for those who hate Microsoft.
  107. My preferences by Piquan · · Score: 2, Insightful

    First off: never underestimate the value of putting research notes in your comments! A simple "This averages O(NlogN), but is worse if the data is presorted" can really make somebody's day.

    Now, the long rambling description of how I like to see comments:

    Every file should have, right after the boilerplate (after copyright, before #includes etc) a brief description of that file.

    ;;; This implements the SAMHAIN algorithm for performing
    ;;; constraint propogation. The caller passes a list of nodes...
    ;;; [Description of what SAMHAIN does ommitted for brevity on /.]
    ;;;
    ;;; The algorithm here is loosely based on the one in "Paradigms of
    ;;; Artificial Intelligence Programming", chapter 17. There, it was
    ;;; used as part of a vision algorithm, but it's still labelling a
    ;;; graph by constraint propogation.

    Name your functions something concise, and accurate, but not necessarily precise. You don't need sort-sequence-on-predicate when sort will do just as nicely.

    The same goes for variables. Using i and j for numeric iterators is fine, but you rarely should use foo and bar. Most variables should also have a short (usually <20 char) comment, although globals should have a longer comment, possibly describing how they're used.

    Every function should have a docstring. In some languages, such as C, this is normally comments at the beginning of the function. In some, such as Lisp, there are conventions for including the docstring in a manner that the compiler will recognize.

    The first line of the docstring should be a self-contained sentence that tells what the function does. The rest can go into detail about how to call it. The purpose of this bit is "what does a caller of this function need to know". Wait on the implementation notes for now... we want the caller information to be all one, tidy package.

    (defun sort (predicate sequence)
    "Destructively sort SEQUENCE.
    Predicate should be a function of two arguments, and should return T if its first argument should precede the second."

    If your language does have docstring support (either directly or through an external tool), then implementation notes belong in comments, not the docstring. Either way, put them after the caller information, so that somebody who just wants to use your function doesn't need to read them.

    (defun sort (predicate sequence)
    "Destructively sort SEQUENCE.
    Predicate should be a function of two arguments, and should return T if its first argument should precede the second."
    ;; We use a modified partition-exchange sort.
    ;; See also Hoare, C.A.R., "Quicksort", The Computer Journal, 5:1, pp. 10-15, 1962.

    As an extention of this idea, functions should begin with a brief overview of how they work. (For extremely simple functions, this may be omitted.) If the function implements a formal algorithm, such as a sort or hash algorithm, then a formal description is certainly not out of place, or give a reference. This is also a good place to note any behavorial characteristics.

    ;; See also Hoare, C.A.R., "Quicksort", The Computer Journal, 5:1, pp. 10-15, 1962,
    ;; and Knuth, D.E., "Sorting and Searching", The Art of Computer Programming,
    ;; Vol. 3, pp. 114-123, 145-149, 1968, particularly algorithm Q.
    ;;
    ;; Takes O N lg N average time. This implementation uses median
    ;; selection to avoid its O N**2 worst-case behavior.
    ;;
    ;; If the data has a pre-existing order, use mergesort instead.

    Divide your code into "paragraphs", between 5 and 20 lines long. Skip a blank line between paragraphs. This also helps find areas that are good candidates for factoring out into separate functions.

    Each paragraph may start with a block comment describing either what that paragraph does, or at least the program's state at that point in execution. Feel free to make these as descriptive as you like; they're the landmarks for somebody reading the code.

    ;; If the inner loop only executed once, then there were only enough
    ;; elements for two subsequences given n, so all the elements have
    ;; been merged into one list. Start-1 will have remained 0 upon exit.

    Loop guards frequently should have a one-line comment describing what they're testing for, in terms of the algorithm as a whole.

    (when (< ,end-1 ,vector-len) ; there are enough elements for a second run

    If a line's meaning isn't immediately clear, then clarify it with a one-liner.

    (let* ((retval-cons (cons :placeholder list)) ;:placeholder will be deleted later

    Any one-liners may be expanded to multi-liners if you need to:

    /* log_forward ignores SIGCHLD, so we must reset it to catch the
    * sendmail exit status. */
    signal (SIGCHLD, SIG_DFL);

    Mark areas that need investigation or more work with a comment of "FIXME"; that makes grepping later on much easier.

    res = pthread_mutex_unlock(&msg_thread->mutex);
    / * FIXME The error handling here needs to be more robust. */
    if (res != 0)
    d_errc(EX_OSERR, res, "cannot release worker thread");

    You can also use XXX for a similar purpose, or (what I do) to mark areas of grave significance.

    /* Frees all transitions out of a state. XXX Whatever calls this must
    * either reinitialize the transitions slist or free the structure. */
    static void
    free_transitions(struct matcher_u *matcher)

    Don't worry about descriptive comments being too verbose. Descriptions of program state, why something exists, research notes, or prose all have their place in comments. The only time I've read a file and thought "Gee, this is overcommented" was when it had template comments with changelogs and argument lists.

    Now what do you not use comments for?

    Don't keep a changelog in your code. Your source-control system does a much better job.

    Don't repeat the argument list. The argument list itself does a perfectly fine job of that, and will always be up-to-date. If the purpose of each argument isn't clear by its name, then add a one-line comment to the arguments. (Note: In Perl, don't shift the arguments off as needed. Get all the arguments off in the first line of code if possible, such as my ($self,$filename,$options) = @_; in order to let somebody calling the function to have an argument list available!)

    Don't document the language (eg, explaining ++). This not only is unhelpful, but distracts from useful comments. If somebody doesn't know what ++ does, they can look it up.

    Credits: Examples snipped and adapted from my own development, as well as CMUCL and FreeBSD sources.

  108. Code that is hard to write... by SilverThorn · · Score: 1

    ... should be hard to read! HEE! :-)

    --
    Artificial intelligence is no match for natural stupidity.
  109. Bad question by MagPulse · · Score: 1

    This question is as complex as "How to I write a good book?". As with English, there are many books that will help you with style and mechanics, but helping the reader understand is up to the coder. For example, The Pragmatic Programmer and Code Complete are analogs to Elements of Style and the Dictionary of Modern American Usage.

  110. Literate programming... by oren · · Score: 1

    ... is the only truly well-commented code. Literate programming was invented by Knuth. If you don't know who Knuth is: he's the author of the definitive CS work called "The Art of Computer Programming". Ask any of your friends who actually studied computer science about it.

    Knuth wrote more than books. For example, he wrote the typesetting program, TeX which is to this very day the most popular way academics in the CS field employ to write their papers (especially using a macro package called LaTex). He just wasn't satisfied with the available ways to write mathematical books at the time (early 80s). He had a good reason - you can see the difference in quality between it and anything else - especially Word (Ugh).

    To ensure you'll have the right idea about the quality of his work, note he's actually sending people checks when they find a bug in his books or his code. Of course people tend to frame them rather than cache them :-). Also note that nobody has managed to obtain such a check for a long time.

    So, what is literate programming anyway? Instead of inventing yet another definition, here's a pretty good definition which you can find in the site, together with many others:

    Marc van Leeuwen. "Requirements for Literate Programming" in CWEBx Manual, pg. 3-4.

    The basic idea of literate programming is to take a fundamentally different starting point for the presentation of programs to human readers, without any direct effect on the program as seen by the computer. Rather than to present the program in the form in which it will be compiled (or executed), and to intercalate comments to help humans understand what is going on (and which the compiler will kindly ignore), the presentation focuses on explaining to humans the design and construction of the program, while pieces of actual program code are inserted to make the description precise and to tell the computer what it should do. The program description should describe parts of the algorithm as they occur in the design process, rather than in the completed program text. For reasons of maintainability it is essential however that the program description defines the actual program text; if this were defined in a separate source document, then inconsistencies would be almost impossible to prevent. If programs are written in a way that concentrates on explaining their design to human readers, then they can be considered as works of (technical) literature; it is for this reason that Knuth has named this style of software construction and description "literate programming".

    Does it work in practice? All I can say is that I have used it in a real-world project with great success. The main downsides to it, and this applies to any type of documentation, is that it takes up-front time (even if it does save time later), and that you need to employ people with some measure of writing ability. It is surprising how many people can code well, but are hard-pressed to write coherent, readable description of their code. Especially if you write your documentation in English and the programmer's native language is Hebrew or Russian :-(

    Oh, and it also is hard to do in IDEs like Visual Studio. And you won't learn about it in your university, never mind your VB in 3 days course. Just like design by contract and many other techniques, the problem isn't that humanity doesn't know how to write software well - it is that humanity doesn't want to.

  111. // From my own experience... by Anonymous Coward · · Score: 0

    If you have too much comments it can be difficult to read the source code.
    The most important thing is to comment code that is not obvious (i.e. code the compensates for a bug in the OS, or code that has been produced by trial and error)
    It's better to have logically structured code and logically named variables and function names, rather than reams of comments, trying to make up for the above.
    Remember that comments aren't a subsitution for code documentation
    And always put the comments in at the last stage (after everyting is implemented and debugged).

  112. my code will get me killed by TheCyko1 · · Score: 1

    After someone reads my code they often feel an unresistable urge to kill me.

    It's hard to become a programmer when you spend most of your time dodgeing bullets.

    comment? what's a comment?

    --
    This message was brought to you by the death of 30 brain cells.
  113. re by Anonymous Coward · · Score: 0

    i have some standard names for my var like "$bla" and "$affe" that i define every time i write new code and i use vars like "$v0-$v99" but i always write comments under them to see what it is and when it's finished i usually rename them to something like "$HeaderVertPos" or stuff to make it easier to read. for me the main issue aint the missing comments but cryptic var names name and stupid and rendundant placed but heavily used backup-vars that you wont figure out...

  114. Important to maintain comments by coreman · · Score: 2

    The biggest problem I have with going through code (as a contractor, I tend to read a lot of new "to me" code) is the case where you're dealing with 2nd or third generation code, the original developers are long gone, and the intent of the routines has changed but the header/interface comments have not. One has to read and understand the code in order to make the changes and while the comments might be helpful, they also might be outdated and wrong. Too many times I've found a comment beside a routine call that say one thing and when I go into the routine, find it's something totally different. I am especially careful about comments that talk about expected return values or side effects. These generally aren't a problem on release 1.0 code but there's a lot of jobs out there dealing with release 5 versions of things where the comments might not have kept pace with the product.

  115. One other point by coreman · · Score: 2

    Many times a group is unwilling to submit comment/non-code changes for a module (due to the return values changing say) to source control because they don't want to have so many modules change for what they see as a "trivial" fix in another module. It's tough to get some of those changes through many review procedures and this is what causes comments in "callers" code to be outdated. Use the comments as a guide, not as gospel.

  116. ccdoc by CoolGopher · · Score: 1

    I find ccdoc to be a great help. It's a JavaDoc like tool for C++.

  117. Re:commenting code ...Too verbose; use 2 word vars by Anonymous Coward · · Score: 0

    call it complex_multi_word_variable, not ComplexMultiWordVariable, for readability's sake. ????

    How is a 4 word variable readable?

    Imagine reading code with > 100 variables like that! Worse than reading a bad novel.

    Both forms are unreadable!
    Too add insult to injury most coders like this go on to write long redundant comments. Essentially repeating what the long variable name tells you!!

    Ever wondered why Mathew is Mat, Catherine is Cathy, Timothy is Tim, Telephony is phony or why a lot of people ask for middle initial instead of the full middle name?

    Instead try something like
    cWordVar or sWord_Var //Complex Multi word. Does...

    Always keep var names to ideally 2 words
    Anything longer is worse than x, y, z.

    Both extremes are bad!!

  118. Over commented example by ch-chuck · · Score: 2

    My favorite example of well commented code, to the extreme, was a text editor w/ assembly code published in a Byte mag about 1983 or so (VDO Video Display Oriented). The source listing was nicely broken down into functions with a paragraph explaining exactely what was going on and why for maybe every 2 or 3 instructions! Anyway, the amount of English text far outweighed the actual code by maybe 10 to 1.

    --
    try { do() || do_not(); } catch (JediException err) { yoda(err); }
  119. The pains of commented code... by Anonymous Coward · · Score: 0

    On a running web site ecommerce web site...

    $creditcard = getParameter("credit-card-value");
    # TODO: Validate credit card number...

  120. Re:reply by fixed · · Score: 0

    well, it shows me as the oldest when sorting oldest first... 10 PRINT "Booya Grandma" REM Comments in BASIC are begun with REM not // REM Mr. FAKE Linus 20 GOTO 10

  121. Good Code... by Anonymous Coward · · Score: 0

    I remember one inspired indevidual saying
    Good code doesn't need commenting and bad code doesn't deserve commenting

    I tend to stick to

    //Get your filthy hands off my code, you'll be sorry

    or

    ' Ha choke on this script jockey

  122. damn by fixed · · Score: 0

    forgot the BRs... corrected below<br><br>

    well, it shows me as the oldest when sorting oldest first...<br><br>10 PRINT "Booya Grandma"<br>REM Comments in BASIC are begun with REM not //<br>REM Mr. FAKE Linus 20 GOTO 10<br>RUN

  123. Describe your design decisions and thought process by mfarah · · Score: 2

    I'm currently developing a project where I have to modify existing source code developed by someone else. I spend most of the time trying to figure out WHY the previous programmer did something the way he did it, and what the hell he was thinking. Write these into your comments. Also, write down in comments small tips for the programmers that might come after you. Comments in the style of:

    /* This function expects an object that has been fully filled and checked for errors before. Be sure to never send it a NULL one! */

    or

    /* We're invoking the call to the database with the "mode" flag set to zero because currently it won't use it - but it COULD be used in the future. */

    help a lot.

    I also have to modify Java source, where I have generic classes that inherit from previous ones a lot of attributes. For example:

    public class A {
    public String s;
    public double d;
    public long l;
    }


    and

    public class B extends A {
    public String ss;
    }


    I prefer to write class B like this:

    public class B extends A {
    // public String s; : A
    // public double d; : A
    // public long l; : A
    public String ss;
    }


    That way I can see quickly all of the attributes class B contains.

    --
    "Trust me - I know what I'm doing."
    - Sledge Hammer
  124. Favor Code Clarity Over Comments by Bob9113 · · Score: 5, Insightful

    In any situation where I see the need for code commentary, I try first to find a way to make the code clearer. If the source code is sufficiently clear, comments are unnecessary. This also avoids the risk that the comments will diverge from the code - making claims that were once true, but no longer reflect the code's actual logic.

    This is poorly commented code (despite the fact that the comment is clear and accurate):

    aClassName = aTask.getUiInitializerClassName();
    // empty or null uiInitializerClassName means this task is not
    // defined for use in this interface. Skip it.
    if( aClassName != null && ! aClassName.equals( "" ) ) {
    ... do something ...
    }


    This is well commented code (despite the fact that there are no comments at all):

    initializerName = aTask.getUiInitializerClassName();
    boolean isNotNull = initializerName != null;
    boolean isNotEmpty = ! initializerName.equals( "" );
    boolean definedForThisUi = isNotNull && isNotEmpty;
    if( definedForThisUi ) {
    ... do something ...
    }

    Of course, this doesn't work in all situations, but I find that I can improve the clarity and accuracy of seventy to eighty percent of my commentary this way.

    1. Re:Favor Code Clarity Over Comments by barzok · · Score: 2

      I never liked putting "not" in a variable name like this. It makes if statements later on klunky to read. Using if (!isNotNull) to determine if something is null can be difficult to wrap one's head around. I prefer to use the positive case:
      if (isNull) {
      do something
      }
      else {
      do something else
      }
      I think you'll find that in Code Complete (previously recommended in this story) as well.

    2. Re:Favor Code Clarity Over Comments by Bob9113 · · Score: 1

      Using if (!isNotNull) to determine if something is null can be difficult to wrap one's head around.

      I completely agree, though only in the case where a variable is being used repeatedly in a block. The example above is from an actual code block like this:


      private void initialize( Task aTask ) {
      String initializerName = task.getInitializerName();
      boolean isNotNull = initializerName != null;
      boolean isNotEmpty = ! "".equals( initializerName );
      boolean definedForThisUi = isNotNull && isNotEmpty;
      if( definedForThisUi ) {
      addToTaskBar( aTask );
      }
      }

      So as you can see, there is no opportunity for a confusing use of the variables. They are entirely localized and for clarity purposes only. This will be most useful when you are using fine grained methods, which may not have been a focal point of Code Complete. Of course, fine grained methods have their problems too - they sacrifice performance for clarity. Many things in programming are tradeoffs. It's just a matter of choosing your priorities.

    3. Re:Favor Code Clarity Over Comments by Bob9113 · · Score: 2

      Upon further reflection, I think that the following is just as clear in setting definedForThisUi, and also makes the use of !'s clearer. Your recommendation makes a lot of sense.

      private void initialize( Task aTask ) {
      String initializerName = task.getInitializerName();
      boolean isNull = initializerName == null;
      boolean isEmpty = "".equals( initializerName );
      boolean definedForThisUi = ( ! isNull ) && ( ! isEmpty );
      if( definedForThisUi ) {
      addToTaskBar( aTask );
      }
      }

      Thanks for the tip!

    4. Re:Favor Code Clarity Over Comments by lkaos · · Score: 2

      I'm sorry, but your second example is ridiculus. Moving comparisions outside of the if statement and introducing three extra named variables is not only horribly inefficent, but makes thing unnecessarily complicated.

      Things like null comparisions do not need to be commented. Everyone knows what your doing if you have 'aClassName != null'. There is no need to waste disk space but restating the obvious.

      --
      int func(int a);
      func((b += 3, b));
    5. Re:Favor Code Clarity Over Comments by Permission+Denied · · Score: 2
      I disagree. Your first example is good, concise code, while your second is far more difficult to read. If you want to express something, why not use English?

      Why would you ever do this:

      boolean definedForThisUi = isNotNull && isNotEmpty;
      if( definedForThisUi ) {

      instead of this:

      if (isNotNull && isNotEmpty) {
      // not defined for this class

      If I ever saw your code, I would change it on the spot to this second way.

      After looking through the rest of the function and seeing that those boolean variables are only used once, I would change it to your first example. Come back in a month and look at the two examples - see which one takes longer to read and figure it (even it it's only one half second, those one-half seconds add up quickly).

      Never introduce boolean variables which are only used in one top-level statement, unless it's to make your code fit in 80 columns.

      Really, you're giving very bad advice, and I'm only responding so I won't have to deal with other people taking your example.

      In fact, I can't believe you came up with this idea from a book - I'm guessing you came up with this on your own. I ask you to please point out the book which gives this advice, so I can avoid it. Someone else already noted Code Complete which explains that using "Not" in a variable name is bad practice (as opposed to using "!"). I would also like to point out The Practice of Programming which says the same thing (don't use "Not") and also gives some advice on avoiding cutesy, pointless one-shot booleans instead of just inserting a simple English comment.

    6. Re:Favor Code Clarity Over Comments by elflord · · Score: 2
      You've still got all those temps. Better to have a separate function that tests for empty: if ( ! definedForThisUi(task.getInitializerName() )) addToTaskBar(task);

      But this isn't a very good example anyway -- the original code was perfectly clear, and better than your "fix".

    7. Re:Favor Code Clarity Over Comments by MikeTheYak · · Score: 2
      initializerName = aTask.getUiInitializerClassName();
      boolean isNotNull = initializerName != null;
      boolean isNotEmpty = ! initializerName.equals( "" );
      boolean definedForThisUi = isNotNull && isNotEmpty;
      if( definedForThisUi ) {
      ... do something ...
      }
      Wow, you'd really do this? Even with the potential null dereference in the third line? Even if the third line was made safe, it's still an extra function call you could have avoided with lazy evaluation. Personally, I think your 'bad' example flowed much better. If you really wanted to get rid of the comment, you could use

      boolean definedForThisUi = initializerName != null
      && ! initializerName.equals( "" );

      The other two booleans are specious. The what for the source is easy to decipher; programmers know what null reference and empty string checks look like. The why is what might be unclear in an uncommented version of the first example, but all the necessary information is exposed using the above line of code.

    8. Re:Favor Code Clarity Over Comments by Broccolist · · Score: 1
      I disagree completely. I found your first example *much* clearer. "initializerName != null" conveys more information at a glance than "isNotNull", which could mean anything. Abstracting it away is counterproductive.

      Again, when I see "if( aClassName != null && ! aClassName.equals( "" ) )" I know exactly what's going on, whereas "if( definedForThisUi )" tells me little and forces me to decipher and remember what's above it.

    9. Re:Favor Code Clarity Over Comments by Flu · · Score: 1
      Both your solutions are good, but in different situations:

      If isNotNull and isNotEmpty are together only at that spot, then the latter suggestion is much better than the first, unless the expression is obscure (for example if the variables would be names isOneLeft and isTwoRight), or very complex, or the comparation needs to be done several times.

      In those cases, a well-named constant boolean can actually make the code more readable than a (potentially invalid) comment.

      /FLu

    10. Re:Favor Code Clarity Over Comments by babyruth · · Score: 1

      furthermore, this is a shortcut operator, meaning the second test never executes if the first fails, which your revision does not take into account (thus the NullPointerException waiting to happen)

      if( aClassName != null && ! aClassName.equal( "" ) ) {
      ... do something ...
      }

    11. Re:Favor Code Clarity Over Comments by naoursla · · Score: 1
      Martin Fowler's "Refactoring" book would probably suggest something like this:

      boolean isNull( Object reference ) {
      return reference==null;
      }

      boolean isEmpty( String str ) {
      return inializerName.equals( "" );
      }

      boolean isDefinedForThisUi( String uiInitializerClassName ) {
      return !isNull(uiInitializerClassName) && !isEmpty(uiInitializerClassName);
      }

      void someFunction() {
      initializerName = aTask.getUiInitializerClassName();
      if( isDefinedForThisUi(initializerName) ) {
      ... do something ...
      }
      ...
      }
      As another person pointed out, you could get a null pointer exception when you set isNotEmpty. The approach above avoids that and keeps your understandable names. This also follows a school of thought that tries to avoid local variables. I would probably consider this example overkill.

    12. Re:Favor Code Clarity Over Comments by James+Youngman · · Score: 1

      Actually I think the first set of code is clearer - because it doesn't introduce the spurious variables which are themselves used in lieu of documentation.

    13. Re:Favor Code Clarity Over Comments by Anonymous Coward · · Score: 1, Insightful

      I have only one thing to say:

      GUARD CLAUSES.

      void doWork(String initializerName) {
      if (initializerName == null)
      return;
      if (initializerName.equals(""))
      return;

      ... do something ...

      };

      *THAT* is well commented code, with no comments. What you had was a namespace-eating, inefficient scope nightmare :) no offense.

      Functions. Lots of functions. Whenever you find yourself tempted to add variables for a single use, you are missing a function with guard clauses.

      (In case you didn't guess, a guard class is a boolean test with return at the start of a function, basically a drop-out test. They're nice and sequential, remove the need for large amounts of indentation in nested if's, and are terribly easy to read.)

  125. Comments as API spec / programming guide. by vil · · Score: 1

    Sun has some good advice about this on their website. They talk about using method level documentation as an API contract specification, as a programming guide, or both. A lot of that paper is written with the JavaDoc tool in mind, but the general points are valid for any language (and you can always use Doxygen, if you want to apply the specifics to C++).

  126. comments by small_box_of_stuff · · Score: 1

    Lets be honest here. Using comments as a crutch to prevent you from having to figure out what what the program does is destined to fail.

    Comments are not compiled. They do not affect the outcome of the program. If you want to know what the code does, even in the presence of comments, you have to look at the code. Comments can be out of date, misleading, and just plain wrong.

    There is no substitute for just reading the code, and learning to understand what it means.

    Even in a beautifully commented piece of code, you will still have to go back to the code, to confirm what its doing.

    Just try to remember. Comments arent compiled. They are not the code. If you want to know what the code does, you have to read the damned code.

    That being said, the comments that are most likely to have an impact on others is comments not about the code, but about intentions. Its pretty easy to convert your intentions in to code, but alot harder to convert your code back in to what you were trying to do.

    The code tells me what you did, but not why. And comments that talk about why you are doing something, and why you chose this path, are less likely to be wrong, missleading, or out of sync.

    If you know what you are doing, you can look at uncommented code and figure out what its doing, but not why. Why is whats important.

    Coding is a kind of compression. It takes the verbose ideas that you and your team have been tossing around for a while, and convertes them in to something quite sparse for the compiler. If I look at your code, I might be able to reconstruct your ideas and intentions, but its not likely. Thats what I need added to the code.

    -

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

      That is a very good point. And if you look at the Linux kernal source most of the comments explain "why" and not "what". One that I can think of off the top of my head is in the memory management code. Whoever wrote the function I'm thinking of has a comment to justify his use of gotos in the code.

      --

      --
      "What do you want me to do? Whack a guy? Off a guy? Whack off a guy? Cause I'm married."
  127. Commented line or commented block and nameing by Flu · · Score: 1
    We started using a standard commenting-style which differentiated between a comment that is valid for a single-line only and a comment that is valid for a group of lines. Of course, single-line comments starting at the end of the line are simple to understand, but when the line is 80 chars+, and the comment is too, things get hairy. So we simply did
    // This comment is valid for
    // the next code-line, only.
    doSomething();

    longVariableName =
    doSomethingReallyLongAndHairy()
    + anotherLongFunctionName(); // And the above comment style
    // is better than this for a single line.

    doSomethingAgain(); // But we do allow this for short lines.

    //
    // However, this comment is valid for all code
    // lines until the next comment of this kind
    // is used, or until the next }-brace appears in
    // the code.
    //

    complexAlgorithmStep1();
    complexAlgorithmStep2( );
    complexAlgorithmStep3();
    Apart from that, we also use self-describing names (unless they get too (>40 characters) long). This definitely reduces the need for comments. We also try to minimize the number of sequences in a single function.

    Another good thing we started with was adding notaion of in-, out- and in-and-out parameters, to separate them from auto's and globals.

    Parameters that are in (readonly) always start with i, parameters that are pointers to uninitialized buffers that are initialized by the funcion starts with o, parameters that point to initialized buffers that are modified starts with io, all variables defined in a function starts with t (yes, could be confused with types, we really should have selected another letter instead), and all attributes starts with m.

    This way, we never accidently create bugs by accessing a local instead of a parameter or a global or static variable, or an attribute, which we found was a Good Thing(tm). Also, the parameter list became more self-describing.

    /Flu

  128. One thing not to do... by Anonymous Coward · · Score: 0
    Whatever you do, don't, ever, never, EVER write comments that are boxed in with ascii characters - boxes of ****** all around the comments are downright fucking impossible to maintain.

    Who the fuck cares if it looks pretty when you have to spend 2 useless hours lining up a bunch of *****'s just because some moron thought that would be the best way to comment.

  129. University CS Standards. by CrazyDuke · · Score: 1
    I believe I lost points if I averaged any less than 6 comments per line of code. I particularly "liked" having to comment the needless classes that only set and returned vars. (..could have just been a struct.)

    Here is an example, the first line of /'s where taken out to get past the lameness filter...

    // Name: getFoo
    // Class: bar
    // Description: Returns value of the integer variable foo
    // Variables: integer foo - returned from function call
    // Called By: Functions outside of the class bar that wish to know the value of foo.
    // Function Calls: nothing
    int bar::getFoo() { //Begin function getFoo

    return foo; //return value of foo as an integer

    } //End of function getFoo

    Gee...I wonder why I enjoyed programming until I went to college...

    --
    Any sufficiently advanced influence is indistinguishable from control.
  130. Worst comment I ever saw by dannyspanner · · Score: 1

    In some VB code I saw:

    ' Add one to the counter variable.
    intCounter = intCounter + 1

    No kidding. Every line was commented that way. I didn't know whether to laugh or cry.

    1. Re:Worst comment I ever saw by IainHere · · Score: 2, Funny

      Top of a huge listing of nasty code: /* I don't do comments */ I knew that tears would be my only comfort in the coming days.

  131. my favourite book on this by Anonymous Coward · · Score: 0

    My favourite book on code readability happens

    to be free. Unfortunately it is not about

    C++.

    Try:

    Ada95 quality and style

  132. Document the intention by BbMaj7 · · Score: 1

    The most useful thing to document in code comments is the intended behaviour of the code. With this information it is simple for any half-decent hacker to find out if the code does what it is supposed to do.

    Takes the guesswork out of debugging. If the code doesn't do what the comments say it was intended to do then you know you've found a bug.

    --
    -- Rich
  133. Too many lameness characters by CrazyJim0 · · Score: 1

    I had a documentation post, but it got nerfed by slashdotomatics lameness filter.

    2 parts to documentation

    #1 Use a bunch of - to make a line really long
    //---

    Section off your code. And comment what it does.

    #2 Document important variables that are well used, especially globals

  134. Be suspicious of comments.... by borgboy · · Score: 1

    Write clear concise code that documents itself. Use well named methods/functions/procedures/subroutines that do one small thing. IOW, write blindingly obvious code that doesn't need comments. Use comments to explain difficult or clever code, and then consider the comment as a red flag - maybe that clever code shouldn't be so clever. Maybe it's a time-critical algorithm, and it DOES need to be that difficult. That's why they pay us the big bucks.

    All that being said, I really like javadoc and it's c# bastard cousin. But that's a different story. Comments have a tendency to rot, but the code is ALWAYS the most accurate "comment" about what the code does.

    --
    meh.
  135. Go to college by Ricky+Glaze · · Score: 1

    In any CS curriculum you would have learned proper code documentation standards. Go take a Software Engineering course.

  136. Why software patents are bad... by wfberg · · Score: 2
    Comments should really only document those things which are not obvious to one skilled in the art. And of course endlessly duplicating comments is pointless, so stick to the novel stuff..

    Of course, if you stick to these guidelines, you're not writing comments, but patents.. So better hide those from your coworkers, otherwise they'll try to claim royalties..

    --
    SCO employee? Check out the bounty
  137. Documentation is not just comments in the code by shoppa · · Score: 2
    For any system above the tiniest complexity, there's a lot that has to be documented outside the code. Just for starters:
    • Persistent and temporary file formats
    • User interface
    • Network protocols
    • System and architectural design
    • Relationships between data elements (or objects if you think that way)
    Some of the above are addressed by UML and associated tools, but for things like network protocols the RFC-type format is the hands-down winner. A particular implementation of a good idea in code might last a couple of years, but the protocols for a truly revolutionary idea will live for decades. (Look at Mosaic and HTTP/HTML for a good recent example.)
  138. The best comments are the code itself by chrysalis · · Score: 2

    IMHO, comments are often confusing. A source code that has plenty of comments becomes unreadable. And comments aren't always in sync with the code when changes are made.

    A source code with no comment, but whoose structure is very simple is way easier to understand. When the compiler sees long and overcomplicated expressions, it painfully transforms them into more, but basic expressions. So why not write simple code?

    I often see complicated lines with plenty of ternary operator usage. Why? Write the same code with simple 'if' statements. The generated code will be exactly the same, but the source code will be easy to understand.

    Another very confusing thing (IMHO) is the usage of expressions without explicit braces in loops and conditional statements. Ie. things like :

    if (ready())
    while (*++take)
    if (*take == 4)
    foo();

    Without indentation, it's very confusing. Worse : what if I want to add an 'else' here? If I want to add an 'else' to the second if, I really have to properly indent it to avoid confusion. If I want to add an 'else' to the first if, I have to add braces. This sort of thing doesn't ease the usage of macros and can give very nasty bugs when cutting/pasting blocks without carefully understanding where implicit braces are. So why not simply write :

    if (ready() != 0) {
    while (*++take != 0) {
    if (*take == 4) {
    foo();
    }
    }
    }

    The generated code will be exacly the same, but there's no possible confusion here.

    Also, 'goto' is not bad. Really. When you have to break from several loops, or just to avoid deep nesting of statements, a well placed 'goto end' is way clearer and faster than useless functions and silly 'flag_to_see_if_we_have_to_exit' variables. Don't forget that after compilation, any program will have 70% of goto-like assembler opcodes.

    Comments can be interesting to note bugs, or TODO stuff.

    Also have a look at the style(9) adopted by the OpenBSD team. There are good ideas.

    --
    {{.sig}}
    1. Re:The best comments are the code itself by scrytch · · Score: 2

      If I want to add an 'else' to the first if, I have to add braces.

      Unless you're using python, which won't even let you. In a language with braces, I can at least hilight the block and let the editor reformat it.

      Also, 'goto' is not bad. Really. When you have to break from several loops, or just to avoid deep nesting of statements, a well placed 'goto end' is way clearer and faster than useless functions and silly 'flag_to_see_if_we_have_to_exit' variables.

      When 'goto' is simply used to jump out to some label that's right at the end of a loop, that's one thing. It's usually far better to use 'return' and inline statements. If the exit was caused by an exceptional condition, you should be using structured exception handling, though C lacks it entirely (it's not too hard to add it with macros, check the LambdaMOO source code for an example) and C++'s implementation is badly botched (threw from a destructor? hello segfault.) Never said C made for very maintainable code.

      Don't forget that after compilation, any program will have 70% of goto-like assembler opcodes.

      By that logic, why not just program in asm? You had to know you were going to get called on that one.

      --
      I've finally had it: until slashdot gets article moderation, I am not coming back.
  139. Hungarian Notation - God No! by smartin · · Score: 2

    There is no easier way to make code ugly and unreadable than to use hungarian notiation. nCount is not in anyway more readable that cnt, it clutters the code and is very annoying. If your code really needs to encode the data type in the variable name then there is something horribly wrong with it.

    --
    The difference between Canada and the USA is that in Canada healthcare is a right and gun ownership is a privilege.
    1. Re:Hungarian Notation - God No! by UnknownSoldier · · Score: 2

      > There is no easier way to make code ugly and unreadable than to use hungarian notiation.

      Using tradional HN I agree. See my above post for how I use a variation which I find usefull.

      > nCount is not in anyway more readable that cnt,

      Those are both bad examples. I don't like playing the guess-which-vowel-or-letters-I-left-out-of-the-var iable game. It's a waste of another programmers time.

      nCount is redundant. Count doesn't tell you anything about the variable.

      NumPlayers, MaxPlayers are much better descriptive examples.

  140. Remember, comments don't have to make sense by lightspawn · · Score: 2
    Sometimes there's a certain... feeling... that you want to convey to the reader, that would make it so much easier to understand the code but cannot be expressed in words. I always use nonsense words, with a tone and rhythm carefully designed to put the reader in the right frame of mind.


    Sure, some of your stuffy cow-orkers may challenge this practice, but it's all for a good cause.

    1. Re:Remember, comments don't have to make sense by bigsteve@dstc · · Score: 1
      Sometimes there's a certain... feeling... that
      you want to convey to the reader,


      I get a a feeling of nervousness when I see overly
      "artistic" comments. Especially when I'm trying
      to maintain it. "What mind altering substance
      was he one when he wrote this???".


      Is that the kind of feeling you are trying to
      convey?

    2. Re:Remember, comments don't have to make sense by lightspawn · · Score: 2
      Enlightenment, son, sometimes may be found outside of words. Why is a mantra needed? Why can becoming one with the universe not be reached by following a recipe? Why did Tolkien feel the need to create a language for the elves?


      Remember the zen mu, or your own discipline's foo.


      Really, some people have no idea about semantic or phonetic fields.

  141. Re:commenting code ...Too verbose; use 2 word vars by Anonymous Coward · · Score: 0

    Imagine reading code with > 100 variables like that! Worse than reading a bad novel.

    but at least it's readable!

    Ever wondered why Mathew is Mat, Catherine is Cathy, Timothy is Tim, Telephony is phony or why a lot of people ask for middle initial instead of the full middle name?

    no

    Instead try something like
    cWordVar or sWord_Var //Complex Multi word. Does...


    Yeah that's descriptive! Now I pity the poor bastard who has to maintain this code.

    Also, what's up with this hungarian bullshit? You wanna know the type of a variable then see its declaration.

    Variable names should be descriptive. If more than 2 words are required to get across a description then so be it. At least it will be more likely to be understood by the next person.

  142. Re:Describe your design decisions and thought proc by chrysalis · · Score: 2

    If you define structure with public stuff but default, why the hell are you using 'class'? Use 'struct'. The only difference between 'class' and 'struct' is that 'class' has private members by default, while 'struct' has them public by default.

    --
    {{.sig}}
  143. easy answer... by patazathoth · · Score: 1

    comment the function before coding it!

    Why?

    1) You will have a better clue of what is it that the function should do. Help you find any problem or hole you got in your approach.

    2) It will be clearer for other who read the source code later.

  144. Good naming is the foundation by whipping_post · · Score: 1
    I do most of my coding in Java and I find that if variable and method names are sufficiently descriptive, while still keeping to (project/company) standards, then inline comments can be kept relatively sparse.

    By and large, comments for "tricky" code, complex algorithms, or non-obvious functionality are all you need to make sure anyone can figure out what is going on in the code.

    The one exception I make to this is to make sure every class and method is JavaDoc'ed extensively. This helps those people USING the class as much as it helps those who are maintaining/modifying the class. I find that overall it increases the quality of code and reduces bugs significantly.

  145. Comments for Doxygenation by lockstocknbarrel · · Score: 1

    I cannot say enough good things about Doxygen.

    I work with huge source trees written in C,C++ and Java, and with Doxygen you can use identical (or not) commenting styles and then let doxygen present the documentation in a nice way. I can automagically create html, man pages, LaTex, pdf, rtf and/or xml documents from mixtures of source code.... entirely flexible and configurable.

    Power and ease of use aside, the real value I get from Doxygen is it's dual sided purpose: It can be used as a tool for development or as a straight public documentation generator. I can take a single source tree and at once generate a super hyperlinked code searcher and a high-level functional description document for non-coders (say your boss). It allows a developer to visually see the architecture of the system through graphical class hierarchies and then hyperlink *directly* to the source code that generated it. Far and away more mature than java-docs....

    You get to the point of wanting to comment more, because the output that Doxygen generates based on your source code comments is so usefull and readable.

    Get it, use it... it will make working on small parts of a large system easier.

    --
    ---------- slow blades penetrate ----------
  146. Tons of code already there by 192939495969798999 · · Score: 1

    How do we deal with the problem of tons of existing code without comments? Adding comments to it when it is hard to determine the intended functionality of said code seems like it would be harder than rewriting the code and adding comments to the new code.

    --
    stuff |
  147. Commenting data by Anonymous Coward · · Score: 0

    When I was an intern at a graphics company, I found myself wishing for data documentation a lot more than code documentation. You can generally figure out what a piece of code is doing by following it, once you know how to interpret the variables it is working on.

    For example, a variable called, say, pDrawSurface is all very nice: it tells you that it is a pointer to the surface you're drawing on. But what format is it in? If it's a NULL pointer, what does it mean? If you have a front buffer and a back buffer, which is it? What if you're rendering to a texture instead of a screen surface? My point is that while good variable names are definitely a requirement, they are often insufficient to _completely_ define what a variable does.

    My feeling is that a variable should have a reasonably descriptive name that will help you remember what it does, but the more obscure points should be documented at the point where the variable is defined. Of course this can also apply to functions, types, parameters etc.

  148. Here be elephants by bigsteve@dstc · · Score: 1
    My favourite, from a long time ago, was a 1000-odd line
    CDC 6000 assembler program whose only comment read:

    PROCESS EQUIBALANCED ELIPHANTS
  149. input output specs by yzquxnet · · Score: 2

    I get peeved at how many people leave out this critical information. Lets say they have a small section of code that is changing information in a database on the fly as it is displayed to a client. They will comment that the code changes the value but nothing else. Oh how I cringe. Not to mention people who don't comment changes they made.

  150. Overview by mathematician · · Score: 1

    What I usually really wish for when I read someone elses code is this: I would like a paragraph or two at the beginning giving an overview. This overview should first describe why this code exists - what problem it is meant to solve - how it fits into the general scheme of things. Secondly, it should explain in general terms how it works.

    As to the details of how it works - well, as they say well written code should be self explanatory, so I don't think this is so necessary. But well written code can never replace the overview.

  151. Peer review by oliverthered · · Score: 1

    The best commented code is the code that is commented on 'By Others',
    When they ask who what the hells going on, you should be writing clearer code.
    When they tell you 'This ways better', you should listen.
    When they tell you 'Theres a buffer overrun' you can fix it.
    When they tell you 'Theres a back door left in IE version 5 that allows Bill G to own your soul' you should use open source software.

    --
    thank God the internet isn't a human right.
    1. Re:Peer review by mgarraha · · Score: 2

      The best way to ensure readability is to test readability. Show your code to two other programmers; whenever they have a question, revise the code to include the answer. After you make this a regular practice, you may find yourself anticipating reviewer comments as you code. Then you will understand readability in a way that no lone-wolf pundit possibly can.

    2. Re:Peer review by oliverthered · · Score: 1

      You may also find yourself reviewing someone elses code and screaming the roof down trying to understand it, or printing it out and reading it before bed time, because it's so butifully written. This is by fay the best way to get people to write nice code, and you also pick up things along the way.

      --
      thank God the internet isn't a human right.
  152. Rational Rose by Kraft · · Score: 2

    (Of course, not entirely fair, since we also didn't force code generation via Rational Rose. We instead reverse-engineered all of our final UML from the code we'd written and tested, and knew worked the way it was supposed to...)

    Any particular reason you didn't use Rose, that you want to share? I am just getting aquianted with Rose now, and I am pretty enthusiastic.

    --

    -Kraft
    Live and let live
    1. Re:Rational Rose by Anonymous Coward · · Score: 0

      Personally I don't like Rose, because it has a buggy UI. Pretty ironic since it should help you with 'well thought out' designs and generate less buggy code.

    2. Re:Rational Rose by Anonymous Coward · · Score: 0

      We've used rational rose before and it slowed the project down
      by about a factor of 4. It was VERY painful for us, especially
      when trying to generate word documents out of our diagrams. Word
      just couldn't handle it.

      In an of itself, it's just awful. But we also had a group of
      Linux programmers having to use windows or VMWare to run rose,
      so we had some unhappy campers.

      Rose is just strange and buggy and it can be hard to get things right.
      If I hear a project's gonna use Rose, I RUN away as fast as I can, laughing because I know the project will fail.

    3. Re:Rational Rose by J.Random+Hacker · · Score: 2

      My WORD! The useless *BONDAGE*! There is a serious disconnect between UML models and C++ code that makes reverse engineering an impossible task for all but the simplest data models. The problem boils down to the fact that a UML relationship type can be implemented in a number of different ways. Similarly, a particular construct in C++ can represent several different UML relationship types. This leads to a many-to-many mapping of C++ coding constructs onto UML relationships.

      I also had a tough time getting Rose to generate a reasonable skeleton when using STL containers. It never seemed to construct the proper container declaration, or place it in the right scope.

      Most of the code it produced would have been hopelessly ineffecient, and I could never convince the tool to change its ways. Tech support didn't understand C++ well enough to understand (a) what I was talking about, and (b) why it was a problem.

      After struggling with the tool for most of a year, *trying* to make it work, I finally ripped the code out, stripped the Rose comments, and started making real progress.

      We now use Doc++ to document the design, and that works much much better. The only thing I miss are the UML diagrams. That last statement is telling: The UML diagrams did a great job of describing complex data structures (of which we have several), but the tool could not generate code to implement the UML diagram that was reasonable.

      I hope you have better luck, but I'd be prepared for much disappointment, unless your project is a small one.

    4. Re:Rational Rose by emag · · Score: 2

      Let me start with a disclaimer that it's been about 2 years since I had to work with Rose.

      With that in mind, here's what I found out about using Rational Rose on a unix platform:

      Rose is not a native unix app. It was ported from Windows using a commercial API kit to allow the Windows API calls to stay as they were. This caused startup to be incredibly so, even on fairly heavy (at the time) hardware with a single user on the box. And usually a couple times a month, something would cause the datafiles for this toolkit to self-corrupt, requiring the removal of a .subdir in order to even launch Rose again (and losing a lot of customizations).

      Opening up a Rose "petal" file, and then saving it, results in changes to the data, even if you didn't even touch the layouts. This was especially a pain in the ass when you'd open a file to look at a diagram, close it, then do a cvs update. Conflicts galore. If you didn't have everything stored in separate files, like, if you had a bunch of related diagrams stored in one petal file (not to mention it sounds like you're saying pedophile all the time), you were royally fucked if you went and updated a portion after someone had checked in a new version of the file (and didn't touch the area you were working in).

      It's unstable. Incredibly unstable. Like I said, it's basically a recompiled Windows app. So bus errors, seg faults, etc., were common after using it for more than about a half hour. Some of our folks never learned the "save early, save often" approach when using Rose (which was another adventure if your diagrams had any complexity), but I did after losing a few hours' work the first few times I used it.

      As other replies have said, the C++ code generation is pure crap. If Rose decided to do something one way, you were forced to write code to do it that way, even if you knew there'd be an implementation problem. And no STL support.

      In generated code, you had to be DAMNED sure that you only filled in the skeletons between Rose's "begin" and "end" comment blocks, or it would silently throw away all the code you'd written. Since we weren't using code generation ourselves, I discovered this talking to coworkers on another project who were forced to generate all of their class skeletons within Rose.

      Mixing C and C++ was a bit of a chore, too. We had some custom hardware we needed to interface with, and there was no easy way to designate the design of this portion of the code within Rose. That could just be the overall unfamiliarity we had with the product though.

      That's about all I can remember right now. I've tried to forget the whole sordid affair. Not that I'm soured on UML itself, but just Rational's products.

      --
      "The urge to save humanity is almost always a false front for the urge to rule." --H.L. Mencken
  153. Comment describe Why you did it by DickLieber · · Score: 1

    Comment are useful to describe why. Why this is needed, why you did it this way. The code itself, assuming you've choosen good descriptive names describes what you did. You cannot indicate the why in the code itself. Also I feel writing comments, and code for that matter, should be addressed to the next person to look at the code. And the next person isn't as sharp as you!

  154. A True Klingon by Walrus99 · · Score: 0

    A true Kingon does not comment his code.

  155. Comments by Anonymous Coward · · Score: 0

    1. What the code is supposed to do
    2. Why it is doing it the way it is (to save yourself the "why didn't you..."s)
    3. Update the comments when you update the code!!!
    4. If it has a high comment / code ratio then something is wrong

    At one job I laboriously commented the Y2K bugs as we went along in advance of our Y2K testing. One programmers job was to remove my comments - not fix the bugs, just remove the comments.

    What the client doesn't see the client doesn't know.

  156. The common Joke by msheppard · · Score: 2

    /* This was hard to write, it should be hard to understand */

    M@

    --
    Krispy Cream is people
  157. It's simple by DaKritter · · Score: 1

    Comment answer the "why" question.

    The code answers the "how" question.

    External documentation answer "what", "who" and "when".

    Parameters and returns of functions must also be documented, especially when they are not obvious or have side effects.

  158. Important!! by Zapper · · Score: 1
    ALWAYS rot13 your comments as this hides spoilers.
    Occasionally I have been reading some code and the idiot put in a comment that just gave the whole thing away.

    Never comment each function, just put one big comment at the end of the file.
    Or better yet: have a seperate file that contains all your projects code comments so that they are easily found in one convenient place.

    Use acronyms and abbreviations to reduce source code size.
    I can't stress this enough, make up your own acronyms and abbreviations if you have to, brevity is the key.

    Hope this helps.

    --
    So much to do, so little bandwidth.
    --
    Try Mozilla
  159. C++-specific stuff by Permission+Denied · · Score: 2
    You mention you work with C++; here are my thoughts on this language:

    First of all, keep your comments confined mostly to your header files. That is,

    // foo.h
    struct Foo
    {
    Foo();
    void bar(double x);
    };

    // foo.cc

    // calculates the square root of X using Newton's
    // method and subsequently uses this to invoke ...
    // throws: SomeStupidException
    void Foo::bar(double x)
    {
    ...
    }

    This is very bad. The comment above Foo::bar belongs in foo.h, not foo.cc. I should never have to read your .cc/.cpp/.cp files in order to use them. The comments in foo.cc should only explain clever tricks, workarounds, etc. There are two purposes for comments: (1) defining interfaces to reuse some code later and (2) describing unusual or unexpected ways of doing things. (1) belongs only in header files. (2) belongs mostly in .cc files, but can also go in headers if there's something particularly nasty afoot. This makes it easy to look at a particular project and get a good idea of how things interact, without worrying about details.

    I work more with C than with C++, but the exact same rule applies (which is not always true - there is no such language as "C/C++" and what is idiomatic for one is completely awkward in the other). Modern idiomatic C dictates that you separate your code into "modules" with a .h and a .c file for each "module." .c files should only be found alone if they don't export any functions that are used in another .c file (eg, they only "use" modules rather than implement anything). The distinction should be made explicit by declaring module-local functions as 'static'

    Another thing I find quite useful is using the "MVC" paradigm (Model, View, Controller). A concrete example: any web-based database application, like slashdot, for instance. The "Model" part is the actual database schemas. The "Interface" part generates HTML. The "Controller" part is the only part that actually constructs any SQL statements. Your controller has good APIs if you can completely change your database schemas without changing any code in the "Interface" part. Generally, well-designed systems like this require comments to define the "Controller" APIs, and don't have too many comments elsewhere.

    Someone else has already mentioned The Practice of Programming and I'd like to chime in that this is an excellent book.

  160. in defense of poorly commented code by FeltTip · · Score: 1

    Look - if it wasn't for poorly commented code, I wouldn't be able to code at all today. Sifting through junk code allowed me to learn more about programming (good and bad) than any book or class.

    --

    ....... rm -rf microsoft ........

  161. Any comment... by akh · · Score: 1

    ...except for FIXME!

    --
    Accept Eris as your Fnord and personally sate her
  162. THE Simplest rule for writing good comments. by bteeter · · Score: 1

    Writing good comments can be accomplished by applying one very simple rule:

    -> Write the comments before you write the code.

    If your writing a sorting function, take the 5 minutes required and write the comments for what your going to do before you do it. You'll be amazed what a difference such a simple step can make. Plus, you'll see the holes in your logic form quickly if there are any.

    Also when making changes to existing code, the same simple rule applies. Write out all of your code changes in the comments first. Then implement the changes. The same benefits apply in this case as in when writing new code. But there is an additional, very important benefit in this case: comments in code are kept up to date. How many times have you seen source code that has _incorrect_ comments? Plenty I'm sure - and in most cases that happens because someone fixes a problem or change logic without updating the comments. Very bad. So, by commenting first when working with existing code, you solve this problem as well.

    Take care,

    Brian
    --
    --
    http://www.assortedinternet.com/hosting/

  163. Get The Well-Commented Book! by Anonymous Coward · · Score: 0

    .:: Strunk And White-Em-C ::.

    ehehehe

  164. I'm not perfect by Anonymous Coward · · Score: 0

    I don't actually keep to the style of capitalizing the first letter of functions and not capitalizing variables, or vice-a-versa. Sometimes I swap these.

    But I do keep constants in all caps.

    More importantly, I keep the spacing standardized, and the braces in the same place all the time, except for one line routines. (rare)

    void OpenFile (cha r* filename)
    {
    ...
    }

    On the other hand, I get descriptive with comments. I usually write out what I am attempting to do with the program in pseudo code before I start coding, and then keep that in the code where appropriate: The program description at the top with the calls it makes; The pseudo code for the methods are kept with the methods.

    Even more so, I try to describe variables where necessary. It's usually not necessary to describe things like idx while in a method, but parameters and other variables usually are good bets for comments. Even a variable like MaxRecordSize can use a comment, since it might not be clear if it means the maximum size possible, or the maximum size found.

  165. Reverse engineering by Susky · · Score: 1

    I also do almost exclusive perl. And I have to deal with several legacy web apps that are failry complicated. I totally agree with commenting logical blocks of code. And I have a few other places that are useful for reverse-engineers...

    - If you have a fairly long subroutine, it helps the reader to comment the begninning AND the END of the block. Something like:

    # Comment briefly describing the upcoming block of code

    sub this_thing {

    lengthy bit of code

    } # End of this_thing

    And how about this:

    - Say you build a group of files where an executable chunk requires several other files. When you use a variable that is established/initialized in the "required" file, drop in a comment to tell the reader where the hell you got it from. It is extremely frustrating to see variables magically appear in a file, and then have to back-track a variable through 20 other files to figure out what you're doing with the value.

  166. The main problem with programming... by Homburg · · Score: 1

    Is quite the contrary - most programmers think to _much_ before they code, thinking about possible future extensions before making code that solves the current problems. Check out extreme programming (with it's motto 'Do the simplest thing that could possibly work') for more arguments in this vein.

    1. Re:The main problem with programming... by Anonymous Coward · · Score: 0

      I've lost track of the number of times people have come to me saying, "we need to modify program X to do this," and I was able to reply, "it's in there." There's a certain balance point between a Q at the other you never finish the project.

  167. unless your company is run by idiots by AssFace · · Score: 1

    I can recall a group of managers reviewing my code and one of the comments I got back was "too many comments"
    not sure what they were getting at. but in their honor I now make an effort to write more unreadable code and I never comment anything.

    job security :)

    --

    There are some odd things afoot now, in the Villa Straylight.
  168. class / struct by Frogg · · Score: 1
    If you define structure with public stuff but default, why the hell are you using 'class'? Use 'struct'.

    The original poster said he was programming Java, and in Java you've not got 'struct' like you have in C/C++ -- so you're stuck with using 'class' for everything.

    hth clarify things somewhat.
  169. Well-commented code by beth_linker · · Score: 2

    You know that your code is well-commented when the moderators give it a +5 Informative.

  170. Constructive comment on symbol names by mpsmps · · Score: 1

    Symbol names are generally a better place to put in comments than explicit comments. They are less likely to suffer bitrot and produce more readable code that almost looks like executable pseudo code.

    For example (In a full-width program screen, one-line functions would only take a single line, so the code bloat here is an illusion),

    ---
    // Not optimal

    i++; // Get next customer array index

    // Spam customer
    mail(customers[i]->email_address, mtext);

    // Lose customer
    delete customers[i];

    ---
    // No comments, but better

    inline customer_t *
    next_customer(customer_t *currentCustomer)
    {
    return ++currentCustomer;
    }

    void
    spam_customer(customer_t *customer)
    {
    mail(currentCustomer->email_address,
    exciting_offer);
    }

    void lose_customer(customer_t *customer)
    {
    delete customer;
    }

    customer = nextCustomer(customer);
    spam_customer(customer);
    lose_customer(customer);

    ----

    Note that inline functions can always be used to create new function names without overhead.

    1. Re:Constructive comment on symbol names by Beliskner · · Score: 2
      Disagree. When reading this code, since it's sequential the former is better. The second code fragment jumps around like a Mexican jumping bean for no reason. Think about it, what you're actually doing when you reverse-engineer it is using your brain to mentally inline the actual code above.

      I do believe however that if you increase the complexity with a few if() conditional statements that the second form would be better BUT the support function declarations should be more compartmentalise by a
      /*
      SUPPORT FUNCTIONS, MAIN EXCUTION BELOW
      */

      What I HATE is unnecessary function calls that give you a 10-level deep stack trace for a simple "Hello world"

      --
      A caveman dreams of being us, the incalculable power and riches. We dream of being Q, then what?
    2. Re:Constructive comment on symbol names by Mr+Z · · Score: 1
      What I HATE is unnecessary function calls that give you a 10-level deep stack trace for a simple "Hello world"

      You mean, like this?

      void lkjsdxc(void) { putchar('d'); }
      void cnqrucqin(void) { putchar('l'); }
      void __________(void) { putchar('.'); }
      void fslfkjdas(void) { putchar('H'); }
      void nkljh32jh345(void) { putchar(' '); }
      void lkj124gtyd6u57(void) { nkljh32jh345(); putchar('W'); }
      void jh76kl6h456(void) { cnqrucqin(); lkjsdxc(); __________(); putchar('\n'); }
      void _439583254(void) { lkj124gtyd6u57(); printf("or"); jh76kl6h456(); }
      void noj14nj4(void) { cnqrucqin(); cnqrucqin(); putchar('o'); _439583254(); }
      void sadjhasdfas(void) { fslfkjdas(); putchar('e'); noj14nj4(); }

      main()
      {
      sadjhasdfas();
      return 0;
      }

      --Joe

  171. Names by Art_XIV · · Score: 2

    IMO, the most useful and frequently overlooked element in documenting code is:

    Meaningful variable/function/method/class names!

    So many developers are satisfied with instance names like the ubiquitous "temp" rather than more meaningful ones like "jobStagingList".

    Well-chosen and expressive variable names go a long way towards making code self-documenting.

    --
    The only thing that we learn from history is that nobody learns anything from history.
  172. Code Dictatorship of the Proletariat by mgarraha · · Score: 2

    I believe peer pressure is the most effective way to improve code readability within a programming team. Coding standards can only address low-level issues, and only if they are enforced. Regular peer review focuses everyone's attention on true readability issues. A senior programmer can learn a lot from a junior programmer this way.

  173. Pseudocode comments by mlas · · Score: 1

    I've seen several links so far to the excellent Code Complete, and I second that one wholeheartedly. One commenting scheme that they suggest is writing your code first in pseudocode, just to get the logic down in plain English (or plain language of your choice), with indentations to indicate logic:

    Get email form data from client input
    Is email address valid?
    If yes:
    Construct email from user input
    Send email to address indicated
    If no:
    Send form back to user
    Highlight email field
    Show email validation message

    Once you're happy with the pseudocode (which, for me, more often than not clears up at least a little shaky logic for me before coding even begins), you can add your code to the pseudocode line by line, turning the pseudo-stuff into your comments. Combined with smart variable names, this is usually all you need. Sorry the example's in PHP:

    // Get email form data from client input
    $form = getFormInput($thisClient);

    // Is email address valid?
    if (validateEmail($form['emailTo'])) {
    // Construct email from user input
    $body = "Hi ".$form['emailReceiverName'].".";
    $body .= $form['emailSenderName']." says to tell you hello!";

    // Send email to address indicated
    mail ($form['emailTo'],$form['emailFrom'],$form['subjec t'],$body);
    }
    // If no:
    else {
    // Send form back to user
    // Highlight email field
    // Show email validation message
    sendForm("email", "That's not a vaild email address!");
    }

    OK, this is a pretty weak piece of code (I haven't had any coffee yet), but the point is that the pseudocode comments plus good variable/function names tend to be a real good
    start on your comments, almost self-documenting. And it tends to produce comments that straddle that line between too much information and not enough. Because the pseudocode shouldn't deal with the nuts'n'bolts of the programming language, you'll never write comments like the hated

    i++; // increment i

    although one of my Golden Rules of Technical Communication is "too much information is always better than not enough".

    --
    "Luck is the residue of design" --Branch Rickey
  174. Because... by Greyfox · · Score: 2
    Nothing makes a maintenance programmer want to slit his wrists faster than Hungarian Notation. Most of my work has been maintenance programming and by some very odd coincidence I've never seen code written by someone who knew how to program using Hungarian Notation. Every time Hungarian Notation was involved, the programmer was such a piss poor coder that it was generally better just to completely scrap their code and start from scratch. As far as I can tell, the programmers involved were using Hungarian Notation to reassure themselves that they knew how to program because they were using a "methodology" when in fact they were absolute fucking idiots who were just wasting the air we breathe. Perhaps not so coincidentally it was also the Microsoft coding standard a few years back. That explains rather a lot doesn't it?

    Now I'm not saying that all programmers who use HN are idiots. This is just in my experience, which is a relatively small cross section of a much greater pool of code. Seeing the style does set an expectation with me now, though, since all my experiences thus far have been bad. Perhaps one day I'll be pleasantly surprised.

    Hmm... asking about opinions on HN might make a good interview question (on either side of the table) now that I think about it. I'll have to add that to my list of questions for when they ask "Do you have any questions?"

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

    1. Re:Because... by jeremyp · · Score: 2

      When I'm programming for myself (not following somebody else's programming standards) I sometimes add a suffix to give me a clue about the name e.g _t for a type as opposed to a variable or _p as an abbreviation e.g. instead of "PointerToSomeData" I'll use "SomeData_p".

      OTOH I think Hungarian notation sucks. The main reason being that it is at the front of the variable name. I'm a firm believer in putting the important stuff at the front, which is what the variable is for. The M$ dev environment has a class browser and there is nothing more irritating than to see a nicely alphabetical list corrupted by the fact that everything begins with lpsz or m_.

      --
      All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
    2. Re:Because... by catfood · · Score: 2
      Nothing makes a maintenance programmer want to slit his wrists faster than Hungarian Notation.

      Unless.

      Your programming language has such weak typing that you have to use it to keep things straight. e.g., Clipper--it lets you declare variables but not their types.

      LOCAL sCustomerID
      is about the best approximation you'd get to what C++ would call
      std::string customer_id
      so at least there's an argument for keeping a Hungarian-style type prefix.

      If the compiler won't enforce type safety, a convention such as Hungarian might help.

    3. Re:Because... by Amazing+Quantum+Man · · Score: 2

      The one hungarian style habit that I picked up (from when I did VC for a living), and sort of still maintain is distinguishing class members from globals (and yes, I know I should use "::").

      I tend to have class members be m_this_member, but that's the only hungarian I still use.

      --
      Fascism starts when the efficiency of the government becomes more important than the rights of the people.
    4. Re:Because... by boots@work · · Score: 1

      Right, and that's why it was originally a good idea in C -- because in pre-ANSI C variables were very weakly typed, and you could easily use a (float *) when you wanted an (int *), with semicatastrophic consequences. If the compiler doesn't warn you, then it can be hard to keep them straight, so using Hungarian is an adequate workaround. Even in those days using a good Lint might have been better though.

      Of course modern compilers do keep types (more or less) straight, and so perpetuating this is pretty dumb.

  175. Andersen Consulting: Kludge by hughk · · Score: 2

    At one stage I had to do a quick and dirty with some software that was hitting priority inversion problems. I was working AC who had caused the issue by sloppy coding - I commented the fix with a warning that this was a "Kludge" and needed a proper cleanup later. AC petitioned for and got the "Kludge" word removed.

    --
    See my journal, I write things there
  176. Here's how I comment; it's pretty helpful. by Anonymous Coward · · Score: 0

    First of all, I name all my variables mnemonically, like workerFirstName, and describe them in a comment when I declare them. Then, if I am building an array from a database query, I lay out a description for each element of the array somewhere where it can't be missed like at the top of the program or the beginning of the subroutine where it's assembled.

    At the top of each subroutine I write, I include a short paragraph describing in plain english what the basic idea of the subroutine is, along with a short writeup of any weird things that aren't obvious, like maybe a pass-by-reference variable that is altered as a side effect (although I don't do that much, occasionally it does come up).

    I also like to break my code up into easily explainable chunks and add a short explanation of what's going on in between each chunk. For example, maybe one chunk would be a section that queries a database to see if there are any records for a particular client. If there are, we may exit the subroutine and if there aren't, we may proceed with an insert. Well, I would describe that chunk with a little blurb. If the chunk gets big enough to get its own subroutine, the blurb would describe why I'm using that particular function call. And so on.

    The important thing is, for each actual *task* in your program (a task being defined in my view as a single step like a database query or a test on some fetched data), there should be some kind of explanation of the task so that six months from now, when you're maintaining the code, you'll be able to remember what you did and why. This will save you SO much time and trouble down the road, it's not even funny.

    Another helpful thing: add a variable to the top of your program, called "amIDebugging". Set it to "TRUE" if you're still testing and "FALSE" once you're done. Set up your program so that if amIDebugging is equal to "TRUE", you open up an output file for logging, and in your code, whenever you have something you want to log for debugging purposes, output a comment or two, inside an if statement that tests this variable. This is cool, isn't it? As soon as you're done debugging, set the value to "FALSE" and all your comments and the log file go away. It's a little more helpful than using a debugger, because you can scan through the logfile if only, say, some records are failing. You can compare records that succeeded to records that failed and see patterns... Of course, that's more database oriented, but still.

  177. comment your question please by Anonymous Coward · · Score: 0

    I just don't see what you're driving at. Your question seems vague -- sort of "I don't understand what's going on sometimes, help?"

    I think Slashdot needs some kind of commenting standards for it's postings.

  178. There is a missing level of documentation by gradbert · · Score: 1
    Out here in the real world of programming I find that I have spent as much time reading other peoples code as i have writing my own. And I have run into two different levels of documentation. At the low end of the scale have been comments in the source code itself, at the other end have been the design documents. The problem with these is that there is a big gap between the two. The comments in the code tend to be rather myopic. They only tell you about a few lines of code or at best a function. (good comments by the way , should focus on what is not obvious from reading the code). At the other end are the design documents. These are almost useless for understanding the code. They are usually written before the code is written, and sometime by a differnet person. I saw one once that described a program as being a tcl extention, but the actuall program what a c++ monster.

    What is needed is a document that bridges this gap. you need to have something that shows how all the parts fit together, and how the data flows through the program. Now while you might have this in your design document, it needs to be referenced back to the code, tell what the real filenames, data types, functions are. Some detailed examples of how the program runs are very helpful.

  179. german comments by beddess · · Score: 1

    alright here's my little anecdote about well
    commented code.

    We grabbed some free code for a little utility
    to help with a project at work, with the aim of
    pulling out a bunch of the relevant functions and
    changing them around a bit. And when i looked at
    the code, all the comments were in german :)

    It may well have been amazingly well commented in german, but it didn't help us any.

    --
    "Weasling out of work is important to learn; it is what separates humans from animals. Except for weasels."
  180. Beagle Bros, Apple II, and Memory Lane... by teamhasnoi · · Score: 1

    IIRC, Beagle Bros. commented everything they did on the Apple II, and put a line or two of ****** to set it apart. Was great to find instruction in their BASIC programs, since they were anything but (Basic. AhHA!;P . That's how I learned the ins and outs of the Apple II. That, and playing lots of Rescue Raiders.

  181. Book on Code by Anonymous Coward · · Score: 0

    Get a book called Code Complete, it is basically a guide to writing good code, using good, solid, standard naming conventions, and proper commenting.

  182. people like you give coders a bad name by CrudPuppy · · Score: 1

    I have two words that come to mind when people see code like yours:

    JOB SECURITY

    and dont even take that as a compliment. it's childish and extremely detrimental to all progress in whatever company is dumb enough to employ you with such shitty coding technique.

    I personally have been a unix sys admin for almost 10 years now and find myself having to write a lot of perl to accomplish things automatically. if my employer feels the need to get rid of me after I have created such a great environment (where others can edit my scripts), that would be an indication to me that I need to train harder and become more skilled.

    keeping your job by writing crap that no one can possibly understand only creates hatred from the others who may have to read and alter your code.

    bah, I'm done.

    --
    A year spent in artificial intelligence is enough to make one believe in God.
    1. Re:people like you give coders a bad name by Anonymous Coward · · Score: 0
      keeping your job by writing crap that no one can possibly understand only creates hatred from the others who may have to read and alter your code.


      I agree with you on this. I prefer to keep my job by being valuable enough to my coworkers that all of them want me around. No one is immune to getting laid off and it may have nothing to do with how good you are. Sometimes, you work at the wrong site or on the wrong project. Having a whole bunch of good references can be worth a lot.
    2. Re:people like you give coders a bad name by NWT · · Score: 1

      keeping your job by writing crap that no one can possibly understand only creates hatred from the others who may have to read and alter your code.
      Hah! Sorry, but i am unemployed. No, i'm not really unemployed, i'm still going to school. I do not work for a company, and so i cannot lose my job. The code i write is for me, and works for me. I share it and if you don't like it, fine, i don't care.

      --
      Life sucks.
  183. Length of variable names by General+Cluster · · Score: 1

    Lots of people here are citing code complete. I am also a big fan of this book. In it, McConnell mentions a defense department survey where they found that variable names were most readable when they were in the neighborhood of 10-20 characters. He was mostly campaigning against short names, but long names are also difficult to read (and can be the source of hard-to-find bugs when character 75 should have been capitalized but wasnt).

    Writing 20-character names to avoid using a comment makes sense. If avoiding a comment means using an 80-character name, bite the bullet and use the comment.

  184. Another great book by KFury · · Score: 2

    For advice on commenting, as well as so many other issues that differentiate a journeyman software engineer from a master, I highly recommend The Pragmatic Programmer. When I start a new job, I often wish my coworkers had read it, and by the time I leave the job, I try and make sure that as many as possible have.

    All right, I know that sounds like a commercial, but it's really a great book.

  185. But there is such a thing as too cluttered by roie_m · · Score: 1

    You're correct about obscure third-party functions, but if you put too many comments explaining functionality (x->run(); /* run x */ i++ /* increment i */), your code will be cluttered to the point of unreadability.

  186. Avoid C./C++, embrace Python by Anonymous Coward · · Score: 0

    What to avoid? C / C++.

    What to do? Switch to Python.
    (in all seriousness, Python seems to quietly nudge users into nice behaviour, and its braces-free, consistent indentation - no more arguements about where to put a f'ing brace! - is a joy to read.)

  187. Look at the comments for SWISH++ by pauljlucas · · Score: 1

    As an example, I suggest you look at the comments for SWISH++. It uses function preambles and cites references to standards and other works.

    --
    If you reply, do so only to what I explicitly wrote. If I didn't write it, don't assume or infer it.
  188. Comments as a method for covering your butt. by MSUWalt · · Score: 1

    At my last (final?) programming job, we had the misfortune of being "led" by people with more business knowledge than computer knowledge and the inability to understand that knowing one thing doesn't necessarily mean you know everything. Thus, in addition to writing comments regarding functionality, I had to start writing comments to cover my butt.

    The last thing a programmer wants is for a programming manager to do a difference check on something he has checked in, see the changed code, and then come by asking why he intentionally wrecked the program. Every time we checked a program out, we were required to make a change management comment at the beginning. On one memorable occasion I had to put the finger on one of our managers for ordering me to make some changes that were irresponsible (hard-coded variables, etc) and basically set the stage for us doing some free future programming fixes.

    One thing I realized after working a couple of years is that you need to make signposts to help protect your professional reputation. Your face may be forgotten, but people 10 years down the road will know you by the code you have written. Ideally we have the time to completely rewrite bad code so that we can make our own elegant solution, but sometimes you only have 4 hours, and providing a work-around is the only way to do it. Do you want people later on thinking that you're a dumb, lazy bastard? No. If you're in a town with relatively few job oppportunities, you don't want the grapevine to start producing sour fruit with your name on it just because you've been told to do something cheesy, shady, stupid, etc.

    Did I get away with putting the manager's name and directive in my comments? Not entirely, but everybody knew afterwards that I wasn't the ignoramus responsible for what I had just done.

  189. KISS stands for many things... by janda · · Score: 1

    Keep it short, stupid. Functions (methods, procedures, whatever you call them) should be as short as reasonably possible. Keep it simple, stupid. Writing lines like that look like sumarian may be cool, but are going to be really hard to maintain. If it takes you longer to explain all the neat tricks you're doing then it does to write the line, you're being too cryptic. Keep it standard, stupid. The overuse of "#define FOO BAR" statements in c is a good example. Likewise, although =+ and += used to mean the same thing, the standard suggests that you use += nowadays. Keep it syntatic, stupid. The days of 6-character variables are long gone. The name of the variable should have some relevance to the use of the variable, such as "MailingAddress[]", not "MA[]". Finally, comments should probably never be used to describe individual program lines. If you need to use something like f03vun( //Verify the city/state. You should rename your function to VerifyCityState(

    --
    Karma: Food Fight (Mostly affected by Date Plate).
  190. Code Complete - Commenting non-code. by Blancmange · · Score: 1
    BRSQUIRRL:
    Regarding comments, the author Steve McConnell would be quick to point out that the best comments are no comments...that good code should flow almost like English and therefore document itself. Comments should be reserved for the (hopefully rare) cases where, for one reason or another, this isn't possible.

    One such case is where no code is written and none should be, but looks like a place where a particular few lines of code should be written. You need a comment to say "Don't do [blarg] because [wibble]". In other words, you should comment the conspicuous absence of code.

    Also, even 'obvious' comments, if written well can be a great help when they show the logical steps of a procedure as you're scrolling the page like a microfiche without caring to read the actual code till you find the place you want to work on.

    --
    Blancmange
  191. "Hungarian" notation - feh by ebh · · Score: 1

    Ahh, yes, another thing Microsoft claims to have "invented", even though we were using conventions like this in assembly language (and other languages whose only data type was the machine word) for decades...

    1. Re:"Hungarian" notation - feh by voncheesebiscuit · · Score: 1

      Microsoft can have HN, it sucks, nobody should be proud to claim it as their own.

    2. Re:"Hungarian" notation - feh by Anonymous Coward · · Score: 0
      we were using conventions like this in assembly language (and other languages whose only data type was the machine word)


      You just gave the best justification for using it and the context in which it is useful. Think about two values, say the return code of a function and a pointer to the return code. Hungarian Notation, or a variation on it, can make the later simply pRC. It is in situations like that where a well established convention reduces typing effort and makes your life easier.
    3. Re:"Hungarian" notation - feh by Doctor+Memory · · Score: 1

      I always thought that Hungarian Notation was created by someone who wasn't smart enough to write a cross-referencer.

      --
      Just junk food for thought...
  192. Too much better than nothing by Anonymous Coward · · Score: 0

    Admittedly sometimes people get carried away when commenting thier code. I would rather read too much than not have anything at all though. Just so long as they are saying something. Disk space is cheap now. Very cheap. It doesn't hurt to explain an algorythm or the data structures being used, even if they are in common use. Rather that than try and figure it out by reading some cryptic optimized code that, while it works, takes you a while to figure it out.

  193. "why" is more important than "what" by NickDoulas · · Score: 1

    I think the most value a programmer can provide in comments is details as to why certain code was written the way it was.

    Comments can certainly help a lot in terms of figuring out what someone's code is trying to do, but you can always figure that part out eventually.

    Sometimes the reasons why a programmer chooses to do something or do it a certain way are very important yet impossible to figure out by only reading the non-commented source.

  194. Memories!!... by Hoi+Polloi · · Score: 2

    Beagle Bros! *eyes tearing* I remember those halcyon days! So innocent...so much in so little RAM.

    --
    It is by the juice of the coffee bean that thoughts acquire speed, the teeth acquire stains. The stains become a warning
  195. This will lose you points at CMU... by Lethyos · · Score: 2
    Had a friend who I worked with at a start up one summer. Told me - quit frustratedly - that he lost points on an assignment for this...
    // increments i by one
    i++;
    Don't do that. Some code is self-documenting. Document pre and post conditions of complex procedures, and make notes of what they do internally. As for the algorithms described in those procedures, leave that for external documentation. (They often require proofs anyway which do not fall into the scope of source documentation.)
    --
    Why bother.
  196. Three levels of comment by Chacham · · Score: 1
    I have seen two types of comments. One is where the comments are all at the beginning of the code, but not throughout. This way you know *what* the code does, but not how it does it.

    The second type is code dispersed throughout, but none at the beginning. This tells you *how* it is doing it, whatever "it" is.

    So, I find the best is to use both. For one, at the very beginning of the code say a lot. Basically what the problem is (that required code), what the answer is (the program itself), and the approach to answering it (the style).

    With that in mind, any reviewer (including you!) will get the correct mindset when looking at the code.

    Then, a second level is needed. That is, the basic idea of what each section of code does. Something like, "this function...", or, "this loop...".

    For the third, each line of code gets a comment, on why it is needed. It is not always needed, but the overwhelming majority of lines could use a simple explanation.

    I find the second level to be the most important. And the third level to be next. I have many times skipped the first level, because it was blatantly obvious.

    As a rule of thumb, there should be more comments than code. If there isn't, you're not commenting properly.

  197. "Design Intent" a.k.a. "why" by SledgeHammerSeb · · Score: 1
    The only comment necessary in any code, answers the question "why". Don't insert a comment otherwise. If you consistantly apply the simple "why" test, you will have very valuable and maintainable code.

    Also, It does not hurt to be a little selfish when commenting code. Assume you will be the one who reads the comment(s) six months from now. So make it good enough so even you can understand what you did.

    I have been involved in software development for almost 20 years, and I have seen some bizarre stuff. I have found the only comments worth the effort answer the question "why".

    Cheers.

  198. To me... by hackwrench · · Score: 1

    a well-commented program is a program whose comments, if I saw just them and not the program, I could write the program without needing to think up implementation details, because they'd be all right in front of me. I have a dickens of a time trying to write comments that way though.

  199. Why, not what by andy@petdance.com · · Score: 2
    The rule to creating comments is simple:

    Explain WHY the code works as it does, not WHAT it does.

    Anybody can tell what it's doing. The reasons behind the design are another matter entirely. Here are some examples.

    # This code doesn't use URI::URL because URI::URL
    # doesn't handle foo:// URLs, at least as of
    # version 1.1.4.

    # This goofy switch statement is called
    # Duff's Device, and it speeds up the loop about
    # 15-20% under load. See p. 182 of "Writing
    # Efficient Programs" by Jon Bentley for more.

    # Using the DB this way is a performance hit,
    # but it's the only way we can be sure that we
    # don't have a conflict in the detail records.

    # Normally, we'd display magic-button-animated.gif
    # here, but Marketing hasn't given us the updated
    # version yet (as of 5/20/2002), so we have to
    # use magic-button-static.gif instead.

    And a real-life example that I pulled from our code:

    my $delve_link_image = "";
    # XXX The interface fashion of the week dictates removing the image
    # link. I'm leaving the code for now in
    # case fashions change again. -- mmh 020515
    #my $delve_link_image = (old code)

    Just make sure that coders know that their comments are to be factual, not emotional. Comments like "I'm doing it this way because Bob said I had to" are useless at best, and inflammatory at worst.
  200. Re:Microsoft Press - Writing Solid Code by Blancmange · · Score: 1
    ObviousGuy:
    Code Complete by Steve McConnell

    Writing Solid Code by Steve Maguire

    After reading Code Complete, which was great, I found Writing Solid Code a laugh a page for the first fifty pages and then more of a cry.

    Writing Solid Code is full of stupid things like:

    • the statement that putting more information in your code is more important than being able to read it out aloud (this may explain why so many coders can not communicate with people - their speech centres have atropied); and
    • the argument that hungarian notation is great because you can perform pointer calculus on complex C/C++ expressions and work out if the 'p's match all the '*'s (WSC fails to mention that such complex expressions are unnecessary and could be broken up into smaller fragments assigned to variables with meaningful names and those used in place of the complex expression)

    Code Complete has a nice section on how some coders write their code like love letters to a computer. It's great. Buy one for your dog too.

    --
    Blancmange
  201. Code Review by tarsi210 · · Score: 2

    Code Reviews - We love them, we hate them, but they work WONDERS. To have another programmer read over your code and have to try to figure it out is absolutely invaluable. Besides finding really obvious bugs or questionable places, your commentary can be critiqued as well.

    For those of you that program by yourself, do the "let-it-ferment" thing. Write some code, then stick it at the bottom of your stack and pull it out in a week. If the comments and code still make easy reading and good sense, keep it. Otherwise, assume if you can't read it in a week, no one else will be able to read it the first time, either.

    In an actual programming dept., if you're the manager/boss, make a set time each week to review code by other members and stick to it. Your programmers may complain but they'll complain worse if they have to be there till 2am fixing a really dumb mistake.

  202. "The Practice Of Programming" by replica · · Score: 1
    From Kernighan & Pike's seminal The Practice Of Programming:

    Comments are meant to help the reader of a program. They do not help by saying things the code already plainly says, or by contradicting the code, or by distracting the reader with elaborate typographical displays. The best comments aid the understanding of a program by briefly pointing out salient details or by providing a larger-scale view of the proceedings.

  203. An example by SageMadHatter · · Score: 1

    Let's define a constant in Java

    private static final int DEFAULT_WINDOW_WIDTH = 640

    That won't be needing any comments.

  204. Brooks! by mikeee · · Score: 2

    Very true.

    In _The Mythical Man Month_, Brooks wrote (paraphrasing here): Comment your code and I will remain confused; comment your data structures and your code will become obvious.

  205. Code Defensively by Anonymous Coward · · Score: 0
    I document anything that won't be painfully obvious to a quick perusal. Generally I have somebody else look over the code and I comment any section that they point at and say, "Now, why are you doing that?"


    Example: in one of my multi-threaded network applications, rather than call inet_ntoa to convert an address to dotted-decimal form, I in-line that code with some bitshifts and bitmasks. Any C programmer who will be working on a network application will probably know what it's doing, but why not just use the library function? Well, it's not thread safe and our installation doesn't have a standard thread-safe version available.


    So that one gets the comment.


    I generally comment any loop and explain what we're iterating over, and what we're doing with each element. I generally lightly comment the beginning of each function and explain what values it expects to receive and what it will possibly change.


    It's easy to write self-documenting code in C. If people used const qualifiers more when they pass things around, code would be a lot more readable. I spend more time figuring out where some random variable gets modified than doing anything else.


    The other thing I comment carefully is any pointer arithmetic or tricky pointer use. Even simple things like pointers to pointers ought to be documented. I assume that whoever is going to come modify code once I'm done with it has nothing but the source to look at to figure out what it does. I avoid leaving comments that inform the programmer to look at some external file or manual that they may or may not have access to. Why? Because I keep running into code that does just that and I can't even find the docs they're referring to.


    I think fairly brief, detailed comments are helpful. I also try to comment anything I do that will work but is bad technique or uses non-standard functions or what not.

  206. Re:Things to bear in mind (Tips With Editors!) by LF11 · · Score: 2, Informative

    I use Vim primarily, and I'm beginning to switch to using Emacs for coding.

    Vim has the most wonderful autocomplete hotkeys; type the beginning of the function/variable name, then press Ctrl-p to search up and Ctrl-n to search down through the file, buffers, etc. Now, long variable names are actually usable for 80wpm typists like me. (I'm around 40-50 for plain text).

    Does anyone know what the equivalent (or at least sorta-equivalent) commands are in Emacs?

    -Chris

  207. Re:Code Complete (do as I say, not as I do) by iamnotaclown · · Score: 1

    The problem at Microsoft isn't the programming staff not practicing what they preach. It's the fact that schedules, feature lists and release dates are driven by Marketing. Software developers are second-rate citizens after the marketing goons. It doesn't help that the carrot at the end of the stick is a shiny Ship-It award.

    I used to work for Microsoft, but I feel much better now.

    - name and address withheld by request

  208. Code Standards Site by Anonymous Coward · · Score: 0

    http://www.pablowe.net/standards/index.html

  209. favorites... by mikeee · · Score: 2

    My favorite was actually an error message; a piece of (commercial!) software crashed, with the error message:

    "Dave says this case can't happen."

    1. Re:favorites... by some+guy+I+know · · Score: 1

      I recall reading about a very large program, written in assembly language, whose only comment was "RIPLVB", next to the constant 1827.

      It turns out that 1827 was the year that Ludwig von Beethoven died.

      --
      Those who sacrifice security to condemn liberty deserve to repeat history or something. - Benjamin Santayana
  210. How To Write Unmaintainable Code by snowtigger · · Score: 1
  211. Find a FreeBSD machine by Anonymous Coward · · Score: 0

    and "man 9 style"

  212. "Why" not "what" by Mr.+Fred+Smoothie · · Score: 2
    I personally believe that code should be as self-documenting as possible; the "what" of what the code does should be explained to the extent practical by the variable, argument, function and method names (i.e. getAccountActivityForDisplay(const char *account, date_range from_to, account_formatter fmt)) and code structure.

    In comments, I think it's most helpful to explain the "why's" of the code, (i.e. :

    SomeClass someObj = null;
    try{
    someObj = someFactoryMethod(someInput1);
    }
    catch(SomeExpectedException expected)
    {
    // log but do nothing, conditional block will
    // handle this along with related problem 2
    LogMgr.logWarning(expected );
    }
    catch(Exception unexpected)
    {
    LogMgr.logError(unexpected );
    // don't show the user our stack traces
    rethrowUserSanitizedError( "User-sanitized message");
    }

    if(someObj == null || !someObj2.someCondition(someInput2))
    {
    showInvalidInputMessage(so meInput1, someInput2)
    }

    I think this helps prevent another programmer's incomplete understanding of the "what" causing them to overlook consequences of making code changes.

    --

  213. My list by edp · · Score: 4, Interesting

    One purpose of comments is to explain the code to another engineer (including oneself in the future). Another purpose is to demonstrate the code works, whether an informal argument that the code does what it should or a mathematical proof. These two purposes have different needs.

    For the former case, standard writing rules apply. Decide who the audience is. I often figure the audience is an engineer who knows the type of programming at hand, but doesn't know what is done by this particular code, and may or may not be familiar with the product, depending on circumstances. Knowing the audience tells you what assumptions to make and what has to be explained, either by prose or by giving directions to reference material.

    Write complete, grammatically correct sentences. This goes a long way to making comments comprehensible. Sometimes a little phrase won't be understood because the reader can't fill in the unwritten parts, or because there's ambiguity in the wording. It is okay to use short phrases when describing objects being defined or declared (e.g., "number of links to this object" or "dollars owed this customer), but keep the context in mind. Introduce the compound object with sentences where appropriate.

    "Dollars owed this customer" reminds me -- use units. Don't write "Money owed this customer" or "time since last update." Specify seconds or milliseconds, not time. Document how the object models whatever it is modeling. That may be a physical thing like time or a conceptual thing. E.g., if a pointer connects one object to another, document the relationship that represents. If a "debt" class contains a pointer to a "person," don't document it as "person associated with this class." Document the relationship -- this particular pointer may represent the debtor, the creditor, the escrow agent, or somebody else.

    Give context. I have seen thousands of modules that just leap into code with no explanation of what they are. Even if the comments say what a function does, a reader might not really understand it until they know what it is used for. Document where the code fits into the bigger scheme and what it is used for. Give the reader context so the purpose of the function makes sense. Even if a complete mathematical description of a function is given, so that the reader can precisely predict its behavior in every situation, it might not make sense to the human mind until they have a mental image or model of it.

    For the second purpose, demonstrating the code works, explain how the code implements an algorithm. It's not enough to explain what the steps are doing; you need to show how the total result comes out of the algorithm, unless it is something simple or familiar. E.g., a formal description of the long division taught in elementary school would generally be incomprehensible. "Find the largest digit d such that d times q is less than r[i]. Subtract d*q from r[i] to get r[i+1]. Append d to output..." Nobody seeing that for the first time would understand what it is doing, even if all the steps were clear. Even if you explained each step and explained the result, it won't be clear to some readers how the steps produce the result, so explain that.

    Document alternatives that weren't chosen, and the reasons why. If you were tempted to implement algorithm X but found you had to do Y because some error might occur, record that information. Otherwise, somebody working on the code next year might see your longer code for Y and change it to X without realizing the problem.

    This isn't intended to be a complete list, just what occurred to me at the moment.

  214. Self-documenting code needs little comment by werdna · · Score: 2

    Code should, so far as possible in context and langauge, be self-documenting, which is to say: the code by itself should lead me as far as it can in understanding. Good, well-designed OODLs make this somewhat easier than more traditional straigh-line imperative languages, but all high-level programming languages are capable of such practices.

    This means coding standards -- all code doing substantially the same thing should probably look the same. Indentation style should be sound and consistent, and unless strong countervailing arguments exist, all procedures should be very short, very well-named, and be very straightforward. As others have noted, variable names should be as precise and accurate as possible -- and, believe it or not, naming variables and procedures properly all the time is VERY hard.

    When code gets written, and you start smelling the "smells" of imperfect code, this means it is time to refactor: move variables out of objects to where they belong; collapse classes where appropriate, or break them up where appropriate; rename procedures. break procedures up to clarify (and rename), consolidate procedures to clarify (and rename) and so forth.

    An excellent book on refactoring is "Refactoring" by Fowler. Refactor until you shouldn't refactor any more. Then the code, sans smells, should read like a charm.

    Then, and only then, will you know what the comments need to say. Comments should be things not possible to express in the code per se, or which couldn't reasonably be understood without deeper analysis. For good, well-factored and self-documenting code, most comments are usually tight, short, rare and VERY helpful. Indeed, most comments in good well-factored code are usually unnecessary for experienced readers -- and too many comments actually get in the way of reading the code.

    One last thing -- keep your code comments current. Too often, changes are made in code without countervailing updates in the comments (since compilers tend not to pick up such things. The single worst possible thing is a comment that is wrong. Worse than not commenting at all. And both are heinous. Almost as bad is commenting superfluously or too much.

    My view -- write your code right. Then, the comments, when necessary, will be apparent -- kinda' like the code became apparent from writing right.

    1. Re:Self-documenting code needs little comment by Anonymous Coward · · Score: 0

      I agree! Here's something I made earlier...

      In general, I believe code should *not* be commented. Code should be as concise and clear as a poem, not as incomprehensible and verbose as a politican trying to avoid the question. Adding comments implies the programming language hasn't been used correctly in the first place.

      If a program is written well, it clearly states what it is doing. If you need to add comments, then either you aren't saying what needs to be said in the code - in which case you're written bad code - or you are repeating what you have said in the code. Saying the same thing again in a waste of time and space. Furthermore, since any translation involving a natural language can never include all the subtleties and details of the original (assuming you're writing your comment in, say, English), putting in commments that repeat what is said in the code will not precisely reflect the code, and thus guarentees that you are adding confusion, even if you remember to update to comment each time you update the code. This is not good.

      For example, I've often heard the opinion that when you write a function, you should add comments making it clear what assumptions are made in that function. This is the purpose of asserts and checks, etc. which should be present in the code, not noted in the a comment.

      Correct code should be clear, which requires that variable names, function names, etc., should make it obvious what the purpose of the variable/object is, as discussed elsewhere. They should be named to say exactly what they do or hold. This may mean long names. I prefer to use hungarian notation myself, but I don't think its obligatory.

      Correct code should assume anyone reading it understands the language used. Manintaining code is not a substitute for learning the language. You should not avoid using the sophisticated features of a language just because someone who may revisit the code might not understand it. If an employer wishes to use code as a substitute for sending someone on a course they're cheapskates who'll end up with a broken product - something not to be encouraged.

      This is not to say code should never be commented. I believe it is justified when:

      - refactoring;
      - the code has something odd in it to avoid an external ideosyncracy, such as a library bug;
      - code which has been heavily optimised, so that convential things are deliberately not done;
      - you can't use version control, and need to identify the five w's (who did what when where);
      - the code reflects a managerial decision which doesn't make programming sense (for example, to avoid a bug rather than fix it, because they're short of cash and need to get the product out now);
      - code which refers to an external document, such as a change control request, a translation from another language such as algebra, a sophistical algolrithm with which readers of your code may be unfamiliar, etc., in which case the comment reference the correct version of the document rather than copying it.

  215. Refactoring may be better by trajano · · Score: 1

    I'd rather the code point out the obvious for me rather than reading the comments and reading the code. I would recommend reading "Refactoring" by Martin Fowler(?) though not really end to end who has time for that.

    I generally would use comments to mark off candidates for large refactorings, e.g.

    // TODO: convert switch to polymorphism

    // TODO: FUGLY CODE, fix ASAP!

    To be honest, I don't really write code that is that readable to other people or myself sometimes. I am still human and I make mistakes. However, when I revisit my code or touch someone else's code, I try to reorganize the code and refactor things.

    Some people may disagree and say that these would slow down the application. However, if the code is more understandable, other optimizations can come about which are cleaner. Plus a good compiler can do a lot of optimizations for us already.

    However, the opinion above is only for application code. Meaning no really complicated algorithms that require a lot of math to understand. Though I rarely do algos anymore anyway so does not really matter.

    If I had to deal with algos, I think rather see someone do it in tangle/weave but the code has to be to the point, just the jist of the algorithm. The tangle'd code will just be added to the library since it can be reused elsewhere.

    I'd welcome your opinions. Thanks.

    --
    Archie - CIO-for-hire :-)
  216. Use the SERTS programming convention by Anonymous Coward · · Score: 0

    Search the web for "SERTS"

  217. It's sophomores like you... by Pollux · · Score: 5, Informative

    ...who make reviewers like me stare at computer screens for endless hours trying to figure out how the hell your computer code is supposed to work.

    Comment sparsely. Do not sprinkle your code with comments. Especially do not use comments like

    Yea, I can already picture your programming style. You'd make a 200-line function with the only comment being " // Creates hash table ". Question: Where does that leave me? When I find out that there's some problem in the hash algorithm, I have to dig through 200 lines of code to find some freakin' bug that is described only by "Creates hash table." Your example of why comments don't need to be made is a poor one:

    // increment loop counter
    loopCounter++;


    That is adding zero value.

    Yes, because it's one line of code, and the code is described through the variable. But when sifting through lines of code, you often find beautiful works like iHateMyJob++; or fuckMyBoss--; to name a few. And needless to say, they're uncommented in the code. Until computer code can be written bug free in complete English sentences (aka Never), the rest of your team of workers needs to understand what your code does.

    Personally, I make sure every function says what goes into it, what comes out of it, and what setup (variables, etc.) need to be made for it to be called. I do not comment every single line of code, but I do make sure that every line is accounted for by descriptive sentences, explaining the task that I wish to accomplish as well as what variables / registers / actions I take to accomplish the task.

    Every time someone has to change some code, you've just forced them to double their workload, and change some comments too.

    Okay, this just pisses me off. You didn't mean what you said. Here's what you meant to say:

    Every time I have to change some code, you've just forced me to double my workload, and change some comments too.

    I can assure you, from a reviewer's point of view, comments SAVE my time from trying to understand what each piece of code is trying to accomplish. Commented code may make you work extra time to detail the lines of code (I do admit, some programmers are quite tallented at keeping track of every single line of code in their head as they work on it on the computer), but it saves tremendous amounts of time once that chunk of code needs to be integrated with other chunks of code into the final product.

    1. Re:It's sophomores like you... by Darth_Burrito · · Score: 2

      But when sifting through lines of code, you often find beautiful works like iHateMyJob++; or fuckMyBoss--; to name a few. And needless to say, they're uncommented in the code.

      Not necessarily true, I have seen examples of the above where the coder actually went on to make comments regarding his choice of variable names. He ended up going on about a rant involving low self esteem.

    2. Re:It's sophomores like you... by MisterBlister · · Score: 1
      That is adding zero value. Yes, because it's one line of code, and the code is described through the variable. But when sifting through lines of code, you often find beautiful works like iHateMyJob++; or fuckMyBoss--; to name a few. And needless to say, they're uncommented in the code. Until computer code can be written bug free in complete English sentences (aka Never), the rest of your team of workers needs to understand what your code does.

      If your problem is that your programmers are naming variables thusly, the issue is that the programmers are retards to begin with. Do you really think that someone who would so poorly name variables is going to bother writing useful comments? I'd fire a programmer who named variables iHateMyBoss but commented them well long before a programmer who used comments very conservatively but chose well named method & variable names.

    3. Re:It's sophomores like you... by lostguy · · Score: 1
      You'd make a 200-line function with the only comment being " // Creates hash table ". Question: Where does that leave me?


      Umm, ready to kill an idiot for not decomposing a 200-line function into smaller functions?

      There are statistical optima for function lengths with respect to defect levels, and 200 lines is not it for C++ code.
    4. Re:It's sophomores like you... by mder · · Score: 1

      Hmmm. I've encountered two schools of thought regarding the 'every line is accounted for by descriptive sentences' thing.

      The first is yours - you like to *read* a piece of code ( including comment.. ) and, as far as is possible, be completely informed as to it's purpose. I must admit, as a reviewer I also appreciate 'self contained' code - code that doesn't require me to chase around a zillion files/documents in order to understand *why* 'flubberdigit13 ^= DDIC_1473' is a good thing to be doing at this point.

      But there's also a 'level of abstraction' decision to be made here. To what extent/at what level should 'design' be captured by comments embedded in the source ? I think that a feature of approaches such as yours is that it encourages the inclusion of 'higher level' design information into source.

      Hence the other school of thought - comments should clarify the narrow-focus details of particular coding constructs, but should deliberately avoid re-explaining design details which are captured in some 'out of band' fashion. At most, a design cross reference may be justified.

      This has maintainance benefits - changes to the design/architecture are no longer so tightly coupled to the actual source code itself, and the sheer volume of text to be maintained is reduced. It also allows design to be captured in the most appropriate form ( which is not always purely textual ), without forcing a coder to make a clumsy and inaccurate ad hoc mapping into a textual format just for the purpose of creating a comment.

      So I guess I'm just saying be careful about requiring voluminous explanations in source code - 'nice to review' is not always the same as 'nice to maintain'.

      --
      Speak now. Peace is overrated.
    5. Re:It's sophomores like you... by SlugLord · · Score: 1

      Well I do think he has some point, nonetheless. Granted he's foolish to discount inline comments outright, but it can be overdone...

      //increments loop variable

      is probably overkill, but if it were something more like

      //finished with this cell, move on

      might be an appropriate use for counter++

    6. Re:It's sophomores like you... by ahde · · Score: 2

      Personally, I make sure every function says what goes into it, what comes out of it, and what setup (variables, etc.) need to be made for it to be called.

      Congratulations, you've just described a function header. The only reason to include that kind of info in comments is if you are using some automatic documentation tool like javadoc--which is a *very* good reason, but a waste of time and space otherwise.

      Overall, you're better spending 10 minutes deciding on accurate, descriptive function and variable names are than 5 minutes duplicating your header in pseudocode or filling the page with descriptive comments.

      Any complex algorithm (like creating a hash table) is not going to be able to be debugged from reading the comments anyway.

    7. Re:It's sophomores like you... by Anonymous Coward · · Score: 0

      Well I do think he has some point, nonetheless. Granted he's foolish to discount inline comments outright, but it can be overdone...

      //increments loop variable

      is probably overkill, but if it were something more like

      //finished with this cell, move on

      might be an appropriate use for counter++


      Wouldn't it be perfectly clear if you just used (eg) CellReference++ instead of counter++ ?

    8. Re:It's sophomores like you... by Boiled+Frog · · Score: 1

      Congratulations, you've just described a function header. The only reason to include that kind of info in comments is if you are using some automatic documentation tool like javadoc--which is a *very* good reason, but a waste of time and space otherwise.

      I disagree. Even if you don't have a javadoc-style tool -- I admit it's better if you do -- it's good to have function headers. If there's a function header, I can see what promises and requirements a function has without having to read the function or trying to track down some external documentation that may not even exist.

  218. Knuth - Literate Programming by goodviking · · Score: 3, Insightful

    Some variation of the methods described in "Literate Programming" by Donald Knuth are a good place to start. In summary, Knuth says that you should be able to extract from the same source both machine instructions, and a human parsable document, with unusually high importance placed on the later. Whether or not you want to imbed LaTeX into your document is up to you (I never have bothered), but on the whole find something that will make your code and algorithms understandable to another programmer who's never met you (because that's probably who will be either grading or maintaining your code at some point).

  219. Sometimes they just dont grok it. by crovira · · Score: 2

    I once wrote some code in Command level CICS-COBOL that used GETMAIN and FREEMAIN to do dynamic memory allocation so I could take a data structure in a file (by order.item.warehouse.quantity,) and stand it on its ear (by warehouse.order.item.quantity,) to get at the data that way.

    It worked fine and I documented it and the BLL cell layouts properly but the CONCEPT of dynamic memory allocation proved to be the stumbling block.

    I ended up giving a course on my hack and they still didn't get it. I eventually left the company and left them with working code that they were not intellectually capable of modifying. I didn't feel good about that.

    Sometimes they don't understand one concept (object instance relationships) and sometimes its another (state machines) but I always seem to encounter people having problems that they are too busy struggling with to see that the problem lies with their application of an innapropriate solution.

    AND THEY AREN'T MENTALLY EQUIPPED TO PERCEIVE THE TRUE DIMENSION OF THE PROBLEM. (Not its metric, [I didn't say SCALE of the problem,] but its topology.)

    There is bugger all to be done in those cases.

    Being ignorant of the uses and applicability of state machines leads to combinatorial explosion of GUI (and supporting objects) code to handle different state transitions.

    Rather than maintaining the state machines, (not even the engines but the state transition arcs and nodes,) they were ending up replicating GUI code.

    That was really fucked up. I was asked to resign. I did, heaving sighs of relief.

    (And then somebody used the building as a landing strip. Yeah. I'm still fucked up about that...)

    --
    MSBPodcast.com The opinions expressed here are my own. If you don't like 'em... Think up your own stuff.
  220. They'll always complain.... by pjrc · · Score: 2
    Well, they'll almost always complain that your code "isn't commented enough", when they are forced to read through it and learn enough to make some changes.

    One of the best examples from my personal experience is a fairly large 8-bit assembly language project I did (for an embedded PIC16C76-based product). The project has approx 25000 lines of assembly code distributed in about two dozen files (which built about a dozen different flavors of the product, though virtually no code was duplicated due to common code being used by includes... it really was about 25k lines of assembly!)

    The first time another programmer worked on it, he of course complained that it wasn't commented very well and lacked documentation.

    In fact, a quick grep ';' *.src | wc compared to a wc of all the files revealed that 34% of the lines had a comment (the vast majority the whole line was a comment, as I tend to write blocks of prose above sections to explain what they do, rather than a comment for each register move).

    But if 8500 lines of comments wasn't enough, there was an 11-page document I wrote about the design of this firmware... about half of it was a "roadmap" that described the "larger picture" of the firmware and how it was arranged into the various files. The other half documented specific tricks (like a 6-instruction sequence including a skip-past-a-skip that achieves a 16 bit add/subtract in that PIC part which lacks carry input). There was also a lengthy discussion of the overall strategy for managing the various bank-swapped memory of that processor and some other stuff about the real-time performance (that was a hard real time application).

    Learning is painful for most people, and learning someone elses code seems to be absolute agony for many engineers & programmers. They always complain that you didn't document/comment the code enough, even in an extreem case like this!

  221. Happy medium by davebooth · · Score: 2

    Lots of posts on quantity of comments and theres a bundle of good arguments for both the more-is-better folks and the dont-overcomment advocates. Similarly the drive to make your variable names meaningful is worthwhile but the one addition to any code, be it perl, C or anything else, that makes maintaining it easier has to be the humble newline.

    The important thing is not how many comments of what type but the overall layout of the source so that it is consistently understandable on reading through it. If a comment is required to accomplish that then insert one. If, OTOH, all you need to do is break up and indent the lines a bit more intuitively then do that rather than trying to explain the more awkward structure in a comment.

    Sure, you can easily pack a fully functional perl script into a 4-line .sig if you want but a 100 line script thats as squeezed together as it possibly can be becomes unreadable no matter how many comments are inserted into it. If a single line of code does more than one step in your program then consider breaking it up. If it absolutely has to be one line in order to work then backslashes are your friend. The guy that reads your code to find out how you did that after you've moved on to bigger and better things might be an entry-level hire who has enough of a learning curve to cope with without wrapping his/her head around tightly compacted code as well.

    Remember how simple you kept it when you first started learning a language? Keep it that way when you're more experienced unless theres a reason to do otherwise.

    --
    I had a .sig once. It got boring.
  222. Experience, Comments, and Design Patterns by Bouncings · · Score: 2

    I've noticed that the exerience of the programmer, like most aspects of software design, is only an asset if the programmer has done a variety of tasks. I've seen veteran programmers who have only written code and actually never maintained it. They never actually learn what maintainers need to make modifications, so the comments only help them write the code.

    My best advice is to do as many tasks in the software development process as possible. This includes testing, maintaining, and working with users and even technical support (gasp!). Don't get stuck doing one thing. You won't get better and better at it, you'll become more out of touch and therefor do an even worse job.

    Experience is best measured in deversity, not years.

    --
    -- Ken Kinder ken@_nospam_kenkinder.com http://kenkinder.com/
  223. Re:Describe your design decisions and thought proc by scrytch · · Score: 2

    If you define structure with public stuff but default, why the hell are you using 'class'? Use 'struct'. The only difference between 'class' and 'struct' is that 'class' has private members by default, while 'struct' has them public by default.

    Why should he? He's not writing C. Why should he have to double the syntax when, as you said, 'class' would do the exact same thing? Maybe it's better that he explicitly has to make everything public. Maybe he thinks, as do programmers in most other languages that support classes and struct, of structs as being mere aggregated data and classes being actual object definitions. Or maybe he just likes browsing through classes by searching for "class " in his editor. Just because the language supports something doesn't mean he has to do it, especially when it actually reduces the value of the code.

    --
    I've finally had it: until slashdot gets article moderation, I am not coming back.
  224. Well-commented code by YellowElf · · Score: 1
    I have several clear goals when I write code:

    • Start with descriptive variable names and, where possible, code structure that models the problem domain. There is a necessary judgment call, as you can get carried away with variable names, such as m_lpszRepresentationOfDatabaseState. The hungarian notation thing can be helpful, but I sometimes find it tedious, especially for local variable names. You have to strike a balance between consistency and usability; if it's a pain to maintain, someone's gonna choke on it later and just not keep it up.
    • Let the code formatting accurately reflect its structure. I go out of my way to align items and maintain a consistent formatting style. It's easier to get a visual picture of how the code works. You might not think of this as commenting code, but it does help the reader understand it-- which is really the larger picture of what commenting is about.
    • Comment the non-obvious only. Don't comment a line like "x += 2;" with "Add 2 to x". Sheesh, we all knew that. As much as there is an argument for "all code should be completely self-commenting"--and I once worked in a shop that regularly removed comments from your checked-in code--you can't put everything in code. Some code just can't accurately reflect the decisions behind the logic, especially in code that's been highly optimized.
    • Comment arbitrary decisions. Why did you decide to limit the array to a static 25 items instead of a self-sizing dynamic array? Why are you doing a quick sort instead of a bubble sort? You don't have to do this for every little thing, and some are obvious (why are you using an int here instead of a char*?), but if it would help a new reader understand things, write it. Manifest constants can be a big help here; use that feature if your language supports it.
    • Comment code decisions based on external information. You don't have to reproduce the documentation for the other component or API, but at least mention it where it's not obvious. "There is a limit of 45 entries for the FoobieBletch address table. See the FoobieBletch documentation in Appendix C."
    • Comment unconventional areas. If you are iterating over an index from 1 to size instead of 0 to size-1, point it out so your readers don't think you're a C-newbie. I find it's also a good practice to comment that you're deliberately leaving out a break statement in a switch. Also, sometimes you have to write workarounds for other people's bugs or misfeatures (like MS' CString class), so it's a good way to point out that the bozo isn't you.
    • Keep comments brief. Verbose comments are boring to read, so your readers won't read them. They're harder to maintain, so maintainers won't maintain them. They're harder to write so you're more likely to make a mistake. They'll become out of date and mislead some foolish coder who forgets that comments are not code.
    • Don't use comments as source control.I hate seeing items like "This code changed by JZR on 3/18/1997. BEGIN CHANGE--" It doesn't help me understand the code. It can get cluttery, especially with common header files or high-traffic development areas. Let your source-control tools provide this information for those who need it.
    • Don't comment out code for long periods of time. A text search will still find the comments and make the searcher wade through more junk. Not to mention if you comment out all the calls to a function, the function itself still looks viable. A temporary commenting out is okay as a quick tool for development testing, but with the right source-control tools you won't need it.
    • Take the time and effort to review existing comments before you check in changed code. This is a hard thing to get people to do, but it helps to maintain consistency. If you don't do it yourself, you're just plain lazy and don't care about those who follow you. Coding is usually a team effort, even if the team is you now and you six months from now when you've forgotten this little stretch of structured wasteland.
    • Don't get too fancy with commenting. It can be tempting to block your comments with pretty /*********/ boxes but if it's a pain to maintain it just gets in the way.


    I'm sure I have more of these somewhere but these are off the top of my head. Besides, I'm in danger of violating my own "Keep comments brief" rule. If I think of more I'll post them later.
    --
    Insert witty saying or aphorism here.
  225. Good reference for coding style by Anonymous Coward · · Score: 0

    The Indian Hill C Style and Coding Standards is probably something everyone who codes should have read at least once:
    http://dogbert.comsc.ucok.edu/~mccann/cstyle.html

  226. They MUST vs. they WON'T by Mr.+Fred+Smoothie · · Score: 3, Insightful
    One of the great insights of the Agile Software Development movement, if you ask me, is the realization that a process which doesn't take into account the strengths and weaknesses of the people who will use it is flawed.

    So, it's one thing to say "if they change the code, they MUST change the comments", but realize that unless you have the ability to force the issue (a tool to make you change comments before saving changes, managers who care more about firing programmers who don't follow code standards than avoiding schedule slippage -- hint: I've never seen one of these, EVER), 9 times out of 10, they just won't do it. It's like teaching abstinance as a method of reducing teen pregnancy.

    Thus, the practice of having comments which are redundant w/ the code is simply setting the project up for failure as the parent poster pointed out.

    --

    1. Re:They MUST vs. they WON'T by ahde · · Score: 2

      More like teaching condoms as a method for avoiding pregnancy. It's an extra hassle. Sometimes you don't feel like it, sometimes you don't have time, and sometimes it just doesn't work right.

  227. Primary audience of code is other programmers by p3d0 · · Score: 2
    Just like any writing, the author of code has an audience in mind. Too often, this audience is the computer or compiler. However, the compiler will be able to handle just about anything you throw at it--see the obfuscated C contest for evidence of this--so to consider only the compiler will leave all other audiences (including yourself in a few months' time) in the dark.

    Think of your code as a document that describes how something is done. Always imagine that it is being read by an intelligent person who doesn't already know how or why this thing is done in a certain way.

    Oh, and never define words in terms of themselves. This is not helpful:

    int markedTreeCount; /* How many trees have been marked */
    Consider: if you saw a definition like this in a dictionary, you'd laugh out loud. Every definition should either (1) completely avoid all the words in the term being defined, or if that is too cumbersome, (2) have a reference to a document/glossary/whatever that describes those words in more detail. If your project has no such glossary, it probably needs one.
    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    1. Re:Primary audience of code is other programmers by smallstepforman · · Score: 2

      The primary audience of code is not the compiler. Anyone SW engineer can write code which a machine can understand. A great SW engineer writes code which another human can understand. A HUMAN is your target audience.

      Quote from Martin Fowler, Refactoring.

      --
      Revolution = Evolution
    2. Re:Primary audience of code is other programmers by p3d0 · · Score: 1

      Interesting. I have never read that book, though I did read Bill Opdyke's thesis over a decade ago. Perhaps that is where I got this idea, though I think it's not too much of a leap to imagine I thought of it independently, since I'm sure it's a conclusion many have reached. It's not exactly rocket science.

      Thanks for the reference!

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  228. Make your code readable! by UncleRoger · · Score: 2

    It's simple:

    Use COBOL!

    --
    Stupid people will be persecuted to the fullest extent allowed by law.
  229. Recommended Classic by Genus+Marmota · · Score: 1
    The Elements of Programming Style by Brian W. Kernighan, P. J. Plauger. ISBN: 0070342075

    I read this brief classic a long time ago in Math 131 (Intro to Fortran) and it set my style for the rest of my carrer. The quality of clarity in programming is independent of the language used. Besides all the excellent advice others have posted, I'd keep this principle on mind:

    The source code is not only instructions for the machine, it is the most important means of communication between the software developer and the (eventual, inevitable) maintainer. Ask yourself, "If I sent this code to another developer who's completely unfamiliar with the project, would they be able to quickly understand what it does and how?"

  230. Comment the WHY or the HOW and not the WHAT by angel'o'sphere · · Score: 2

    Hm ... I find the following observation interesting:

    Most programmers (especialy those without formal education) find programming more an art than an engineering task.

    If you talk to them about a "software project" they imediatly tell you HOW to do it and skip the "analysis phase" in which you usualy try to figure WHAT is needed.

    Another thing, similar interesting is: how do you teach or how do you learn?

    The best way is to start with the WHAT. That means simple facts, like: "a programming language supports the concept of storage and the concept of instructions(usualy)".
    Supported with simple examples.

    Then you teach the HOW. How to use the concept of storage? How to use the concept of instructions?
    Supported with simple examples.

    Finaly you teach the WHY. That means you teach the principles which lead to "the physical laws", efficiency, beauty or in depths insights. E.g. why to use a guard element at the end of an array while searching the array with a loop.

    If we go building a new application for a customer we usualy do an OO analyis and a OO design. (If we are engineers and not artists)

    That means we first analyze the WHAT. What is the application supposed to do? Then we can go deeper and analyze HOW is the application supposed to do it?
    So far we are far away from code. We only found classes, some attributes and some few methods. Because we looked only on the WHAT. The HOW, we looked on so far, was only the user point of view.
    If we shift to design, to actually get closer to the code, we more and more concentrate on asking us HOW. HOW will it work, HOW can it work, HOW should/will it be implemented to work. From the domain constraints of the application we shift into technical constraints of the run time environment and the implementation.

    So .... writing program code is mentaly a thing where you fiddle with the HOW.

    How to get a new customer into the DB? The code describes how to do it ... even if the code is hard to understand.

    The first goal in coding(the foundation is layed by the analysis) is using good class names and good method names(or the equivalents if you program not oo).

    This gives you an insight WHAT you want to achive.
    While you code you fill methods and add methods(if you otherwise would write to big methods) and craft HOW to achive it.

    So, what should a comment now do? The comment is needed to fill the gap, or to express the third point of our mental model we make: WHY.

    OOPS? Yes, we know WHAT we want, we know HOW to get it, but WHY do we get it in that way?

    Comments are needed to express WHY we in certain cases drop a habit. (e.g. most for loops in C/C++/Java have for(;x less_than y;) ... if we need x == y, suddenly we should write WHY we need that)

    Several posters pointed out this is a dumb comment:
    i++; // increment i

    Right! But it is not dumb because it is obvious what i++ does, or because it is superfluvious.

    It is dumb because it explains the WHAT. It says: what the line of is code doing.

    Unfortunatly comments like that are used in language teaching books. To TEACH coders that "++" means (post-)increment.

    New coders learn by that: you have to comment like this.

    So again: don't comment the WHAT. Comment the WHY.

    In teaching OO my rule of thumb for method sizes is: it needs to fit on the screen of my lab top.

    As I beam with my labtop onto the wall, I use a big font, like 18. Methods then have a size of 8 lines or so.

    If a method gets longer, you usualy make sections and write a comment on top of that section, do you?

    Well, thats an excellent way to extract a method name from that comment and to put that section into a "protected" method.

    With having more methods, some of them protected and factored out of otherwise to big methods, we suddenly get more freedom to "modify/extend" derived classes. And: oops, we suddenly are close to use a well known design pattern: Template Method. The big method is smal and calls several small methods. The big method is the Template Method, the smaler ones are hook methods. In a derived class suddenly I can moddify such a single step of the algorithm by overwriting a hook method.

    So, now you probably have a class with 25 methods?
    Probably you should divide the class up then ...

    The art of OO Analysis gives you the insiged to realize early that a class mixes two concepts and therefor should be split up into two classes.
    E.g. keeping all attributes of an author in the book class, just lets the class explode and is wrong anyway.

    The ART OF OO PROGRAMMING is to anticipate such refactoring points and to use them wisely when appropriated(and not to use them when not).

    Programming in itself is no art. Just like painting in itself is no art. Artist usually studdy 10 years and more under the guidiance of other artists .... coders should do the same.

    My programms have nearly no comments. Except for classes, WHAT is it for. Methods and their parameters, WHAT are they for, and sometimes HOW do they work.

    If a method body is not clear, or if I feel I should do it, I explain WHY I do certain things like I do.

    Except for counters all variables have long explaining names. Methods and classes anyway.

    I do not use index variables like "bookCounter" because a loop like:
    for (int bookCounter=0; bookCounter less_than MAX; bookCounter ++) {
    if(found(book[bookCounter]))
    return book[bookCounter];
    }

    meets my criteria of: it does not give any benefit. I see WHAT is going on, and there is no special need to explain WHY something is happening.

    A simple 'i' is good enough. (I used for more than 10 years variables like bookCounter ... and dropped it some 4 or 5 years ago.)

    The hint, pointed out by several posters, to use assert() instead of comments is absolutely valid. Drawback: tools like doxygen and javadoc, do not transfer those asserts into the outside method documentation. So by browsing HTML docs you do not see it.
    If you have to dig into the code anyway, an assert is much better than a comment. Especialy if you have a test suit triggering your asserts.
    To bad, realy to bad, that SUN went for an assert facility in Java 1.4 and did not use pre- and postconditions like Eiffel :-(

    Regards,
    angel'o'sphere

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  231. Doc & code sync always drifts! by Mr.+Fred+Smoothie · · Score: 3, Insightful
    So what happens when the code changes and breaks the assumptions so fastidiously outlined in the documentation?

    It's less of an issue w/ Javadoc and Doxygen comments (which is embedded in the code) than external documentation, but the fact is that managers reward code changes, not documentation changes, and programmers are lazy.

    Until you can change these basic, simple facts, what are you going to do? One strategy is to encourage self-documenting coding standards as well as encourage documentation updates. But people NEED to remain aware of the basic principle that the only authoritative documentation is the source code itself.

    --

    1. Re:Doc & code sync always drifts! by slamb · · Score: 1
      So what happens when the code changes and breaks the assumptions so fastidiously outlined in the documentation?

      You know what pre- and post-conditions are no longer true, so you can fix the bugs you've introduced. If you actually read the documentation, you can fix the bug before it's a problem. If you don't, your successor will have an easier time fixing the bug after you're fired.

    2. Re:Doc & code sync always drifts! by Mr.+Fred+Smoothie · · Score: 2
      If you don't, your successor will have an easier time fixing the bug after you're fired.
      Programmers fired for not updating documentation? What planet do you program on? I can't even get programmers fired for writing classes with single accessor methods for accessing multiple data fields (taking the fieldname as a string, of course).
      --

    3. Re:Doc & code sync always drifts! by slamb · · Score: 1
      Programmers fired for not updating documentation? What planet do you program on?

      Wishful thinking and low blood sugar may have been involved. In any case, I was trying to say that paying attention to the documentation would avoid bugs, and the bugs would get him fired eventually. Even so, you're probably right.

    4. Re:Doc & code sync always drifts! by ahde · · Score: 2

      whoops...

      just sent out a bean with methods like:

      setParamName(param)
      setParamValue(value)
      getPa ramValue(paramname)

      All took sinlge String. And I did it to avoid introspection. Sure makes jsp easier though.

    5. Re:Doc & code sync always drifts! by Mr.+Fred+Smoothie · · Score: 2

      Um, if you want to avoid using introspection, why don't you just stop using Java Beans and access your object's methods and fields directly?

      --

  232. When I get bored... by Rorschach1 · · Score: 2

    I write all of my comments in haiku.

    comments in haiku
    not for any good reason
    i was really bored

    Ok, not a really good example, but you know what? No one's ever said anything about it.

  233. eat your veggies by _|()|\| · · Score: 2
    most people who read [books on nutrition and dieting] end up eating junk food anyway because they just don't have the time to do it right.

    I use habits learned from Code Complete every day, such as taking the time to choose a good name (no, I'm not talking about Hungarian notation). The single most important point of the book is that people read code, too.

    I found Writing Solid Code, another Microsoft Press book, to be less enjoyable. It was, however, worth its price for one C habit I've retained: put the rvalue on the left in equality tests. For example: if( 0 == foo ). Why wait until run time to find that you've accidentally assigned, instead of compared?

    As to "junk food" in programming, I prefer to categorize all of that as "rapid prototyping."

    1. Re:eat your veggies by Anonymous Coward · · Score: 0

      Thanks a lot for that equality test. I really mean it! :D

    2. Re:eat your veggies by Jaeger · · Score: 2
      Using the -Wall switch with gcc (and, I assume, dinking with the options on other compilers as well, although I don't have as much experience with them as I do with gcc) will warn you if you try to do something stupid like if(foo = 0). It's not foolproof (it suggests that you can put an extra set of parenthesis around the equality to supress the warning), but every thing you can get to help you out is a good thing.

      My all-time favorite bug that ever crept into my code was in a C++ constructor. I wrote something like

      MyClass::MyClass(int _blah) : blah(blah) {}
      instead of
      MyClass::MyClass(int _blah) : blah(_blah) {}
      Even with -Wall, gcc still didn't warn me that I was doing something that made no sense at all.
    3. Re:eat your veggies by flossie · · Score: 2
      For example: if( 0 == foo ).

      I thought that was a really great technique when I first came across it and used it extensively. However, it is shocking how disruptive this construct can be to one's train of thought when reading through a complicated algorithm. It is also of limited value as it doesn't really help when it becomes necessary to test if (foo == bar). Consequently, I have reverted to relying on the compiler to tell me when I have made a typo.

  234. Comments in Code by Simonetta · · Score: 1

    Often the coder can describe the program in one-on-one discussions far better than he can write a detailed description or remember to add comments.
    In this case, get one of those speech-to-text programs like Dragon or Kurtzweil or IBM and have the programmer go through the voice training. Then have him (it's almost always a him) do a long description of the program in voice and append the text generated from the speech to the code.
    If this is too much of a hassle then simply use a boom box to voice record the programmer throughly describing the code and convert the recording to a mono voice quality MP3 file. Include this MP3 file with all of the other files of the project. Better yet, link the sections of MP3 description right into the code. This entails having a second source code file that isn't ASCII, but it's the 21st century and it's time to upgrade these old text-based inflexable compilers to multimedia input/output.
    This is quick, easy, and a whole lot better in the long run than incomprehensible comments scattered in the source. Programmers and project managers have to start thinking 'outside of the box', especially since programming is the most conservative (and reactionary) sector of the computer/electronics industry.

  235. What is well-commented code? by Anonymous Coward · · Score: 0

    Anything written in Perl.

  236. [OT]Re:Things to bear in mind (Tips With Editors!) by follower-fillet · · Score: 1

    Try Meta or Alt + '/'

  237. Never? Not even on an embedded system? by yerricde · · Score: 1

    In fact I never create a new function/method if it's only going to be called from one statement.

    Never? What about interrupt handlers, or other callback functions? Those are only going to be called from one statement, inside another function. And what if an embedded system (such as Game Boy Advance) has an area of slow memory and an area of fast memory? Sometimes, you want your main game loop to be in slow memory, with certain inner-loop functions (the audio mixer, etc.) in fast memory.

    I've seen functions broken up like this where a subfunction is called within a loop, which demonstrably sucks CPU cycles (pushing and popping registers over and over again is no way to optimise).

    Many architectures (x86, arm, mips) place the first four arguments in registers anyway.

    --
    Will I retire or break 10K?
  238. Good list; a couple of observations by Spinality · · Score: 2

    This is a good framework. Your code is probably very pleasant to read. I might argue with your position about marking changes, however. There are times that it's highly useful to see why and when a particular block of code was inserted. Basically, if it's relevant to understanding or troubleshooting that chunk of logic, then by all means leave fingerprints.

    One other suggestion you didn't make was: Write the comments first. In The Old Days this was much more important, when working e.g. in assembly language, C6, or FORTRAN. But it's still very helpful. As you start writing the code, implementing your abstract design, you pass through all the major decision-points that shape the detailed implementation. It's relatively easy to capture those decisions as you rough out the module, explaining macro control and data flow, algorithm design, etc. Later comments tend to focus on the gory details rather than the big picture.

    Another suggestion is: Revise old comments. It's easy to let old comments go out of date, particularly module-level and block comments. Part of the revision discipline should be reading through the existing documentation and making sure it's (still) accurate. If not, fix it.

    Two more: Design and use a set of standards for naming, module headers, error handling, diagnostic messages, etc. These things don't evolve; they have to be implemented by choice and agreement. And Use whitespace intelligently to ensure that important things are easy to see.

    --
    -- We all have enough strength to endure the misfortunes of other people. La Rochefoucauld
    1. Re:Good list; a couple of observations by YellowElf · · Score: 1

      About marking changes, I would argue that the best place for that information would be source control. Source control will allow you to diff the two to see what version put the new code in or took it out, and also allows a change comment which describes the difference. Change comments require that you know the history of the code, which not all readers will have.

      As for why code was inserted, that is always relevant information for comments :-).

      I really like your idea about writing the comments first, however. I sometimes use this approach but honestly I don't do it often enough except where I'm having a difficult time getting my brain around a project. Probably because I don't use it, I didn't think to put it in-- my poor discipline is showing through.

      Your idea about required standards in coding is also excellent. I prefer to use that approach but I often find it unpalatable to my coworkers because, well, herding programmers is like herding cats (or is that nailing jelly to the wall), and I don't have the dictatorial authority. Or the project already has lots of existing code. Rarely do I get to start anything.

      Your other comments I think I mentioned already, but I agree with them.

      --
      Insert witty saying or aphorism here.
    2. Re:Good list; a couple of observations by Spinality · · Score: 2

      I agree that source control is orthogonal to commenting and should be used appropriately. But rigorous source control is not available or appropriate in every context (e.g. fragmented source environments like Smalltalk, or many single-developer projects where source control becomes a barrier to productivity). And besides, I *like* seeing a comment like

      // inserted 2/24/01 to resolve race condition problem
      // I think I got it, but call Bob at x235 if you wind up looking at this code :O
      . . .
      // end of race condition fix

      As far as herding cats is concerned, I find that developers who are aghast at the idea of imposed standards may be quite willing to work collaboratively on developing those standards: "Let's come up with a set of naming conventions to help new hires get on board. And in the process, we can decide how we'd really like to do things 'right' in the future. You draft a set for local variable names; I'll draft a set for database objects; then afterwards we'll work together on shared data and class hierarchies." It's true that everybody will have strong and conflicting opinions about what standards are reasonable; but talking these issues out can often lead to a better understanding all around, since most such opinions are based on valid concerns that should be balanced in any group standard.

      My commenting discipline matured when doing operating system programming in S/370 assembler language, an environment just bulging with entropic forces trying to make code incomprehensible. My coding style became semi-famous because I was essentially always programming with the comments, inserting the actual source code to implement those comments like a human compiler. It worked well, and since I did it so much and so fast, the commenting strategy became second nature. So even though it wasn't as necessary in C or (shudder) VB or whatever, it's always been natural to code outside-in, from concepts and data structures into the details.

      A technique I often used was this: 1. Invent a pseudocode language that is close to the problem domain for describing the solution. 2. Write comments using that pseudocode to show the algorithm. 3. Either a) Insert source code that performs the logic, or b) Write a compiler/interpreter/dataflow graph/whatever to implement the pseudocode language, and transform the comments into source code or an instruction stream for that engine. (You might think of Regular Expression processing as an example of this approach.)

      The compelling reason to invest so much value in comments and other precoding scaffolding is that it encourages rearchitecting the system ('refactoring' in today's parlance) a few times during implementation -- it's relatively easy to change things and recognize the canonical elements when you're still at a conceptual level. It gets harder and harder as the details get fleshed out.

      JMHO - Trevor

      --
      -- We all have enough strength to endure the misfortunes of other people. La Rochefoucauld
    3. Re:Good list; a couple of observations by YellowElf · · Score: 1

      It does make very good sense to me to use comments in the place of source control where such is not readily available or is overkill. But the comment example you provide actually gives useful necessary information separate from the date/person comments. I'd want to know about the race condition in any case as a general comment. What I really mean, is the person and date information useful enough to be kept in the code? After a while they become obsolete; either the person leaves or years go by and the code remains. I've seen comments in code saying it was added four years prior, or some section was commented out by a person long forgotten. Having a point of contact for the section of code is useful, but it is better to have the text explain itself. Really though, I split hairs here as we are both much more in line than at odds with each other.

      I will have to admit though that none of these can be thought of as hard rules; there has to be a balance to them all. We have to also take into account team dynamics and agreed-upon procedures. I don't think I've ever been involved with a project that didn't make some kind of non-perfect requirements on the participants; either there were some procedural hoops or we didn't have good source control or the existing code couldn't be rewritten or something along those lines. So these are all rules made to be broken as appropriate.

      --
      Insert witty saying or aphorism here.
  239. When I am bored I by Haiku+4+U · · Score: 0
    often look for haiku in unlikely places.

    :)

  240. learn from the masters... by carpe_noctem · · Score: 1

    Here's a code segment from the linux kernel demonstrating good commenting practices (from file /arch/sparc64/kernel/process.c)

    dump->magic = SUNOS_CORE_MAGIC;
    dump->len = sizeof(struct user);
    dump->regs.psr = regs->psr;
    dump->regs.pc = regs->pc;
    dump->regs.npc = regs->npc;
    dump->regs.y = regs->y;
    /* fuck me plenty */
    memcpy(regs.regs[0], u_regs[1], (sizeof(unsigned long) * 15));
    dump->u_tsize = (((unsigned long) current->mm end_code) - ((unsigned long) current->mm->start_code))

    --
    "Quoting famous computer scientists out of context is the root of all evil (or at least most of it) in programming." - K
    1. Re:learn from the masters... by SilentStrike · · Score: 1

      Heh, no Open Source project is complete without numerous usage of the F word. http://lwn.net/1998/1015/a/f-word.html

  241. inline by yerricde · · Score: 1

    I discovered the hard way that sometimes a call to a routine is actually larger that the code for the routine itself, at least using code warrior for the palm.

    Does your compiler support the 'inline' keyword? If you are using C++ or C99, it supports 'inline'. If you are using 1990's C in a recent compiler, it probably supports 'inline' as an extension.

    --
    Will I retire or break 10K?
  242. Each line of code has a comment line. by Anonymous Coward · · Score: 0

    Before you start groaning, this does *not* necessarily mean that you
    must generate N lines of comments for N lines of code.

    Example:
    /* Swap entries i and j in foo array. */
    int temp = foo[i];
    foo[i] = foo[j];
    foo[j] = temp;

    I consider it okay to be "lazy" and have one comment line to describe
    multiple lines of code.

    The idea is to make sure that the "comment coverage" covers all lines
    of code.

    Take away all code and you should have the pseudo-code describing what
    you're suppose to do. Think of it of being a redundundant way of reading
    the source file. The programmer can either read the code or your comments--
    whichever is easier.

    -cmh

  243. My naming convention by NibbleAbit · · Score: 1
    I follow a strict set of conventions:

    1) All methods(functions) are named in the pattern ObjectAction (like invoice_create or InvoiceCreate if the language standards are mixed case).

    2) All functions have a standard header. This includes name, parameters, return values, side effects, purpose, notes (how it gets done) and revision history (a brief one liner, the change logs give more detail)

    3) All variables are declared upfront, with descriptive names, and if required a description of how they will be used.

    4) All functions are alphabetically listed in the source. If you followed 1), this should put all relavent code close together.

    5) All functions are fully responsible for the Action they purport to do and do nothing besides what they purport to do and their names reflect this.

    6) Where appropriate, special inline comments delineate major parts of code ("Determining destination", "Calculating taxes" etc.) These sections are typically good candidates to concider for breaking out into separate routines.

    7) Other in-line comments always exist where it is not obvious what or why you are doing something, but never exist if it is obvious.

    I have been programming for about 25 years and these generic rules are appropriate for just about any language or environment I have come across. The biggest rule is if you are working on an existing application, don't change the style to suit yourself. Program in the style that has been established for that application. Nothing worse than trying to debug an application that has 15 standards because 15 programmers have worked on it.

  244. To me it means ... by grgcombs · · Score: 1

    To me, well documented code means that someone who doesn't know C can read my C source code comments and port that application to their native programming language easily.

    They don't have to look at the source itself at all to get a good english undstanding of what each part of code is supposed to do.

    This doesn't mean you should write a ten page paper, all within /* and */, but it does mean that every section of code should be well thought out and well described, not in techno-speak, unless absolutely necessary.

    These comments would be good to describe what the variables are, and what is happening to them in the code and why that's important.

    Too early in the day to continue, but I think I've blathered enough.

    Greg

  245. My 2 cents... by MrIcee · · Score: 1
    Having been in the computer industry for more than 20 years... here are my 2 cents about good documentation and good code.

    We have always required, in our corporation, a 3 to 1 ratio of inline documentation to code. What that means is... if we count overall comments in code to lines of actual code, we should find roughly 3 times the number of comments to lines of code. This does not mean that each and every line is commented... but that SECTIONS are well comment and clear.

    Now... holding to a *fixed* amount of comments does not make for good comments... but it DOES require the programmer to PRODUCE comments. So what does make for good comments?

    1. Comments should be used where ever code might be confusing, or where you do something in a manner that would make the reader say *gee, I could do this more efficiently* - to tell the reader WHY NOT.
    2. Comments must ALWAYS be written WHEN THE CODE IS WRITTEN OR CHANGED. Why? Because if you say *well, I'll go back later and add the comments* - later NEVER happens. Period. Thus comments MUST be placed at the same time code is written. We prefer to see the comment occur first and then the code - because while writing the comment you often realize something about the code itself.
    3. Comments are NEVER for the coder. They are for OTHER coders. So, when writing comments we must be careful to think *does this explain what happens to someone who has never seen my code or coding style before*? If not, rewrite the comment till it does. The point of comments is to make code MAINTAINABLE even when the original coder is gone.
    4. Comments should NEVER be placed in a separate document. They should ALWAYS be placed in the code itself. Any company who spends weeks/months writing up detailed documents that describe code are simply wasting time because the code will NOT reflect the documents. When making changes, a programmer won't stop to think *gee, I wonder if I need to change the separate documentation too*. But if the comments are in-line with the code than it is much simplier and clearer for both the programmer and others to maintain.
    5. Humor. Comments should contain programming humor. Why? To make it enjoyable to read and write. Quite frankly, I *LOVE* writing comments. Not only does it make it clear in MY mind as I code, it is enjoyable to read later. By introducing humor into the code you actually help to promote comment coding (e.g., make it fun) and also comment reading (e.g., READ the damn comment before you make changes)
    6. Comments should ALWAYS preceed the code it describes. It should NEVER be after the code it describes (Duh)
    However, there are more to comments than just this. Coding style must also be taken into account.

    When I was learning computers years and years and years ago... self modifying code, self modifying data segments, and the use of GOTO's were encouraged. Shortly after I left college, colleges started teaching that self modifying code/data and GOTO's are EVIL. Why? Not because they are REALLY evil... but because middle management couldn't read code. This is why we have attempts at OOP and other stupidity... because middle management can't read code.

    So... we say *don't use goto's* but instead we make tons of flags and nested IF's and checks to break out of conditions. Now... a simple WELL COMMENTED GOTO is much more efficient, and less wasteful, and less bug prone... than making a bunch of flags and checking them in numerous places. But students were taught to use flags, etc.. because middle management couldn't handle a GOTO. Case in point... let's say your in a nested WHILE() statement... and in there you are in a series of IF statements... and a condition occurs and you want to break out of the entire set of whiles. Well, if you use a GOTO, it's one line of code - which relates EXACTLY to one line of assembly. However, if you use flags... its a variable that has to be maintained... and checked in a couple of places, with breaks. That's LOTS of code and LOTS of possibilities for bugs. Inefficient and bad. A simple WELL COMMENTED goto would have saved quite a bit.

    Other coding styles are also important to think about when commenting and coding. For example, consider this chunk:

    • if (somecondition)

    • {
      do something here;
      }
    The above line of code is how many people are taught to program. That is... put the curly bracket on it's own line.

    But this is much clearer:

    • if (somecondition) {

    • do something here;
      }
    Why? Because in the second example it is IMPOSSIBLE to accidently put a line of code below the IF, and have it interrupt the curly. For example...
    • if (somecondition)

    • a = b + c;
      {
      do something here;
      }
    In the above example some programmer didn't look at the code carefully and pasted his formula under the IF instead of above... because the curly bracket is on it's own line, this changes the meaning of the IF entirely. The formula now becomes the IF clause... and the curly bracket expressions will ALWAYS be executed. This will be VERY hard to catch. But by putting the curly bracket at teh END of the IF statement, instead of the next line, only for formula will be incorrect and will be easier to catch.

    Does this have anything to do with comments? Yes... because CODING STYLE can in itself act as a comment!!

    The bottom line for comments and coding style is that they should NOT be written for the programmer who wrote them... they should be written for the programmers who have NEVER seen the coding style and code before - and have to maintain the program. The comment must be explicit... clear... and up to date.

    Soap Box Off

  246. so YOU'RE the guy... by Twister002 · · Score: 1

    ...Whos code I always have to work on!!!!

    one comment every physical file.

    What'a your next great suggestion? "Don't update the techincal spec or the functional spec because you don't have time because that triples the amount of work you have to do if the code is also commented. Just ride in like a code cowboy and make the changes you need".

    I agree that if the next person doesn't change the comments, it makes it harder for the next person that has to work on the code. SO MAKE SURE THEY CHANGE THEM. If they don't, they're not really the kind of coder you need around.

    In the past, I've modifier existing comments likes so.

    //orginal comment
    // modifier by SCK 2/1/2001 - fixed possible buffer overrun in var m_intInput

    It didn't take me that long to write the comment and the guys that worked on the code after me appreciated it

    --
    "For a successful technology, honesty must take precedence over public relations for nature cannot be fooled." -Feynman
    1. Re:so YOU'RE the guy... by Cederic · · Score: 2



      Hmm. The code I delivered last week (50 java classes, another 45 unit test classes using JUnit) has approx. 1 Javadoc comment per public method.

      That comment contains detail on what the inputs need to be, what the outputs will be, and what error conditions can occur.

      The code itself uses sensible variable names (there are no single letter variable names in my code) that describe what's going on. As only two of my methods are more than 15 lines long, this means that the code is extremely easy to read and very maintainable.

      Those two methods are non-trivial btw - and both of them were ones I just lacked the time to refactor, or they would be shorter. And both contain inline comments, because the code is not clear. Oddly enough, I hate this, but I've done it because I recognise the necessity. One day I'll get the time to write an internal rate of return calculation that's properly refactored and doesn't need comments, and still performs adequately, but until then I guess I'll stick with the comments.

      In my experience, people do not update the comments. They do not update the technical spec, and they do not update the functional spec. I focus on delivering workable maintainable code, and putting in comments that people will neglect and will (at a later date) mislead people does not make the code maintainable. If you work in an environment where comments are regularly updated, congratulations - I don't, and I've never met anybody who does.

      ~Cederic

  247. assumptions by Anonymous Coward · · Score: 0
    The basic comment describes the purpose/usage of what it comments. The inputs/outputs/effects of a function or the meaning of a variable. These comments are very handy when reading someone elses code, although well named functions and variables can often obviate them.

    The other, more important comment is to list the assumptions being made. The relationships between objects, functions, the user, hardware, other software, etc. So call it local comments and global comments. Most local comments can be derived from well written code and are redundant. The problem I usually have with code is too many local comments and not enough global comments. Global comments tend to be the ones that you would find most useful in your own code if you go back and look at it after a while. For instance, why is it ok to do something that is counterintuitive from looking at the code. Or why do these certain side effects need to happen in this function. Or anything else that relates to program flow instead of function flow.

    Global comments are also the most difficult to write. Sometimes we forget the assumptions we make, or are not even aware of them at the time because they seem so obvious. Global comments often seem like the kind of information that would be in a design spec or code documentation, but I think they also belong in comments. For instance, I like to see a very detailed description of functions listed in public header files. The information should be mirrored in documetation, but if I am in the middle of writing code and I am looking at a header file anyway, it is very convenient to find more than the prototype of a function.

    So anyway, the standard I would like to see is significant documetation in headers, and reasons and assumptions in source. The comments in headers should contain enough information that you should not need to look at the source or the documentation unless you need specific implementation details. You should be able to call a function or use a simple object. The comments in source are for someone else maintaing the code, not calling the code. It should describe assumptions made, pitfalls of adding or removing functionality, standard ways to extend features, relationships and dependancies between this and other components, and everything that you need to change the code.

    So, headers to use the code, source to change the code, is my suggestion for comments. For languages without that distinction, prototypes to use the code and source to change it, or comments to use the code before the implementation and change the code intermingled.

  248. Personal commenting practices by franknagy · · Score: 1

    Here is some of the informal "rules" I've
    adopted over many, many years of writing code:

    * Declare _important_ variables on single lines
    with a comment describing the purpose of the
    comment (started with Fortran code continued into
    C and Perl)

    * Preceed "blocks" of code by longer comment blocks (set off by blank comment lines) providing a description of what the code block or loop,
    or whatever is going to do. Particularly expand the explanation if the code is particularly tricky or clever.

    * Document subroutines and functions by comment
    blocks at the head of the procedure. This might
    come before the procedure declaration or
    immediately thereafter. It details that the procedure is to do and may also describe the
    arguments. If the arguments to the procedure
    are declared (i.e. C), then declare each on a
    single line with a descriptive comment.

    * Files/modules usually have a comment block at
    the top which tells what the file contains,
    why it exists, contains the copyright declaration and often has a section to record modification
    history (each one line with version #, date,
    initials and description of changes which might
    make the "line" into multiple lines).

    * Comments in the code are indented along with
    the code.

    --
    Dr. Frank J. Nagy Fermilab Computing Division Authentication and Directory Services Group
  249. Logging = good comments by irritating+environme · · Score: 1

    Once code is separated amongst multiple files, classes, function liibraries, etc, it will become difficult to follow.
    My personal experience has shown that explanatory paragraphs and high-level steps should be in comments, and an explanatory logging statement per 1-3 lines of code with variable states will handle the rest. The best thing about the logging statements is the ability for someone to track a program's execution flow and truly see what is going on. Any decent logging framework will be able to optimize the code for debug vs. production execution as well.

    --


    Hey, I'm just your average shit and piss factory.
  250. Rusty Russell's comments are great. by Mr.+Fred+Smoothie · · Score: 2
    In the iptables code (can't remember if it was the userland code or the kernel code), I remember seeing:
    • A comment to the effect "If you don't understand this code, DON'T FUCKING CHANGE IT"
    • a terse line of code which ignored the return value of a called function with a comment to the effect "Look at that: laziness, impatience and hubris, all on one line!"
    --

  251. Use FWEB by Anonymous Coward · · Score: 0
    For good, maintainable code and comments and documentation, all from the same source file, try Fweb .


    FWEB uses your compiler(s) to compile the source code. It will use TeX to make your comments in the source code into documentation, with the source lines included (or not, if I recall correctly). This way, one file contains the code and the documentation. If you change the way it works, you can at the same time change the explanation, and the documentation; all three are there together, staring you in the face.

    It's GPL, so you can use it freely, and tweak it if you need to, but it's been around for a while and probably won't need tweaking.

  252. 3 words by Mr.+Fred+Smoothie · · Score: 2

    Spreadsheet
    flight
    simulator

    --

  253. Have a team standard by sohp · · Score: 2

    Use a tool like doxygen to formalize your comment formats. The Mozilla project has a page for their doxygen-generated documents at the Mozilla/SeaMonkey Code Documentation and Cross-Reference.

    In the Java world, Sun has a couple of documents on how to comment code, How to Write Doc Comments for the Javadoc Tool and Requirements for Writing Java API Specifications. Note that the latter references Object Class Specification by Edward V. Berard, Essays on Object-Oriented Software Engineering, 1993 Simon pp. 131-162., which is an excellent read in general.

    All that said, please read and live Martin Fowler's comments on coding style and comments in "Refactoring: Improving the Design of Existing Code"

  254. Re:Variable Names -consistency by DrCode · · Score: 2

    All variable names should be variations on "xyzzy". Examples are "xyzzy1", "xyzzy2", "xyzzy3". When you get too many of those, you can start putting the digits in the middle: "xy1zzy", "xyz3zy". And you can also vary the capitalization: "xYzzy".

    Finally, if you still need more names, you can use "plugh".

    These also make good passwords.

  255. That's a client management issue by Twister002 · · Score: 1

    You don't let the client shove those things down your throat at the last minute. You tell them, "Either the date has to shift or we have to leave out this feature until later."

    I know, I know I can already hear the chattering of keyboards in /. land. "But the client MAKES us put the feature in and THEY control the MONEY". I've been in that situation before and 9 times out of 10, once I've explained it to the customer that they will be getting a better value and more stable code by either slipping the delivery date or by letting us include and document the new feature and deliver it in a patch later they understand. Of course you get the occasional jackass that is on a power trip and says they won't pay if it ships late, that's why you make sure you're business is totally dependant upon one client. You make sure you have as many clients as you can handle so no one client can lord over you.

    --
    "For a successful technology, honesty must take precedence over public relations for nature cannot be fooled." -Feynman
    1. Re:That's a client management issue by Andrewkov · · Score: 1
      You tell them, "Either the date has to shift or we have to leave out this feature until later."

      We call this "Phase 2", you tell the customer something like "This is excellent, we will definitely incorporate it into Phase 2". Of course, Phase 2 never happens, but it gets the customer off your back.

    2. Re:That's a client management issue by Cederic · · Score: 1


      Almost. Initially it's a "Ok, we'll deliver that, but be aware of what your trade-offs are", and longer term it's an education issue.

      Realistically it takes 18 months of continual pressing, education and convincing before even switched on management (business, not IT) will really start to get the message. Unfortunately I've never yet worked for the same business team for more than 2 years..

      ~Cederic

  256. Re:Describe your design decisions and thought proc by Fulcrum+of+Evil · · Score: 2

    why the hell are you using 'class'?

    Because this is Java and Java lacks structs

    --
    "We returned the General to El Salvador, or maybe Guatemala, it's difficult to tell from 10,000 feet"
  257. addendum - Simple rule of thumb by Twister002 · · Score: 1

    comment stuff that is out of the norm or is a cheesy workaround to some OS or component bug. I often code for the Windows platform so my code is sprinkled with nuggets of wisdom like this.

    // have to do it this way to avoid problem X

    or

    //tried it the suggested way but that didn't work so we'll do it this way. May revisit later.

    Those are just examples, the actual comments are much more precise about the problem.

    --
    "For a successful technology, honesty must take precedence over public relations for nature cannot be fooled." -Feynman
  258. Principles and Motivation by SEGV · · Score: 1

    First, let's discuss some principles behind commenting (or just documenting) code.

    Is code well commented? Well, think of how long it takes to understand the code. Then, once you've understood the code, think of how long it should have taken you to understand the code, knowing what you now know. Why the discrepancy? Could it be addressed by better documentation? Probably.

    So now you've identified poorly commented code. How can you comment code properly?

    Let's assume you are coding with intent, and not by coincidence. You should have a plan, and know what you are doing, and not just be making it up as you go along. Think of it as shooting a movie with a script, and not improvising every scene. Well, the comments are your script. You should already have the (meaningful) comments before you begin. Write them first. If you don't have them, why? Are you sure you aren't just improvising?

    Another principle is not repeating yourself. Say things once, and only once. Information should be in one place. So, if the comments repeat the code, that's a violation. Remove one: the comment, not the code. It's better to put the information in the code, and not in the comments. Save the comments for things that aren't as easily said in the code. That's why some movie scripts describe backstory and themes and influences that aren't explicit in the frames of the film.

    Finally, why isn't this done? We all know we should comment our code for the next person, and when we are the next person, we curse our predecessor who didn't take the time to properly comment the code.

    Why didn't he take the time? Better yet, why didn't his management force him to take the time? Let's face it, the reward structure is not set up for fostering well commented code. Management wants code that runs now, and doesn't care if some intern complains about lack of comments while maintaining it some months later.

    So why should you comment well, even if management doesn't care? Think of it as a stamp of professionalism. You take pride in your work, so you go above and beyond what J Random Hacker would produce, because you know it's right. The code isn't done until it is commented and tested.

    Anyways I just finished reading the book The Pragmatic Programmer and it has lots of practical advice. I've been coding professionally for six years and it still makes me want to reevaluate my work and see where I can improve it.

    --

    --
    Marc A. Lepage
    Software Developer
  259. Javadoc by anonymous_wombat · · Score: 1
    This is not meant as flamebait, but javadoc works pretty well for Java. I don't know what software is out there to do something similar, but this style of documentation has been talked about at least since Donald Knuths web and weave in the 1980's.

    In case you are not familiar with it, javadoc produces a collection of html files automatically from structured comments within Java. It is a pretty good first pass for documenting code. I am sure that there must be some open source programs that will do the same thing for C++.

    1. Re:Javadoc by SilentStrike · · Score: 1

      Yeah.. doxygen. http://www.doxygen.org It works for Java as wel as C++.

  260. post and pre conditions! by viperstyx · · Score: 1

    im just a measly ap student in high school but from my experience, pre and post conditions for all functions are infinatly usefull! also all classes should have comments describing their constructors, what they do and what their perameters mean!

    *sigh* im sure i sound like a moron but oh well

  261. Architecture and Flow of Control comments by Random+Man · · Score: 1

    Far too late to join this conversation, but let me add my $0.02 anyway.

    What I miss most in most source code are comments that communicate the architecture and flow of control at the module level. When you get the source code for a project, it's generally a flat list of files. Where do you start? main() is not always the right answer - what's needed is an overall look at the code base and a guide to how it was put together.

    Comments in the source rarely address these questions, being more locally oriented as a rule.

  262. If it needs comments, it's not well-written by KC0A · · Score: 1
    Generally, the usefulness of comments is overrated. A programmer who knows how to comment usually knows how to write code that is clear enough to need no comments.

    The most important thing to document is the purpose and usage of each class. This is usually best documented by including an example of the class usage in the class header file.

    This becomes easy if you write a test for every class before you write the class. Then you can just copy the test code into the header file, and if you forget, then a programmer can simply look
    at the test.

    If you are having trouble writing the test, or describing the complete functionality of the class, then it is simply too large and should be split.

    Well-named variables and functions can eliminate
    the need for most comments. Rather than
    writing

    // do_something_complicated
    ... fifteen lines in two nested loops ...

    simply say:

    do_something_complicated();

    and extract the fifteen lines into a separate function.

    Do not abbreviate variable or function names,
    unless you have a standard set of abbreviations
    for your project that are ALWAYS used.

    Try to write code so that it reads as much like
    English as possible. Use noun-phrases for const member functions, verb-phrases for non-const member functions, and predicate phrases
    for boolean functions.

    Read Refactoring by Martin Fowler.
  263. Good Inline Comments by red_gnom · · Score: 1
    I type inline comments on the right side of the code, so it forms its own collumn of text.
    This way anybody can read it when it's neaded, and its presence is not distructive at all while reading the code.


    It's so simple.

  264. While we're all talking about DEVELOPERS... by SlapAyoda · · Score: 1

    This site is the definitive source for information regarding developers.

    http://www.echo23.com/domokun/

    I urge you all to check it out immediately.

    --
    # wrote sig.txt, 23 lines, 31337 chars
    1. Re:While we're all talking about DEVELOPERS... by SlapAyoda · · Score: 1
      --
      # wrote sig.txt, 23 lines, 31337 chars
  265. blame the slacker in me by i+chose+quality · · Score: 1

    well, when it comes to commenting my code, i always end up with:

    code
    strange code
    absolutely weird code
    black magic code
    hard code {comment: works great}

    --
    "We regard you as if you were capable of mild *dissociation* reproof for minimal performance of assigned processing. We regard you as a *supreme command cluster*."
    Greg Bear in "Blood Music"

    --
    the computer is online
    i am not at it
    what a waste of ressources
  266. As this will never be seen by the like of man... by feloneous+cat · · Score: 2, Insightful

    My favorite "useless" comment was one that was part of a (thank gawd) proprietary OS which had in the header to a chunk of assembly language "DOES NOT CHANGE REGISTER HL". The first thing it did was change register HL.

    My point is that comments can be as much a problem as they can be a solution. If you have time to change the code, but no time to change the comment, then in essence you may as well have NO COMMENTS. Which really defeats the purpose.

    I have found, for the most part, that GOOD function and variable names are FAR better than a half page of comments (as an example, take a page of C++ code and change all the variables to one character... see how hard that is to read?).

    Second, ignore the law that says we can't exceed 80 columns. It is dumb. It is old. It defeats the purpose of having a HUGE SCREEN with little teeny lines. 80 columns are the size of IBM punch cards. AKA dinosaurs.

    Third, kill whomever sez that Hungarian notation helps. It doesn't. It is the SECOND DUMBEST thing to come out of Microsoft. People who adopt it are mindless beasts of burden. You don't want to be one of THEM do you?

    Fourth, BE FANATICAL about taking the what reads from others and discard what doesn't. I used to make boxes with slashes and dashes, etc. When I realized I spent more time "refixing boxes" I got rid of the boxes.

    Fifth, is the best size for a bottle of gin. Gin and tonics may not help with coding, but they take the pain away from reading others code. Also good when the boss says "so, what the hell does this mean?".

    Sixth, "standards" doesn't mean squat in the real world. Getting code out is far more important. Learn what is absolutely required for comments.

    Seventh, if it is a trick TELL THE READER! Your audience is the next guy who has to support your dreck...er...wonderful creation. He is probably going to be less brilliant. If you use a trick of the compiler, LET HIM KNOW. I have worked (and written) code that dies a mysterious death when you "optimize it" - when in fact it IS optimized.

    Eighth, learn from the screwups of others. If something you picked up reads like crap, then figure out how to make it better. Does it need to be indented more? Better variable names? Etc. Surprisingly, others probably had the same problem.

    Ninth, NEVER write code with comments like "YES". I knew of a HUGE chunk (when printed is stood three feet tall) which had five comments in it. One was "YES". The contractor had to sit for several days with it remembering what it did before he could modify it. Mindblowing, isn't it?

    Tenth, Keep evolving. Writing comments is a lot like writing code, you get better at it as you get older. And the style eventually gets more terse, but more reasonable. Eleventh, EVEN if it seems obvious, sometimes it may not be. Be prepared to defend what may seem like simplistic comments. Twelfth, This is the most important. BE CONSISTANT.

    --
    IANAL, but I've seen actors play them on TV
  267. Javadoc is great training. by Java+Ape · · Score: 1

    I write several languages, and thought I was pretty good at commenting my code. My boss was happy, my co-workers didn't complain, life was good. Then I took a job at a Java-shop, where javadocs were generated hourly for all shared library classes. Since I was writing shared library stuff, that put me in the limelight. I found I had many bad habits: My class descriptions were frequently too brief, and included no examples of how to use "Widget3.class". If I included multiple constructors, I frequently only documented the "most verbose" variant. Since my variables were hypothetically well named, it seemed superfluous to comment on what they did, even if I defined them globally and used them in multiple methods. The list goes on. The generated javadocs were used by other developers who depended on my classes for critical functions of their own projects. Surprisingly, they were unhappy with the "minor" omissions in my documentation, and suggested that I look at Sun's classes for a clue. After a hearty helping of humble pie, I actually learned to comment my classes in such a way that they were as useful as those written by the Sun programmers. Even though I still write perl, C++ etc. the commenting skills I learned with java are now second nature, and very helpful. Try using javadoc on your code, then READ the generated documentation - if it doesn't explain your class accurately, completely, and at a level that would let another programmer understand your program, you have more to learn. BTW- those in-line comments, while not picked up by javadoc, are absolutely essential for other programmers. If you have time to alter the code you most certainly have time to alter the comments!

  268. Coding comments by VG_slash · · Score: 1

    I always wondered why the Software "AllClear" has not been used to comment code. It has a pseudocode language that is used to create flow charts. Looping and other standard constructs are there. Very simple really, a period at the end of a line indicates that the line is a statement, for example.

    By creating the flow chart for your code with that pseudocode you have a verifiable set of instructions that can be turned into comments by simply adding a "this is a comment" string in front of each line with a stream editor.

    Then you can build the code needed to implement the pseudocode between the appropriate comments.

    Later, you can always add comments or extract the comments at any time (think grep) and recreate the flow chart to check (or figure out, if its someone elses code) what is going on.

    VG

  269. Some useful pointers... by ktohk · · Score: 1
    I find this site useful:
    http://mindprod.com/unmain.html

    :)

  270. Yes, but why not strip? by yerricde · · Score: 1

    do not run strip on generated executable

    What policy reason is there not to run strip on generated executable?

    --
    Will I retire or break 10K?
  271. Comments by counterexample by slamb · · Score: 3, Informative

    Take a look at these files. This project is basically an example of what not to do. It's faggotted up like a twelve-year-old schoolgir's notebook, to borrow a phrase from The Onion. In particular,

    • The huge block comments have these banners that are at column 1, in complete defiance of the indentation. Consequently, the indentation is not at all consistent across the code. It makes it difficult to visually see what level you are at. It makes using a folding text editor impossible.
    • there are lots of comments along the lines of "// slamb was here, 4-26-02". These are things much more appropriate for a version control system (cvs annotate). They clutter up the code unnecessarily.
    • the comments that are there explain nothing. For example,
      // This is the main method that Java invokes at start-up

      That should be obvious from the "public static void main (String argv[])".

    • They are not in the proper form for Javadoc, Doxygen, or any other documentation generator. If you go to the trouble of putting comments at the beginning of methods in structured way, you should do so in a way that can be used to generate easily browsable documentation. See Writing Documentation Comments at Sun.
    • The grammar is inconsistent and awkward. That same document gives hints on making useful documentation with grammar that does not distract.
    • The code is not self-documenting. If you adhere to a consistent coding standard, like Sun's Code Conventions, you will know what a lot of stuff is without resorting to comments at all.
  272. Does the spec include screen shots? by yerricde · · Score: 1, Troll

    if you can't write the user-manual from the spec then the spec is incomplete.

    So you're saying the specification should include screen shots of the finished app on all platforms? What about the names of the owners of all trademarks used in the manual?

    Not only could you comment out the program structure document so that the compiler would ignore it -- but you ended up with absolutely accurate and comprehensive documentation built into that source.

    Unless, when it comes time to maintain the software, some new hire goes in and changes the code without updating the comments in parallel. Then the code and the spec have fallen out of sync. It will happen.

    If you're smart and use good tools you can selectively collapse and expand the in-source documentation

    What free editor do you suggest?

    --
    Will I retire or break 10K?
  273. Don't stop at well-named variables by Leomania · · Score: 1

    I wrote a 3000 line perl program at my last company to provide a "floorplanning language" for chip place about a year ago (1.5 years after I left the company) I was told the program was alive and well and had been extensively added on to with few changes to the underlying data structures or processing routines. My old boss said my coding style and comments were the key to their ability to continue to use the code.

    I was pretty damned pleased to hear that!

    Bottom line, don't get fancy with the coding; it rarely saves execution time to use side effects or multiple operations per line, but sure makes it hard to figure out after the fact (even for the author).

    - Leo

    --
    You don't use science to show that you're right, you use science to become right.
  274. I heard that with financial software by pommiekiwifruit · · Score: 1

    if you don't make the change the trader needs NOW, he has been known to physically punch programmers in the face, cos he just lost X million dollars.

  275. Evil Coder's Bible by Zancarius · · Score: 0

    I have found some of the tips in the Code Obfuscation Guide to be reasonably helpful if not entertaining. After all, no one else is going to ever have to look at your source code, right? (Browny points for anyone who can highlight each of the tips in this particular guide used by Microsoft.)

    --
    He who has no .plan has small finger. ~ Confucius on UNIX
  276. good tools by technomom · · Score: 1

    If you do Java, do Javadoc comments - fill in @param, @exception, @return, etc.. Trust me, somewhere, sometime, someone will thank you.

    Likewise, if you do C/C++, check out CCDoc and do the same thing.

    http://www.joelinoff.com/ccdoc/

    JoAnn

  277. Comments in Code by Anonymous Coward · · Score: 0

    I used to hate when my professor would make us comment every single line of code for our projects. It made even the most programs take forever to finish. He even made us comment the brackets, oh the humanity!

    Seriously, comments should be just enough to explain what the code is for and how it does it. It is there to save time for the next person who comes along so they don't have to waid through thousands of lines of code to find something.

    What I like to do is have a meaningful header at the top of each structure and function (class/method for C++ and then have minimal comments at the end of decision statements that direct the flow of the logic.

    // This function returns a random number between
    // 1 and 200

    int someFunction()
    {
    int someValue = random(100);
    int someOtherValue = random(100);

    if (someValue >= 50) Is Greater or equal to 50
    {
    someValue = someValue + someOtherValue; /add
    }
    return someValue;
    }

  278. Well-Commented Code by Anonymous Coward · · Score: 1, Informative

    As a fourth year student at the University of Oklahoma in the MIS program, I have taken a few programming languages (including C and Fortran) and I have had different instructors attempt commenting quite differently. In my very first programming course, my C instructor didn't really care about comments, he made really no attempt to inform us of how/what/where to correctly comment, as for variable names, we could basically use whatever we wanted --seeing that I didn't know any better then, this is what I did (and have had problems remembering what this code was used for ever since.)...After that mess, however, I took a Fortran 95 class with a professor in the CS dept here--he had very stringent requirments concerning every aspect of the code (including documentation) which I found very helpful (however time consuming to do). I don't know if this applies to non-procedure languages, however, in Fortran, we were required to have a variable declaration section in which constants were listed first (with REALs before INTEGERS), then local variables (REALs before INTEGERs), then external variables for functions/subroutines, etc. We could not use any literal constants in the body of the program (except character strings) --we could only use named constants (declared in the variable section). We also had to make sure that our variable names had to make sense to someone who knows nothing about the program (which could make variable names incredibly long, however, in one's drunken stupor--one can still understand what they mean).

    We also had to comment every line of Fortran code (that was meaningful) and before declaring our variables, we had to create a comment section that clearly listed and defined each and every variable name. At the beginning of the program and before each function/subroutine we also had to have a comment box stating the name of the program (function, etc.) and description of what it did. (for functions we also had to list any arguements being used.)

    Although all of this commenting was rather time consuming and increased the length significantly, I found it was incredibly helpful when I have had to try to figure out the logic again.

  279. Quote by Rob Pike by Anonymous Coward · · Score: 0

    Basically, avoid comments. If your code needs a comment to be understood, it would be better to rewrite it so it's easier to understand. -- Rob Pike

  280. Wait till you've almost forgotten it by vanyel · · Score: 3, Insightful

    Unfortunately, this is rarely practical, but I find the most useful comments are written when I'm going back through code I wrote over a week ago. The reasons for doing things are no longer on the surface, and thus if there's something I look at and have to dig for understanding, then it needs better explanation.

  281. omg by Cenam · · Score: 0

    6 years and you don't know how to comment code properly, if you have to ask this and you have over 1 year ex. you shouldn't be coding..

    --

    The Truth: There is no string:)
  282. Steal comments from other people's code, ... by Anonymous Coward · · Score: 0

    Steal random comments from other people's code, and sprinkle them liberally throughout yours. It keeps the PHB's who insist on minimum comment levels happy, and anyone who has to actually work with your code will have to so thoroughly study it that they'll understand it better than you.

  283. First, use a good language... by frank_adrian314159 · · Score: 2
    Use a language that reduces the need for comments.

    Let's take for example, C++. If a variable is passed by pointer or reference, you need to document whether it is being passed that way because it is altering the contents of the object or for efficiency (Yes, I know about const. Do you know about the debate over logical const-ness, that destrys the usefulness of the idea?) You have to document allocation and deallocation strategies. You have to document how array limits are passed. If something points to an interior of a structure, you have to document that, too. Old coding habits pop up - like allocating booleans as bits in a word - you need to document those. And, oh yeah, make sure that you document whether the int you are returning is really being interpreted as a boolean, too. There are more examples, but that's enough to make the point. C++ requires more documentation because it has a richer set of ways to do things at the micro-level of the system, any of which that can be translated to the macro-level, where it has very little effect on the logic of the system, but huge effect on the way the system is coded and interpreted.

    So my first recommendation is to use a language where less needs to be documented. Lisp or Smalltalk come to mind immediately; Java or Python in a pinch.

    --
    That is all.
  284. The Speed of Thought by Anonymous Coward · · Score: 0

    ... you should be able to type faster than you can think ...

    The reason *you* can type faster than you can think may be that you don't think very fast.

  285. Re:Things to bear in mind (Tips With Editors!) by JonRock · · Score: 1

    Try "dabbrev-expand", normally bound to M-/, and if you like it you can search for more documentation on dabbrev (dynamic abbreviation) commands and settings.

  286. No such thing. by llzackll · · Score: 1

    I've found that the only code I really understand is the code I write myself. It takes me a while to understand someone else's code, ,even if it's well commented.

  287. You are a moron by RelliK · · Score: 3, Interesting

    1. Your "improved" code is much less readable than the original. Whoever has to maintain it will need more time to comprehend it.

    2. You introduced a bug on line 3 (null pointer dereferencing).

    Yes, I have personally seen code like it and I wanted to shoot the fucking idiot who wrote it.

    --
    ___
    If you think big enough, you'll never have to do it.
    1. Re:You are a moron by Bob9113 · · Score: 2

      2. You introduced a bug on line 3 (null pointer dereferencing).

      I didn't write a unit test, since this is example code written off the cuff (I know, there's no good excuse for not writing the unit test first - forgive me). My unit tests include bounds tests. The first pass would have induced me to change the code to "".equals( string ).

      1. Your "improved" code is much less readable than the original. Whoever has to maintain it will need more time to comprehend it.

      I disagree. I believe that the use of the variable name "definedForThisUi" more concisely states the intent of the conditional than the first example. Typically a person is more interested in seeing the high level meaning of the aggregated condition that allows entry to the block than the collection of states that must be evaluated in assessing that aggregated condition. This is the reason for creating aggregating conditional methods, such as person.isEligible(), which checks the state of several parameters (perhaps age, membership level, and purchase history).

      Moreover, one stated objective was to make it less likely that the explanation of the code would diverge from the logic. Comments have a nasty habit of not changing when someone alters the logic - but when the code is the commentary, they cannot mutate independantly. Also, programmers tend to be more anal about the clarity of code than they are about comment revision.

      Of course, this code is doing two very simple boolean checks - hardly necessary to clarify this small, simple block - but then, it is just an example. Perhaps you have heard of books on programming style. They typically show small examples which do not, strictly speaking, require the enhancement in question. These examples are meant to demonstrate the concept. Getting the most from examples like this requires that you abstract the meta information - the reason behind the action. A fine example is chapter 1 of "Refactoring". Buy a copy - it is really quite good - and read paragraph 3 of chapter 1 for a more clear explanation.

      Yes, I have personally seen code like it and I wanted to shoot the fucking idiot who wrote it.

      I do not understand how this statement was intended to support your positions, so I do not know how to respond. FWIW your attitude does not sound conducive to a team atmosphere. Have you been fired a lot? Have you ever considered rage management therapy? Screaming into a pillow is supposed to help. JM2C.

      You are a moron

      moron Pronunciation Key (môrn, mr-) n.
      2. Psychology. A person of mild mental retardation having a mental age of from 7 to 12 years...

      I find it hard to believe that the typical moron would care about code commentary and be inclined to express an opinion - regardless of your impression of that opinion. Besides, would a moron use big words like "mutate" and "induced"?

      :^P

    2. Re:You are a moron by ahde · · Score: 2

      the probles with your code isn't in the naming convention -- which is an improvement, but you've got operations and assignments on the same line, which are then assigned to temporary variables (boolean at that!) which then need to be checked (with a boolean operator yet!) later on, where you have to remember what the boolean values represent.

  288. It's like pornography by Anonymous Coward · · Score: 0

    I may not be able to define good documentation, but I know it when I see it.

  289. Practice of Programming by Xamot · · Score: 1

    The Practice of Programming by Brian W. Kernighan and Rob Pike. ISBN: 020161586X The Practice of Programming (reviewed sometime in the past by slashdot) is an excellent read, I hand it out to people the right crappy code.

    --
    ?
  290. My favorite comment of all time by Anonymous Coward · · Score: 0
    I found this in 475,000 lines of crap that I worked on over the last 18 months. (The company is now crumbling). This has got to be the epitome of what it wrong with programmers that come from these 18 - week certification courses:
    // Fail-safe logic: if production site,
    // then always do CC xactions
    $vProductionSystem = ProductionSystem;
    if ($vProductionSystem)
    {
    $bbDoCCAuth = true;
    }

    if ($bDoCCAuth)
    {
    ... // code here...
    }
    1) Where does "ProductionSystem" (assumed constant) come from?
    2) Why set THREE values equal to ONE constant?
    3) What's wrong with:
    // If production site, then do CC xactions
    // else, continue assuming that they were successful
    // PRODUCTION_SYSTEM is defined in Globals.inc.php

    if (PRODUCTION_SYSTEM)
    {
    ... // code here
    }
  291. Comments as pseudo-code by booch · · Score: 2

    When I write code (even code that nobody else will see) I write it as psuedo-code in comments first. That lets me get it straight in my head before I write the code. It seems to help -- it makes my coding go quicker.

    My comments don't go as far as your examples. Instead of "loop through the employee records" and "print the record" I'd write "print all the records".

    --
    Software sucks. Open Source sucks less.
  292. True professionalism by Anonymous Coward · · Score: 0

    ...stems from the fact that professionals are paid professional salaries. So, until I make as much as the CEO, you can fucking kiss my ass. If it's annoying, give us time to do it properly.

  293. Comment architecture, not code by StupidFodder · · Score: 1

    The primary goal of commenting is to save time by making it easier for a literate programmer to jump into your code and understand how it works.

    A literate programmer doesn't need you to comment tricky-looking lines of code or to ensure every looper value is "iSomethingDescriptive" instead of "i". What a literate programmer needs is *context*--they need to understand the overall architecture of your code, how the small piece they are looking at fits into the architecture. This means you need to comment the goals of each method or function, the structure of each class/object/interface, by specying *why* you've broken things down or structured things in such a way or *why* a function or method is trying to do some particular obscure magic. This way you don't have people walking into your code, picking up a piece of it, and having absolutely no clue what it is trying to accomplish, why it's trying to accomplish that, or when it gets invoked.

    This is why "write the comments first as pseudo-code, then fill in the actual code beneath the comments" approaches are generally successful--because they in effect guarantee that you've thoroughly outlined the architecture of your code in the comments.

  294. why, not what by moocat2 · · Score: 1

    One of my personal mantras when commenting is to make sure I am commenting on why I'm doing something instead of what I'm doing. The code will already show the what, so add something to that.

    To illustrate this point, consider the following snippet of code:

    // Add 7 to the line count
    line += 7;

    Yes, the comment told exactly what the code does, but what are we adding the number 7. Why is this value special? Is it somehow related to the number being prime?

    So, if the comments are just reiteratring exactly what the code is saying, don't bother. Give the reason about why something is being done.

  295. Here's what I do. READ THIS, SERIOUSLY GOOD ADVICE by Anonymous Coward · · Score: 0

    //
    // What the heck does this code do...
    //
    // META: Why the heck did I do it this way...
    //

    Here's the key. Nobody wants to read obvious comments like "this function takes this argument...blah blah blah" or "prints this..." If you've written any amount of code you you don't need to see this. It is easy to figure out from the header or code itself. NOW, if you do need to pass some strange argument or return some strange argument or do something which looks obvious but may not be, put it in the comments. e.g. a pointer to a pointer to a pointer, whatever. They key now is to write a meta comment when you start doing abnormal coding. META: Why the hell did you do it this way. What were you thinking at the time. Why did you think this was the best way.

    The key is the meta comment. This will tell someone maintaining your code what the hell is going on much more so than a bunch of terse:
    input: ....
    output: ...
    what this function does: ...

    It will tell the maintainer WHY you did it this way. Maybe it's because you were connecting to some ancient piece of hardware or software that required it this way. No other type of comment will convey this more than a META: comment just after the original comment.

    Later the maintainer can easily see and realize "oh, that's why he did it that way. That's no longer true/relavent. It would be safe to change the code now."

  296. Say what you're trying to do by Anonymous Coward · · Score: 0

    I find the most useful comments in code are the ones that explain what you're attempting to do
    eg. //return first instance of character in a string

    That way when someone else comes along and tries to maintain the code, if they know a better more efficient way to code that piece of functionality, they can do so.

    Too often I find myself not keen to modify a routine as although it's obvious what it actually does, I'm not sure what the original coder was trying to achieve, and I have to assume that maybe they are much cleverer than me and I've missed an important side effect that they specifically coded for.

    To reiterate:
    code tells you what it's actually doing
    comments tell you what it's supposed to be doing

  297. Re:Variable abbreviation by Doctor+Memory · · Score: 1

    My variable name length tends to have a direct correlation with their scope. If I need a local loop index, I call it "i", since it's obvious from the context what it does. If I have some sort of global configuration variable, it's going to be named "targetSystemType" or something like that.

    --
    Just junk food for thought...
  298. Coding Style by Sir+Robin · · Score: 1

    Norvig & Pitman have a lot of good things to say about coding style and commenting style. They deal specifically with Lisp, but one can easily generalize the first several parts of the presentation to any language. A couple of my favorite points:

    It's All About Communication
    Expression + Understanding = Communication
    Programs communicate with:
    o Human readers
    o Compilers
    o Text editors (arglist, doc string, indent)
    o Tools (trace, step, apropos, xref, manual)
    o Users of the program (indirect communication)

    Some things to notice:
    o People's style changes over time.
    o The same person at different times can seem like a different person.
    o Sometimes that person is you.

    --
    My /. ID is only 5,210 away from Bruce Perens's.
  299. No comment - seriously... by tz · · Score: 1

    I find most of the problems with code is that it is badly architected, or just was a design in progress and NEVER refactored.

    There are a few people I know that I can read their code much like a book and it can be completely devoid of comments. But the indentation, variable naming, subroutine splitting follow some very precise rules which I've seen elsewhere. It was to the point that in 15 seconds I pointed to an offending line of code after talking about queue structure (the code was the wrong of linear v.s. circular).

    There is an aesthetic beauty to good code. The form follows the function precisely. There aren't any extra variables. This is probably the same as the Quality Plateau as stated in the programmers stone below.

    The splits across files are also well thought out. Each file can stand on its own and would be reusable and self contained. They contain a lot of statics. The separation into the files is also along a minimalist interface - as few exports and imports.

    Most of this is from a bi-weekly refactoring - new functions end up in the wrong file, or they are proven to work untuned, so AFTER IT WORKS part of the process IS TO MAKE THE CODE SIMPLE TO MAKE DOCUMENTATION EASY.

    Complex code is hard to understand even with perfectly accurate (maintained) documentation. But this is where comments come in. If something is being done that is subtle or otherwise not immediately apparent from the code structure should be explained. For embedded targets, it could describe the hardware effect (e.g. the Check LED will turn ON).

    Another area is to bypass a compiler bug (or anomaly - not all of C's behavior is precisely specified), so if x11 breaks, but x*2048 works, state that. Or to synthesize another operator, e.g. if you have 16*x around in z from earlier lines of code, and do you can do y=17*x or do y=x+z ; /* y=17*x */ - you must indicate the conceptual target of your "hand optimization".

    The worst code I've seen - up to the totally opaque is usually in Object Oriented designs. This is NOT a problem with OO, but its misuse. Instead of LED_PORT |= CHECK_LED; /* ON */, someone will create three layers of objects to a universal idealized interface, then three more layers getting to the hardware, each in a different file, so Activate(Check); [which somehow goes to LEDOn which inherits something to actually do it, but the actual bits and port will be elsewhere] will be all you see and you don't know if the hardware is broken or which of the layers the error is in. You still can do the original line in C++, and it will be completely obvious what you are doing and what line or bit to test and what it does.

    Three layers should suffice for most designs. A layer is a power as in the inverse of logarithm. So the complexity of 30 lines in one layer would be a complexity of 225 in two and 1000 in three. When you create a layer, you create interfaces across that layer. And you have to document the interfaces completely and precisely. It is easier to annul an interface than to document and maintain one.

    Think about TCP/IP. Basically 4 layers including the application and physical. The problem with the 7 layer ISO model is that it was too deep. TCP/IP was simple, straightforward, and clear.

    So as far as comments, they should indicate the exceptions - code that is dissonant from the aesthetic for a reason.

    The rest (interfaces, data, etc.) should be clearly documented, but that doesn't mean as inline comments.

    Very good resources:

    http://www.ftech.net/~honeyg/progstone/
    http:// www.tuxedo.org/~esr/writings/taoup/

  300. Variable name length by vrmlguy · · Score: 2

    One of the best ideas that I ever encountered was that the length of variable names should be proportional to the size of their scope. So, one the one hand, this is OK:
    for (int i=0; i
    (assuming that the "..." doesn't contain any braces), but function/method arguments should be longer, like "name" and "parts" in this:
    int createWidget(string name, billOfMaterials parts) {...}
    and globally-visible items (like the class and method names above) get the longest names.

    --
    Nothing for 6-digit uids?
  301. Documentation of Architecture and Standards by AShocka · · Score: 1
    You need a bigger vision than just documenting code. If you don't document the whole architecture of the code libraries and classes and describe their relationships and functions, you just end up with a mass of spaghetti comments. Too many comments becomes yet another cognitive overhead. It is better to write code in a clear style and just comment occasionally why you did something, which may not be immediately obvious.

    If your team is not documenting the architecture and code libraries in a programmers manual they are not being professionally managed (Danger Will Robinson). Also, coding teams should either work to a given set of coding standards and guidelines (it's up to your team what they are) to ensure and enhance a style within the architecture that is easy for any maintainer to work with, and for future teams to enhance and develop, which itself should also be a formal document.

    Many programmers do not like working with such disciplines, but I am sure the more experienced ones out there actually agree, that if projects start with such disciplines, the chances of project success and deliverables if much more enhanced, and the ease of development between version is also better managed. Without such disciplines, each version becomes more and more difficult to manage. You can have fun working with such disciplines, the experience of writing better, more clearly defined quality code is very rewarding in itself.

    And as stated here already, say why you did something, not what the code does.

  302. Variable name lenght (redux) by vrmlguy · · Score: 2

    One of the best ideas that I ever encountered was that the length of variable names should be proportional to the size of their scope. So, one the one hand, this is OK:
    for (int i=0; i<size; ++i) { ... }
    (assuming that the "..." doesn't contain any braces), but function/method arguments should be longer, like this:
    int createWidget(string name, billOfMaterials parts) {...}
    and globally-visible items (like the class and function/method names above) get the longest names.

    --
    Nothing for 6-digit uids?
  303. It's an art.... by beaviebugeater · · Score: 1
    Commenting code, like coding itself, is as much an art as a science. Not a lot of people do either well, and finding someone who does both well is rarer still. It isn't an easy task to quantify objectively what makes for "good" comments.

    In the end, you want something clear and concise. But describing how to get there is tough.

  304. My Coding style by Anonymous Coward · · Score: 0

    Ok, it's a (little bit) too much effort for
    the 'average' programmer, but I've seen the
    benefits:

    - Before the function/method, describe the purpose of the function and it's arguments )

    // this function returns 1 divided by the squareroot of (A + B)
    double invsqrtAB(double A, double B) {

    // 1.first add A and B
    // 2.then take the square root of it
    // 3.and then divide 1 by the above result

    // add arguments (1)
    double C = A + B;

    // squareroot (2)
    C = sqrt(C);

    // final step (3)
    C = 1 / C;

    // we're done
    return C;

    }

    It really helps if you have large functions and if a thirds party has to add functionality, bugfix or just understand/review your code!
    Especially after a long time ...

    1. Re:My Coding style by Anonymous Coward · · Score: 0

      #define invsqrt(A, B) (1/sqrt(A+B))

  305. Refactoring, by Martin Fowler by smallstepforman · · Score: 2

    To quote our good friend Martin Fowler (in reference to Smelly Code):
    "Comments are a sweet smell in code. But sometimes they are used as a deoderant, intented to mask a foul smell. If you need comments to explain a section of code, its time to Refactor".

    Comments will not solve your software maintainance problems. Refactoring will. If you havn't read Martins book, then drop everything and read it. Refactoring, as well as the Gang of Four book, are the most influential books on Software Engineering.

    --
    Revolution = Evolution
  306. can be a godsend, but... by PhilJackson · · Score: 1

    Well commented code can be a godsend but at the same time I find it difficult do debug code that is littered with un-needed comments:

    //print the data
    printf("The data is: %s", data);

  307. I dislike the book by Anonymous Coward · · Score: 0

    The book can be summed up in one sentence:

    "The process *is* the product"

    I have been trapped in a company that thought that adding process -- even the wrong process -- was the right way to manage.

    The problem with the process is that it's anti-innovative; not "non-innovative": "anti-innovative".

    In a recent article in Technology Review (available for free viewing, online) Clayton Christianson said it best:

    "Sony, for example, was history's most successful disruptor. Between 1950 and 1980 it introduced 12 bona fide disruptive technologies that created exciting new markets and ultimately dethroned industry leaders--everything from radios and televisions to VCRs and the Walkman. Between 1980 and 1997, however, the company did not introduce a single disruptive innovation. Sony continued to produce sustaining innovations in its product businesses, of course. But even the new businesses that it created with its PlayStation and Vaio notebook computer were great but late entries into already established markets.

    What drove Sony's shift from a disruptive to a sustaining innovation strategy? Prior to 1980, all new product launch decisions were made by cofounder Akio Morita and a trusted team of associates. They never did market research, believing that if markets did not exist they could not be analyzed. Their process for assessing new opportunities relied on personal intuition. In the 1980s Morita withdrew from active management in order to be more involved in Japanese politics. The company consequently began hiring marketing and product-planning professionals who brought with them data-intensive, analytical processes of doing market research. Those processes were very good at uncovering unmet customer needs in existing product markets. But making the intuitive bets required to launch disruptive businesses became impossible."

    Adding process is not the answer, unless that process is necessary and utilitarian.

  308. So which is it? by Anonymous Coward · · Score: 0

    "I only work with Perl" ... "I've never had to deal with 'obfuscated' code"

  309. Better practice-- inline comments tell why not how by einhverfr · · Score: 3, Insightful

    Functions should have their arguments documented-- what they mean and what they do, and their return values documented. That is sufficient.

    Inline comments have a place, but they are way over used. If you are telling me how your program works using inline comments, I will ignore those comments becuase if there is a problem, your code may not behave as advertized.

    Instead inline comments should document WHY you do something a certain way and help me to understand what problems caused a particular piece of code to us a particularly clumsy algorythm or why a seeminly extranious bit of code was added. Don't tell me how-- that is what the code is for.

    And use whitespace as your friend to break things up into logical chunks which are easily readable and logically connected. This is the reason for indenting your code, but the same principle can be used by adding additional line breaks to separate logical chunks of code (this makes more sense then meaninglessly breaking up functions).

    I think that these are relatively language independent advice. I use it in Perl and PHP, and when I read C and C++, I appreciate these tips as well.

    --

    LedgerSMB: Open source Accounting/ERP
  310. Re:commenting code ...Too verbose; use 2 word vars by caca_phony · · Score: 1
    Instead try something like
    cWordVar or sWord_Var //Complex Multi word. Does...

    my point was that underscores_between_words_is_easier_to readThanCamelCapsIs, regardless of length of names. And extra capitalization is annoying. (also, I hope sWord_Var is not in a game where it could be misread to apply to a weapon).

    --
    ...and this lie crawls out of its mouth: 'I, the state, am the people.'
  311. would be geek? by sister_snape · · Score: 1

    And calling for coding standards including standardized comments? I've seen a lot of attempts at this in my 22 yrs in the business and all of them are tedious when detailed enough to generalize comments. They tend to lower code to a LCD that everyone either agrees on or just got tired of the entire process. They don't generally do anything for real code quality (which isn't a matter of standards) or for real readability either all too often. As a geek I am much more interested in how to design and write code more beautifully and powerfully. I am hardly at all interested in 'coding standards'.

  312. Use What's Already Out There by gviamont · · Score: 1

    I agree with some of the suggestions which recommend adopting a team coding standard. However, to get started quickly I'd also recommend grabbing publicly available coding standards from successful teams who are already well-established (and modifying them as necessary for your own needs). For example, my friends who worked on maintaining LAM (formerly the LSC at the University of Notre Dame, they are now in the CS department at Indiana University) had an excellent coding standard that included rules for commenting code ("The LSC Coding Standard"). I'm not sure if the document outlining their standard is publicly available, but you could certainly contact them (or any other successful coding teams you know of) and ask them for a copy. I haven't worked much in industry, but most of the people I know in the academic/research software development groups seem likely to be willing to share already-written documents outlining the nitty-gritties of their coding standards. Also, for more good advice on the process of good software development, I highly recommend a book called the Pragmatic Programmer.

  313. dumbest comment (from the Apple //c ROM source) by Anonymous Coward · · Score: 0

    ... "this code is bizzarre, and magicians never reveal their secrets"

  314. The Practice of Programming by troels · · Score: 1

    While not dedicated to coding style alone it is a good read. It is fairly short (~260 pages), it is well written, and it covers a lot of topics.

    If you want more details:

    Title: The Practice of Programming
    By: Brian W. Kernighan and Rob Pike
    ISBN: 0-201-61586-X
    Printed Price: $24.95 US

  315. Why, not what! by Snoopy77 · · Score: 1

    Just my little pet gripe about commenting:

    Tell me why you are doing something, not just what you are doing

    Just a little example:

    intVariable += 1 // add one to the variable

    Well duh! I can see that. But why are you adding one to the variable. Any fool can see that we are adding one to the variable, that is the only thing that doesn't need commenting. What I want to know is why you are adding one, is it a counter, some sort of index?

    Yes, sometimes an explaination of what you are doing is required as well but the big question is why. 'What' can usually be figured out without too much hassle but 'why' is what we all need to know.

    just my 4 cents (I'm dealing in $AUS so I gotta double my 2 cents)

    --
    "She's a West Texas girl, just like me" - G.W Bush Iraqis
  316. nm by SeanAhern · · Score: 1

    Why the heck would you run nm on executables? What's that supposed to tell you? Especially C++ code, you aren't going to learn much.

  317. Get a Style Guide by aebrain · · Score: 1

    The "How to write Unmaintainable Code" article on the web is an excellent resource for documentation - much as "Web Pages that Suck is an excellent guide for web designers.

    Your organisation - even if it's just 1 man and a dog - should already have a style guide in place. Don't have one? Well then it's easy, there are plenty of good ones on the Net, for Java, C++,Lisp,MATLAB, Ada and many others.

    A good list of C and C++ styleguides is here. Just pick one. The important thing is to make sure everyone uses the same one, exactly which one is more a religious issue than anything else. That's an over-simplification, some really are better than others, but at least all the ones on that list have been tried, tested and peer-reviewed.

    As for my own opinions, a few issues

    • Make variable names meaningful. If you do this, then most of your comments will be metadata, e.g why you did something, and who and when a change was made, rather than what is being done. If you're doing something tricky or unusual, then having a pseudocode preamble can be worthwhile.
    • If you can, try to use a relatively high-level language like Ada rather than a low-level one like C. But this is almost never under your control. The Javadoc auto-documentation tool is one of the biggest plusses that Java has over other languages - so if programming in Java, Use It!!
    One final thing: your teachers should be castigated for not teaching you this already. For my sins, I've been a CS teacher at ADFA and coding style was always worth Far more marks than merely getting a chunk of code to do something right. Hacking a Kludge to do some trivial mickey-mouse stuff is far easier than professional programming, any 9-year-old hacker with VB can do that. But to make a diamond-hard industrial-strength software component that people's lives can depend upon, that can be modified easily and retain its integrity throughout its lifecycle, that's "non-trivial".
    --
    Zoe Brain - Rocket Scientist
  318. How to write well documented code by Anonymous Coward · · Score: 0

    Writing well documented code is an easy four step process.

    Step 1: Write undocumented code.
    Step 2: Place code aside for 6 months.
    Step 3: Look at your code again and document which parts of it you do not understand.
    Step 4: Study the parts of the code you do not understand until you remember what you did, then document that.

    You now have well documented code.

  319. Can you imagine... by booms · · Score: 1

    A beowulf cluster of comments?

  320. did you really ship debug code by Anonymous Coward · · Score: 0

    I thought all production oriented linkers removed the name referrances when you do a non-debug link.

  321. Re:good points, ***BUT***... by Anonymous Coward · · Score: 0

    You *DO* know that you can use HTML tags such as

    1. boldface
    2. italics
      • bulleted
      • lists
    to emphasize parts of your comments, don't you?
  322. HP75 design spec comments by codesmithe · · Score: 1

    The HP75 (yeah, I'm damn old) had some interesting comments, though not always in the source code...

    SCENE: Fade to a small cottage in the sheep country of New Zealand.
    Roo-man is standing in the doorway. His dark masculine hands, callused
    with long hours at the terminal, grip the shoulders of a young, raven
    haired woman.
    "Wendy, my dearest, you must understand we face difficult times.
    Times through which only the resourceful, the methodical, the
    dedicated will accomplish the tasks that lay ahead. I do not do these
    things lightly. We may have to give a little against the foe of
    piece-meal programming in order to gain on the other fronts facing
    limited space and slow processing speed. Yes, Wendy, this is a
    calculated risk, but it's a risk that's got to be taken!"
    "Oh, Roo-man, I never doubted that you had the best intentions. I
    guess ... (wiping a tear from her eye) I guess a programmer must do
    what he must do."
    Roo-man enfolds her in his arms, briefly forgetting the heavy
    responsibilities that have been laid upon him. Pausing, he holds her
    at a distance as if memorizing every feature. Brushing the hair from
    her eyes he smiles, then briskly turning hops between space and time,
    reassured that the one who means most believes in what he is about to
    do.

    http://www.hpcalc.org/hp48/docs/humor/rooman3.tx t

    http://www.hpmuseum.org/hp75.htm

  323. Use a code formatter by Anonymous Coward · · Score: 0

    Ideally you'll all be using the same development tool.

    If lucky enough to start a project from scratch, agree with other developers on a coding style and use a code formatting tool to enforce those standards.
    e.g. hello () {
    // stuff here
    }

    v.s. hello ()
    {
    // stuff here
    }

    One that adds missing Javadoc comments would be handy to.

    That way classes remain easy to read.
    But do this early, otherwise you get CVS diffs where formatting has changed everywhere!

  324. Wrong book by Bastian · · Score: 2

    If you want one that covers those culprits, read Rapid Development by the same author - it talks about the management end of software engineering. Code Complete is meant to cover the programming end.

  325. Propper comentations by MoneyT · · Score: 2

    Coments shoud, from what I remember from my CS courses.

    a) Describe in detail what the function does, or what the variable(s) store

    b) Describe the preconditions of the function (what has to happen for the function to be called)

    c) Describe the post conditions (what the end result of the function is (what does it return and where does it send the data)

    --
    T Money
    World Domination with a plastic spoon since 1984
  326. Change Risk Management - Unit Testing? by Bob9113 · · Score: 2

    Why is this important? When you change the comment, you must think about the comment. You must think about the change you've done and how it fits in with the rest of the code, and what the rest of the code is trying to do.

    Contrast this with changing the code, which can safely be done willy-nilly. Thank you for saving us from random code changes by adding blocks of unverifiable natural language which may have a vaguely similar meaning to anyone other than the original author. :-) (now don't get your panties in a bunch, I'm just yanking your chain)

    But if the objective is to mitigate the risk of change, might I suggest trying unit testing?

    Test Infected

    I actually don't worry about the potential adverse side effects in some distant section that might result from improving this section. If it passes the tests, it is right. If it is wrong, it will not pass the tests. If it passes the tests and a bug is later found, it indicates an opportunity for improvement of the unit tests. Enhance the unit tests to reflect the newly discovered requirement, then do the minimal improvements to the code necessary to pass the improved unit test.

    I will make you two promises: 1. It will feel extremely unnatural at first. 2. If you really commit to it in version n, you will experience less bugs in version n+1. Unfortunately, it is impossible to perceive a bug that never exists, so you will have to have a fairly solid feel for how many bugs to anticipate to fully appreciate the improvement.

    As anecdotal evidence; when I build up a new package, I start with the unit tests for the smallest components first, and gradually build my way up. At the end, I start wiring all the subcomponents together. It is not uncommon for me to spend two weeks developing a collection of classes, and less than an hour debugging them in the final integration.

    1. Re:Change Risk Management - Unit Testing? by Anonymous Coward · · Score: 0

      As anecdotal evidence; when I build up a new package, I start with the unit tests for the smallest components first, and gradually build my way up. At the end, I start wiring all the subcomponents together. It is not uncommon for me to spend two weeks developing a collection of classes, and less than an hour debugging them in the final integration.

      Sure, I have the same experience myself. I write automated tests for the smallest classes, which often makes for very painless integrations.

      But this is only one way to improve software quality. I *also* comment like a madman, in a way that would probably drive you nuts. Fortunately, you don't work for me.

    2. Re:Change Risk Management - Unit Testing? by Cederic · · Score: 1


      Sorry, we were discussing commenting, so I didn't mention the fact that I just delivered 131 fully automated unit tests that all pass in approx. 1.51 seconds, and provide approx. 94% code coverage (the rest is EJB/Database technology code, which has non-automated unit tests around it).

      Which is how I know the code does what I intended it to do (code reviews and system testing and UAT will make sure it does what the customers want it to do).
      ~Cederic

  327. C++ Variables by finity · · Score: 1

    Someone may have already pointed this out, but C++ variables are usually cryptic, as are C variables. It's just kinda the nature of the language. Comments shouldn't be cryptic, though.

  328. Re: avoid mirrors by kuma · · Score: 1

    oh boy, where to begin... forget the example, may be stupid, so what, the point is that it is ridiculous to put a dozen fucken logic statements together with a little comment above stating what the mess should mean.

    this is usually with an abundance of operators and a sparsity of parenthesis.

    i spend every day untangling stuff into *short lines* and i feel good.

    ~~~~

    ` ** apply promotion filters **
    ` selection sequence filter
    $version_needed:=$valid_version_code
    If ((Records in set("Selection_Filter_Set")>0) & $version_needed)
    $version_needed:=$version_needed & (Is in set("Selection_Filter_Set"))
    End if
    ` usages filter (cute hack? automatics!)
    If ((Size of array($usages_array)>0) & $version_needed)
    $usage:=[Promotion_Selection]Usage
    If (Substring($usage;1;1)="A")
    $usage:="A##"
    End if
    $version_needed:=$version_needed & (Find in array($usages_array;$usage)>0)
    End if
    ` revisions filter
    If (($filter_from_revision>0) & $version_needed)
    $version_needed:=$version_needed & ([Promotion_Selection]Revision>$filter_from_rev ision)
    End if
    ` date filter
    If (($filter_since_date#!00.00.00!) & $version_needed)
    $version_needed:=$version_needed & ([Promotion_Selection]Date_Changed>$filter_sinc e_date)
    End if

    ` ** apply version filters **
    ` latin version filter
    If ($spanish_version & $version_needed)
    $version_needed:=$version_needed & $include_latin_versions
    End if
    ` cycle-feature filter
    $cycle_feature:=([Promotion_Selection]Usage="FEA")
    If ($cycle_feature & $omit_cycle_features & $version_needed)
    $version:=Substring($version;1;1)+"1"
    End if
    ` written text filter
    QUERY([Copy];[Copy]Pull_Version=($selection+$versi on))
    $copy_okay:=((Records in selection([Copy])=1) & ([Copy]Proof_Status="OK"))
    If ($copy_okay & $version_needed)
    $version_needed:=$version_needed & (Not($omit_written_versions))
    End if

  329. He's a crappy coder by Anonymous Coward · · Score: 0

    Knuth may be brilliant but his code wouldn't even earn him a call-back interview in the company I work for.

  330. curl-up with a good comment by hasitwho · · Score: 1

    comments are nothing more than that which makes a good reading short story (or book). It follows well and if you leave them out, your readers imagination may not only distort your story, but also "sharply" hurt them in the long run, leaving you with terribly bad reviews. I am a commenting (as well as a formatting) freak.

  331. Mathematical Rigor by Anonymous Coward · · Score: 0

    Just read any book by Walter Rudin. There you will find the proper amount of comments.

  332. How To Write Unmaintainable Code by Max+Threshold · · Score: 1
    How To Write Unmaintainable Code

    Intentionally hilarious, but as it says, "checking for unmaintainable design patterns is a rapid way to defend against malicious or inadvertent sloppiness."

  333. Re:Things to bear in mind (Tips With Editors!) by LF11 · · Score: 1

    Thanks a lot! Eventually, I'll go buy the O'Reilly Emacs book. :)

    -Chris

  334. There were some in the Win 3.x SDK examples by ralphc · · Score: 1

    Back in the day we got in the Win 3 SDK. In a C example, to get out of 3 or 4 nested loops if there was an error condition there was a "goto wearefucked;" with the matching ":wearefucked;" at the end of the function.
    Of course by the next version Microsoft had started working with IBM more and the goto had been changed.

  335. Newsforge Article by Henry_Doors · · Score: 0

    there was an article
    http://newsforge.com/article.pl?sid=02/04 /01/15522 25 on Newsforge a little while back that offered some sensible advice

    --
    "I deny nothing, but doubt everything." Lord Byron
  336. IMHO... by Anonymous Coward · · Score: 1, Informative

    I haven't had time to read through this massive reply list, but I'll just throw my own 2 cents in...

    I've found that variable names are important. I make a point of making concise and clear variable names that describe that is happenening, i.e. HitCount rather than FuckingVarCounter. I use scope names from Hungarian(g_, m_) for global and classes, but avoid prefixing types(i, l, f, etc.), mainly because if a var type is cahnged later it gets really irritating. Of course, Replace All is useful too...In any case, I feel that the name of a variable should also make it's type obvious(e.g. NumSheep should be an integer).

    As for comments, I use them to explain algos that are not really basic(not like a simple loop) and generally explain _why_ something is being done. I use newlines to divide code inside functions into logical blocks, rather than cutting it into senselessly multiple functions.

  337. Comments by Anonymous Coward · · Score: 0

    Been coding since '68. After long bitter experience, I now strip all comments out of code before I read the code. I have found that this speeds up debugging/trouble shooting. You don't get suckered in with someones past dreams about what the code should do, instead you can deal with what the code really does. Learn to read code.

  338. I've seen genuine long functions plenty of times by Anonymous+Brave+Guy · · Score: 2
    I've never seen a method over 20 lines that really needed to be that long.

    I use them every day. Some of the code I deal with performs complicated mathematical algorithms. The functions run to 100+ lines. The algorithm is a compete entity in itself. It has no logical subparts. It does not decompose into meaningful steps. It just does a whole bunch 'o maths. Are you suggesting that I should refactor this code into separate parts at some arbitrary points just to keep the code shorter than 20 lines per function?

    All the evidence I've ever seen says that not only do longer functions not harm readability (up to a limit of around 150-200 lines, at least), arbitrary decomposition such as you advocate does harm readability, because it forces the reader to jump around for no good reason.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  339. Not always possible by r6144 · · Score: 0
    Sometimes we do trial-and-error on the trickier code in order to make them right. If you tried 3 times and the code still has some small problem, so you fixed that last bug and your code works, how many of you will re-comment the code?

    And don't tell me to think before coding. If you are going to write a heap-sort program, of course you should have a clear idea on the algorithm, but it is just HARD not to make a few mistakes (like n/2 vs. (n+1)/2) in the code, especially when implementing such an algorithm for the first time.

  340. Dvorak by Anonymous Coward · · Score: 0
    Well I'll have to argue with you about the speed of typing... I'm not sure how fast you think, but it seems to me that it would be impossible to type (or write or speak for that matter) as fast as I think. (I'm working on getting used to the dvorak keyboard for that)

    I changed to Dvorak a while back, and my experience was that it did not noticably increase typing speed. It
    • did
    however, significantly reduce the wrist and finger strain I had been suffering...