Slashdot Mirror


How to Write Comments

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

90 of 556 comments (clear)

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

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

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

      *grumble* Forgot the
      s.

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

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

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

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

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

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

      A race for karma
      Carelessness surely follows
      Always preview first

      --
      proof, n. A demonstration that a conclusion is implied by certain premises and axioms.
    4. Re:Reading by meringuoid · · Score: 5, Funny

      Post with bad format
      Then rewrite it correctly
      Get double karma

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

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

      --
      Real Daleks don't climb stairs - they level the building.
    6. Re:Reading by InvalidError · · Score: 4, Informative

      Same for me.

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

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

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

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

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

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

      Feel free to flame me now :)

      --
      'No rational religion claims "supernatural" exists, that's an atheist slander.' - seen on slashdot.
    8. Re:Reading by gstoddart · · Score: 4, Informative
      My haiku is rotten
      I hang my head in sorrow
      Forgot the season.

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

      --
      Lost at C:>. Found at C.
    9. Re:Reading by ebh · · Score: 5, Insightful

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

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

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

    11. Re:Reading by Sax+Maniac · · Score: 2, Funny
      I hate one-liners. Here's a fake example of stuff I see all the time:

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

      --

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

    13. Re:Reading by dcam · · Score: 2, Informative

      I'd largely agree with this.

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

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

      }

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


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

    --
    liqbase :: faster than paper
    1. Re:Comments by Golias · · Score: 5, Funny

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

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

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

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

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

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

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

      --

      Information wants to be anthropomorphized.

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

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

      --

      Information wants to be anthropomorphized.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      Jedidiah.

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

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

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

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

      --
      If you want a vision of the future, imagine a youtube comments section scrolling - forever.
    7. Re:Haiku Commenting? by Coryoth · · Score: 2, Informative

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

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

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

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

      Jedidiah.

    8. Re:Haiku Commenting? by Drachemorder · · Score: 2, Insightful

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

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

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

    Let the commencement of the comment posting beginulate!

  5. cenqua! by i.r.id10t · · Score: 5, Funny

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

    The Commentator

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

    --
    Don't blame me, I voted for Kodos
    1. Re:cenqua! by Anonymous Coward · · Score: 4, Funny

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

  6. Check out Rob Pike's thoughts on code commenting by podz · · Score: 5, Informative

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

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

    Just like good documents are self coding...

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

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

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

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

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

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

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

    3. Re: Good code is self documenting... by Canthros · · Score: 2, Insightful

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

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

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

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

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


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

  8. Comment every conditional branch or loop by Matt+Ownby · · Score: 4, Funny

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

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

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

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

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

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

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

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

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

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

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

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


      Exactly. I was thinking the same thing.

      Clearly labeled abstraction is self documenting and is just better.

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

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

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

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

      NEVER do dumb shit like:

      int i; /* loop counter */

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

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

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

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

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

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

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

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

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

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

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

  10. The why not the how by Ckwop · · Score: 4, Insightful

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

    A trival example:

    Don't do this:

    public bool CheckSmsValue(Account smsAccount)
    {

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

    Do do this:

    public bool CheckSmsValue(Account smsAccount)
    {

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

    Simon.

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

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

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

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

      What about doing this?

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

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

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

      public bool CheckSmsValue(Account smsAccount)
      {

      And instead say:

      public bool isSmsValueAccurate(Account smsAccount)
      {

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

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

      Phew. Sorry for the long-windedness.

      --
      You're special forces then? That's great! I just love your olympics!
  11. Words to live by by 3CRanch · · Score: 5, Funny

    During college I always lived by:

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

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

  12. Comments tell reason. by Daniel_Staal · · Score: 4, Insightful

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

    --
    'Sensible' is a curse word.
  13. Three Books to Read by CortoMaltese · · Score: 3, Informative
    Three pretty good books that have insightful views on how to write readable code and comment it appropriately:

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

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

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

      --
      Guy asked me for a quarter for a cup of coffee. So I bit him.
  14. Comments First by Doc+Ruby · · Score: 4, Insightful

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

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

    --

    --
    make install -not war

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

      > Good comments are written first, before the code

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

      --
      Sheesh, evil *and* a jerk. -- Jade
    2. Re:Comments First by Doc+Ruby · · Score: 2, Insightful

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

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

      --

      --
      make install -not war

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

      I prefer my comments to be in the present tense.

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

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

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

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

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

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

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

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

    Remember the seasonal reference!

    Begin declaring
    Global integers, constant
    As the winter rain

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

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

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

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

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

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

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

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

    Does this mean you have to do this?:

    my $i = 0; # initialize variable $i

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

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

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

      --
      this is the most important sig ever! In your face 446154!
  18. Re:Check out Rob Pike's thoughts on code commentin by prgrmr · · Score: 2, Insightful

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

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

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

    © Leo Plotkin

  20. If you don't comment it will come back to haunt u by gasmonso · · Score: 2, Interesting

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

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

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

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

    /* Would you like fries with that? */
    hme_write32(hp, tregs + TCVR_FRAME, (FRAME_WRITE | (hp->paddr
    Mind you, it's not a comment but this one was good for printer status:
    static char *usblp_messages[] = { "ok", "out of paper", "off-line", "on fire" };
    --
    Avantslash - View Slashdot cleanly on your mobile phone.
  22. Closely linked with good code by AlvySinger · · Score: 2, Informative

    It's pointless writing "good" comments on bad code. Write clear obvious code that doesn't rely on needless tricks or language side-effects.

    Layout is important but don't get obessive. You'd write prose using paragraphs, use whitespace in code.

    Good comments are hard because, like code, bad comments are very easy. Don't describe what's obvious from the code. Why is better than how. Don't spend ten lines describing a pattern when you can refer it by name.

    Don't add redundant comments (and this is from someone who writes more than my peers). Twenty lines of boiler-plate for each method is pointless. If there's a need for a detailed change history then your source-control should provide this. If the code requires heavy detail try refactoring it to make the code clearer.

    Simple metrics are difficult but look at your code without comments and imagine what'd be useful if your coming at it blind. What would you want to see? (Try this with a random sample of colleagues code. Typically - from experience - you won't have to spend too long removing comments because there won't be any.)

    And the difficult bit: make sure you're in a culture that values comments and documentation. It's pointless crafting detail now if some future developer will ignore them or not maintain them.

    Finally, none of this is exact. Everything about can be argued. Get some literature (McConnell, Brooks, etc.) and learn from this too. Use what the situation demands, don't apply things where they're not warranted.

  23. 'Why', not 'How' by lawpoop · · Score: 5, Insightful

    The code is the 'How'. What the reader needs to know is 'Why' you are taking these steps. What larger goal are you accomplishing? What is the purpose of this code? What is its justification for existance?

    Fill in this blank: "If were weren't running this code right here right now, we wouldn't be able to do _____. We could have done it this other way, but we chose this method because of X, Y, and Z.

    In a real world example, code is like "Turn left, Go to High Street, turn right, continue on to 1122 High St, pull into the driveway, and park the vehicle." Those are the steps taken, but the goal you are acommplishing is "We want to return the library books, so we are going to drive the books to the library using the car."

    OK, so why are we taking the books to the library? Ultimately all comments will filter up to the goals of the application. They are all nested subgoals of the design specs.

    --
    Computers are useless. They can only give you answers.
    -- Pablo Picasso
  24. Are you certain this is what you want? by palad1 · · Score: 2, Funny

    public void GNAAT()
            {
                System.IO.Stream stream = System.Net.HttpWebRequest.Create("http://www.goats e.cx/receiver.jpg").GetResponse().GetResponseStrea m();
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(stream, false);
                stream.Close();
                System.Windows.Forms.Form form = new System.Windows.Forms.Form();
                form.BackgroundImage = bmp;
                form.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                form.Disposed += delegate(object src, EventArgs args)
                {
                    GNAAT();
                };
                form.Show();
            }

    // A moose once bit my sister. You see, she was carving her initials in the moose with a toothbrush when...

  25. Comments are Critical to larger scale projects by localman · · Score: 3, Insightful

    Sure, well written code should read clearly and be clear about what is happening at every step. But in any larger scale project, no matter how well you make your data structures or how cleanly you encapsulate, eventually you'll code things where the motivation isn't clear.

    Good comments don't talk about the code itself, they talk about why the code is doing what it's doing. What the code is doing should be obvious if it's well written, but I've never written a code file that couldn't benefit from a little english exposition.

    Cheers.

  26. "should I write comments?" by tomstdenis · · Score: 2, Insightful

    Boom, you're fired.  If you have to ask that you're clearly incompetent.

    As to what a good comment is, it's something that gives context to a section of code.  Comments aren't supposed to "explain" every step of an algorithm but rather explain why they're there...

    e.g.

    // for loop from 1 to 5
    for (i = 0; i < 5; i++)
       // strcmp for "key"
       if (!strcmp(strings[i], "key")) dowork();

    Could be written better as

    // we are going to look for the string "key" in the array
    for (i = 0; i < 5; i++)
       if (!strcmp(strings[i], "keys")) dowork();

    (better yet is to replace '5' with some constant or other label).

    In cryptographic tasks I assume the reader has the RFC [or other spec] handy and I just explain what parts of the standard I'm fulfilling, e.g.

    // step 3c, xor key with 0x5e
    for (i = 0; i < keylen; i++) key[i] ^= 0x5e

    That way the reader can follow my code against the spec quicker.

    If you're not capable of these sorts of comments it's because you don't think like a developer.  You're slinging one line of code against another instead of properly breaking your task down into many smaller more modular tasks which can then be easily expressed on their own.

    Tom

    --
    Someday, I'll have a real sig.
  27. lazy programmers by MatD · · Score: 5, Insightful
    People use the 'code should be self documenting' excuse because they are lazy and don't want to take the time to actually write documentation.

    If you are programming anything non-trivial, you are going to have sections of code that are obscure, and when you have to go back and fix a bug, or add functionality, you won't have any idea what the hell you were doing.

    For example, I've written code that had to run on displays with 256 color palettes in windows. It involved saving the current palette when the window gained focus, and then restoring it when the window lost focus. But I couldn't even tell you how I did that now. If I had to go back and look at that code today, I'd have no idea what I was thinking. I do recall that is wasn't actually very many lines of code.

    Back before UML was a common thing, I used to 'write' my code in comments and stubs, as a design. After I could read through the code as a narrative of what my app/service/dll did, I would actually fill in the stubs to make it work. This ended up saving me a lot of time in the long run, as I didn't really have much refactoring work to do while coding.

    --
    Since when did operating systems become a religion?
    1. Re:lazy programmers by reclusivemonkey · · Score: 2, Informative

      Back before UML was a common thing, I used to 'write' my code in comments and stubs, as a design. After I could read through the code as a narrative of what my app/service/dll did, I would actually fill in the stubs to make it work. This ended up saving me a lot of time in the long run, as I didn't really have much refactoring work to do while coding.

      For a non-programmer writing VBA at work, this has been by far the most useful comment to me. Thanks :-)

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

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

    --
    There's no place like ~/
  29. Unified theory of commenting by awtbfb · · Score: 5, Funny
    // If you can't follow this, go ask CowboyNeal
  30. My haiku by timbck2 · · Score: 4, Funny

    So many good posts --
    Damn! I wish I had mod points!
    Better luck next time.

    --
    Absurdity: A statement or belief manifestly inconsistent with one's own opinion. -- Ambrose Bierce
  31. Re:Humour in the Linux kernel - on fire by moskrin · · Score: 2, Informative

    As I understand it, the "on fire" entry in the printer status indicates when a line printer has a paper jam and is still online, thus potentially generating enough heat to *actually* catch fire... or so I've been told.

  32. I have to tell this story... by RetiredMidn · · Score: 4, Funny
    ...if I haven't already.

    Back in the 70's, I worked the Help Desk at my college's computer center. I was approached by a student taking the entry-level programming class, which taught FORTRAN; programs for the class were written on punched cards (!) and submitted to our RCA Spectra for batch processing.

    Anyway, this guy came to me with a question about a cryptic compiler error message (maybe that's redundant). I asked to look at his listing, and found the problem easily enough, but I was intrigued to see that his code was double spaced! (See it coming, yet?) I wanted to figure out how he did it, because I thought it would be useful in my own work to leave room for writing notes on my listings when I looked at them back in my dorm room.

    I couldn't find any special options on his command card (the first card in the deck that specified how the deck was to be processed; I finally realized that every other line was a blank comment line. (A "C" in column one, and nothing else on the line/card, for you young'uns).

    I couldn't imaging taking the time at the card punch to type just "C", then feed a new card (which took a couple of seconds) between every line of code, so I asked him why he had bothered.

    His answer...

    [...wait for it...]

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

    P.S. The program, about 15-20 lines long, was devoid of actual comment text.

  33. Overcomment everything by Animats · · Score: 4, Interesting
    Of course you write comments. Usually more comments than code. Don't look for excuses not to comment.

    Some comments I've written:

    • From a physics engine:
      // The contact force component is aligned with the vector between
      // the two closest points. The frictional force is in a plane
      // perpendicular to that vector and through the midpoint of pnt0-pnt1,
      // The frictional force vector is opposite the velocity vector
      // component in the friction plane.

      // Witness point checks.
      // All witness points must be on their polyhedron's side of the
      // separating plane.

      Here the purpose of the comments is to explain the math.

    • From the control code for a DARPA Grand Challenge vehicle. Here's some code I wasn't happy with, so that's clearly noted.
      // constructPath2 -- reactive obstacle avoidance and path planning
      // - the hard cases
      //
      // Called when we have to do some obstacle avoidance
      //
      // Path is an output only.
      //
      // First pass tries to find some path that will work within the turning limits.
      // If that fails, we try "brake then steer" mode - look for the longest path
      // in any direction, regardless of dynamics limits, and slam on the brakes
      // while turning. The actual steering command will be limited later.
      // ***MAKE SURE THAT CHECK IS MADE***
      //
      // ***NEEDS WORK***
      // ***SEARCHING OUTSIDE LIMITS WILL ALWAYS FAIL***
      //
    • Finally, here's some Perl code, part of the code that runs Downside.
      #
      # extractsecurityclass -- extract class of a NASDAQ security
      #
      # Foreign and bank securities aren't filed with the SEC, so
      # we need to note this. There are also test and statistics items that
      # aren't real securities.
      #
      # Note that the test for "bank" is rather poor. NASDAQ used to
      # identify banks using a column in the table, but they no longer do so.
      #
      sub extractsecurityclass($)
      { my $vals = shift;
      ## Check for symbols that don't file with the SEC
      if (${$vals}{'test_issue'} ne 'N') { return('test'); } ## is test
      (We have to stop there; Slashdot's "lameness filter" rejects Perl code.)

    All code should have well-written comments. As Wirth pointed out years ago, people who can't express themselves well in their native language are generally poor programmers.

  34. At least in C the rule is by washley · · Score: 2, Funny

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

  35. Article Author on Crack by dmatos · · Score: 4, Insightful

    As per the subject line, the author of this article is on crack. I'm not going to argue the why's and wherefores of his text, but I have a major objection to his "when". He states that the best time to comment code is once it's all done, and you're just about to submit it. WRONG!

    Has he ever worked on a major project? One that cannot be held in one brain in its entirety at one point in time? START with the comments. Start with the program architecture. Decide what each part will do. Write out how each part will accomplish its goals. Then, copy/paste that into your editor, and write the code to match the comments.

    Believe me, if you can plan out how everything will work in the first place, and then just follow your plan, the whole project will be much easier. An added bonus is that the code comments just come straight from your design document. Of course, from the tone of the article, I'd guess that this guy's response would be "What design document?"

    --

    It may look like I'm doing nothing, but I'm actively waiting for my problems to go away.
    --Scott Adams
  36. Re: ADA by Black+Parrot · · Score: 2

    > Yeah Taco, I remember the big green book too. Thanks for giving me flashbacks!

    What is this 'ADA' you speak of? American Dental Association? Americans with Disabilities Act?

    The programming language is called 'Ada', as in Ada, Lady Lovelace, Charles Babbage's sidekick.

    --
    Sheesh, evil *and* a jerk. -- Jade
  37. indeed, but to be both traditional & slashdott by Phil+Urich · · Score: 2, Funny

    Soviet Russia
    "Season mention" comments you
    In Winter: Profit

    --
    I remember sigs. Oh, a simpler time!
  38. Is that you?! by kentyman · · Score: 2, Funny

    //
    Midn, is that you?
    //
    I haven't seen you in like 30 years!
    //
    How've you been?!
    //

    --
    You know where you are? You're in the $PATH, baby. You're gonna get executed!
  39. Question for all the coders out there.. by TiggertheMad · · Score: 2, Insightful

    I am an old school coder, and I see a lot of this stuff these days:

    if (foo) {
    // Bleah
    // Bleah
    // Bleah
    // Bleah
    }


    Why do people put the opening bracket on the same line as the conditional? where the hell did this come from? I see it a lot in JS, and more modern C/C++ code. I always though you were supposed to use carrage returns and tabs to make it easy to see the body of a conditional:
    (underscores for whitespace; damn you slashcode!)

    if (foo)
    {
    _____ // Bleah
    _____ // Bleah
    _____ // Bleah
    _____ // Bleah
    }


    Did I miss something? Are all the 'cool' coders doing this now, and I'm just old?

    --

    HA! I just wasted some of your bandwidth with a frivolous sig!
    1. Re:Question for all the coders out there.. by aaza · · Score: 2, Insightful
      Believe it or not, one place it comes from is presentation slides (PowerPoint, or just plain overhead transparencies).
      It lets you get the whole example on the page in a font that is readable from the back of the lecture hall.

      Personally, I prefer it like this. The opening brace on the line with the conditional (for, while, if, etc), the conditional block indented, and the close-brace at the same indent as the start of the conditional. I tried a few other ways*, but didn't like them: they weren't readable enough for me.

      * Other ways tried:
      Open and close brace on separate lines to condition, at the same indent, code indented further (which you have above)
      Braces and code indented further than the conditional, but lined up with each other
      Braces indented from conditional (lined up with each other), code indented from braces [this was the worst]

      It's largely a matter of personal choice, or project code rules, really.

      --
      In theory there is no difference between theory and practice.
      In practice, however, there is.
    2. Re:Question for all the coders out there.. by Chemisor · · Score: 2, Insightful

      > I am an old school coder
      > Why do people put the opening bracket on the same line as the conditional?

      You must not be very "old school" if you don't know the answer. The cuddled braces are the original K&R indentation style; they are what C was supposed to look like.

      Another answer is that there are two different ways to look for blocks. I look at indentation as a clue to the new block and when I see a brace on a line by itself I immediately interpret it as:

      if (x);
      {
      }

      This is especially true when I can't see the end of the line. Obviously, it doesn't take long to switch mental gears, but it is inconvenient. No, I am not going to switch to this style. You have to indent the code anyway and since the indentation change already says "new block", the brace is redundant, and therefore should not be emphasized. I might also point out that the braces are only required for multiline blocks anyway, so looking for indentations is a skill every C programmer needs, wherever he places the braces.

      People who put braces on separate lines look for the opening brace itself to signal the start of the block and panic when they see indentation level change without it. It is really just another way of looking for blocks, and I am disappointed that it is so commonly taught.

    3. Re:Question for all the coders out there.. by jallen02 · · Score: 2, Insightful

      I started coding doing K&R C style braces. I have used them for many many years. I have recently been trying the opening brace on a separate line. It isn't so bad. There are a LOT of languages out there other than C. You can make a bunch of logical arguments for both ways. It is almost like vi vs. emacs. I can spot blocks either way. I also do a lot of Ruby coding which doesn't even use braces and instead uses the end statement to denote the end of the block. So you actualyl *have* to know what statements can start a block to even begin to know if you should be looking for an end to the block.

      As long as you are consistent with your style others will be able to read your code. Maintainability matters more than stylistic preference and both styles are maintainable. They are called STYLES after all.

      And technically automatically interpreting a line without a brace as a terminated statement (IE: with the semicolon) can be just as bad as programmers that can't find a block of code. You should know the language well enough that you can interpret any common brace style. Ok.. no more nit picking.

      I think one of the reasons it still dominates is it still gets used in book writing to condense lines of code. Almost all developers read code examples written here and there. I think this is big on continuing the tradition. When I was working on a my PHP book I know I used the brace on same line as the conditional method because it saved lines.

      In the end being consistent trumps stylistic preference. The best argument I have seen is for condensing code. It does save a line or two here and there if you really need it. With 1280x1024 being a relatively common display resolution used by developers these days I don't think it is such a big deal to have an extra line for the braces :-)

      Jeremy

    4. Re:Question for all the coders out there.. by DeafByBeheading · · Score: 2, Informative
      With 1280x1024 being a relatively common display resolution used by developers these days I don't think it is such a big deal to have an extra line for the braces


      <disgruntled 1024x768 coder>
      How big a deal it is depends a lot on the kind of code you're writing. If you've got lots of small ifs, tight loops, and small functions, the braces *do* take up a significant chunk of screen real estate.
      </disgruntled 1024x768 coder>
      --
      Telltale Games: Bone, Sam and Max
  40. Re:Are you reading the same thing I am? by petermgreen · · Score: 2, Insightful

    basic programming classes seem to push overcommenting.

    good comments should imo cover
    1: the why (why am i doing it this way)
    2: the why not (why am i not doing this the obvious way)
    3: the high level what (though to some extent this can be pointed out through method signatures etc)
    4: the low level what in cases where it wouldn't be obvious to someone reasonablly skilled in the language.

    However you don't get many of those in trivial programming excercises but the teachers are still supposed to encourage people to use comments. So naturally comments that point out trivialites are the result.

    --
    note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  41. Hard problems by Dire+Bonobo · · Score: 2, Insightful
    > If it is not obvious from the code, it should be refactored.

    If it is obvious from the code, your project is too simple.


    (Flippant, but not totally false. I work on research code that does...significantly complicated things. It can be hard enough for me to keep track of the interactions of the algorithms even when I'm designing them on paper; translate them into code, and the result is not at all trivial.

    What my code does can be hard to understand when I've made a serious effort to clearly explain what it does in prose; even then, I expect understanding what it's doing to require effort from other researchers in my subfield. To expect any of them---much less a more junior researcher---to understand what is going on from the code alone is simply nonsensical. They would dismiss it as a waste of their time, and rightly so.

    If code were that easy to read and understand, it would be found in most computer science research papers; that such papers avoid it like the plague suggests that's not the case, even for less-complicated problems.)