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.

9 of 556 comments (clear)

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

  2. Re:MOD PARENT UP. by $RANDOMLUSER · · Score: 1, Interesting
    > No one at Microsoft has ever had anyone murdered.

    Tell that to Gary Kildall

    --
    No folly is more costly than the folly of intolerant idealism. - Winston Churchill
  3. 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/
  4. Re: Good code is self documenting... by bunratty · · Score: 4, Interesting
    Yeah, right. I recently debugged some code that did matrix calculations. It turns out that the matrix involved was always positive definite, and therefore the calculation could be done by performing Cholesky decomposition rather than explicitly taking the inverse of the matrix. Needless to say, there were no comments explaining any of this, and it took me hours to reconstruct the thoughts and derivation behind the original code.

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

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

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

    --
    What a fool believes, he sees, no wise man has the power to reason away.
  5. On code commenting by david.emery · · Score: 1, Interesting
    Comments should concentrate on the "why", the code itself should be clear about the "what" and "how".

    Specifying the "what" in a human-readable form is a strength of some languages including COBOL and Ada. No one (hopefully) would argue that C-based syntax is particularly intuitive, and that common practices that emphasize brevity also are focused on reader comprehension. Where the language doesn't aid comprehension of the "how" or "what", comments should help.

    In 25+ years in this business, I've seen everything from

    i++; /* increment i */
    to code preambles that resembled War and Peace.

    dave

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

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

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

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

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

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