102 comments

[ 3.0 ms ] story [ 178 ms ] thread
Exception up = new Exception("Something is really wrong."); throw up; //ha ha

LOL.

Pretty sad that all these examples are bad comments not good ones.

Here's a comment from some code that I posted to my blog. The idea was that this would explain in detail to someone reading the code what I was doing with the pieces of a wooden train set. This was critical to the operation of the program and I imagined that many of the readers of the code would need a careful explanation.

It turns out that I'd forgotten what this code does so the comment was helpful.

  # The 15 possible pieces: a straight edge (which has $unit length) and
  # is used as the measurement for everything else, a bridge (which is
  # twice the length of the straight edge; it is actually supplied in
  # two pieces but for the purposes of this program is considered to be
  # a single piece) and a curve (using $radians_in_curve above the
  # length of the straight line between the ends of the curve is
  # calculated).
  #
  # Each entry consists of three parts:  
  #
  # length: the length in a straight line between the ends of the piece
  # at its centre. 
  #
  # angle: the angle (in radians) between the straight line through the
  # piece and a tangent to the curve at the piece's start.  This only
  # applies to curved pieces where the straight line is the line joining
  # its two endpoints.
  #
  # count: how many of these pieces are supplied.
  #
  # Note that curves can be placed in either a clockwise or
  # anticlockwise direction. The program detects this by looking at the
  # angle.  If it's non-zero then the piece has two orientations.

  my %pieces = (
    Bridge   => { length => $unit * 2,
                  angle  => 0,
                  count  => 1 },

    Straight => { length => $unit,
                  angle  => 0,
                  count  => 2 },

    # Here's a curved piece, the angle a is $radians_in_curve, the
    # length l of a side is $unit.  So length is the distance between
    # the points labelled s and f. Bisect the angle a you get a right
    # angle triangle with hypotenuse of length $unit and angle at the
    # vertex of $radians_in_curve/2.  So the angle b is $PI/2 -
    # $radians_in_curve/2. By simple trigonometry the length is twice
    # $unit * cos($PI/2-$radians_in_curve/2).
    #
    #                  s
    #                  C
    #               .  .  C
    #             .   b    C
    #         l .       .   C
    #         .              C
    #       .            .   C
    #     .  a               C
    #   .  .  .  .  .  .  . C
    #  o                    f
    #
    # To calculate the angle to the tangent at point s (the angle c),
    # note that the angle formed by os and the tangent is a right angle
    # (since os comes from the centre of the circle).  So b+c is $PI/2
    # but b is $PI/2 - $radians_in_curve/2 and so c is
    # $radians_in_curve/2
    #
    #                  s
    #                  .
    #               .  .  .
    #             .   b  c  .
    #         l .       .     .
    #         .                 .
    #       .            .        .
    #     .  a                      .
    #   .  .  .  .  .  .  .  .  .  .  .
    #  o                    f
    #

    Curve    => { length => 2 * $unit * cos($PI/2-$radians_in_curve/2),
                  angle  => $radians_in_curve/2,
                  count  => 16 }
  );
http://blog.jgc.org/2010/01/more-fun-with-toys-ikea-lillabo-...

Interestingly, the first line of this comment contains an error. There are 19 pieces not 15.

That's beautiful! I have lately been encouraging all my team to take advantages of comments to document the high level business logic as it was at the time of development. It provides utility during code review and future dev, and it's a terrific CYA when debating with stakeholders about what they said they wanted then versus what they "remember" asking for.
That example is particularly verbose because I knew I'd forget it and it wasn't obvious what I was doing. A clear example of something shorter is:

  // Briefly the algorithm goes like this:
  //
  // Slide a 16x16 block across the entire image from left hand corner
  // to bottom right hand corner.  For each 16x16 block perform a
  // discrete cosine transform on it and then quantize the 16x16 block
  // using an expanded version of the standard JPEG quantization matrix.
  //
  // Each quantized DCT transformed is stored in a matrix with one row
  // per (x,y) position in the original image (the (x,y) being the upper
  // left hand corner of the 16x16 block being examined.
  //
  // The resulting matrix is lexicographically sorted and then rows that
  // match in the matrix are identified.  For each pair of matching rows
  // (x1,y1) and (x2,y2) the shift vector (x1-x2,y1-y2) (normalized by
  // swapping if necessary so that the first value is +ve) is computed
  // and for each shift vector a count is kept of the number of times it
  // is seen.
  //
  // Finally the shift vectors with a count > some threshold are
  // examined, the corresponding pair of positions in the image are
  // found and the 16x16 blocks they represent are highlighted.
  //
  // Uses the FreeImage library (http://freeimage.sf.net/) to access
  // image data
From: http://blog.jgc.org/2008/02/tonight-im-going-to-write-myself...
> as it was at the time of development

Also as it was interpreted at the time of development - the two should be the same of course but we don't live in a perfect world. If a comment explains exactly what the code is trying to do and why, and the "what" matches the code but doesn't match the client expectations then as well as fixing the code you know you might need to update documentation elsewhere too to make it cleare.

Superb. (TODO: look for an ASCII drawing mode for Eclipse)
IDK about Eclipse, but Emacs comes with M-x artist-mode
DrRacket lets you embed images directly in source code.
Reminds me of the comment at the start of python's heapq module: http://hg.python.org/cpython/file/bd8afb90ebf2/Lib/heapq.py . Grammatically not a comment, but I would count it as one semantically.
I really hate how heapq in python doesn't allow a comparator function. Stuffing tuples is the accepted solution, but it feels wrong and adds a bunch of unnecessary code when using heapq. Nice comment, but sub-par implementation.
The favourite one from our codebase:

   // And God said: "let there be....shite"!
(followed by some C# reflection code to break into a sealed class in the .Net framework)

All other comments are pointful, well described and useful.

Before I click, I bet this has been closed as "not constructive".

[edit] Yep.

It's the kind of thread that really has no home. Proggit would shoot it down for being frivolous, HN would probably do the same if it was a self-post.

I'm glad that StackOverflow leaves closed questions visible. A lot of the value I get from SO comes from opinion-y questions getting answered by experts.

Letting people ask these questions freely would destroy the community. They would grab all attention, and the focus would be on creating clever questions and answers, not providing good help for developers. Kinda how the biggest sub-reddits work; content that is easy to diggest grows quickly to the top.
There's only so many of 'these questions'.

There is especially no harm in letting the historical ones stay open.

And no use in leaving them open as well. What would a new answer buried away accomplish?

And closing them with the "historical" note makes it clear that similar questions should not be asked.

Yes, but this is fair comment and nicely put:

> question is now closed, I think 528 "answers" is probably enough, no? :) – Jeff Atwood

It is annoying, though, how so many useful SO questions get closed for various reasons when they are just the question I want answered. Perhaps the real problem is Google giving a lot of weight to SO answers, even when they are closed?

I once posted a question citing reason I thought it was not duplicate even citing each of the few similar 'duplicate' questions I could find which did not answer my specific question.

Of course it was closed immediately.

Yes, and deservedly so. It's not a question with an answer, it's not even a poll. Other communities would close it as "Chatfilter" or "GTKY". What's interesting is that it was ever allowed on SO, and that it stood as acceptable for so long. And I wonder if the fact that there was a time in SO's lifecycle where it was accepted was important to the site's success. It's the sort of question that fosters community and good will in a way that "MVC 4 Validation using Data Annotations and Jquery" does not.
/* Here be dragons. */

At the top of the main loop of a heavily multi-threaded, iocp-based socket server written in K&R-style C. When I refactored it and ported to C++ I left the comment in.

Comment from a project I used to work on:

  # Circular references are a pain, yet so easy to avoid,
  # however unpicking them at a later date can be hard
  # and [python module name] especially so.
  # Therefore I shall ignore this for now and use this poor quality
  # botch to stop the code from breaking.
  # I dream of a day in the future when I will be able to remove
  # this crappy hack and the [project name] source code makes the world
  # a better place.
  # Until then I will cry myself to sleep each night.
There's a lot to be said about programmers, but in how many other professions do people actually feel like crying for not finding the best solution to a problem?
Vets? Doctors?

What does a programmer have to cry about?

I used to work on simulations of industrial lifting cranes. Crane operators would use the simulator to plan a lift before going out into the field to execute it. This was 'round about 2008, when New York City had all of those cranes fall over in one year. Luckily, none of them were any of our customers, but every day was a new test of patience as we waited on the news to tell us what company was responsible so we could check out customer list.[1]

I'm now working on DOT road signing systems. The software I am writing will be used to figure out when and where to put up speed limit and warning signs.

What is really, super concerning is that, though I am capable of doing all of the math and physics that the job requires (and there is really no reason for you to believe me on that point, which makes the situation even worse), none of the other programmers I've ever worked with on these projects could.[2] The companies that hired me just got lucky that I typically go with the least-effort job application process and am too lazy to be constantly applying to jobs. There was no vetting process, it was just "take the cheapest guy we can get".

When people could die as a direct result of a programming error on your behalf, it tends to change your perspective on things.

[1] When the company ignored my analysis that certain parts of the data was logically inconsistent (this system used look-up tables to do everything, very little was actually simulated), I quit. As far as I was concerned, the fact that none of our own customers had been in the news was mere luck and I had no interest in being on watch with my hands tied behind my back when it finally did happen.

[2] The most recent fun defect I had to fix involved someone having added two angles together, one in degrees, the other in radians. That prompted this little thought-experiment in code: https://github.com/capnmidnight/UnitsOfMeasure/tree/master/U.... It works for some simple things and has an interesting side effect of helping document the code, which I realized when I failed to convert a particular poorly documented section of the code to this system.

> none of the other programmers I've ever worked with on these projects could.

Thank you, this is going into my risk assessment of various dangers.

You should. We don't certify programmers, so it's a very real risk.

On the other hand, I do not support the efforts of my state to attempt to license software engineers. As it's written, it really only seems like a protectionism racket to keep upstarts from competing with established firms. To whit: employees of S-corps are exempt. Way to miss the entire freaking point, Virginia.

Accidentally crashing a Martian lander into the ground?
(comment deleted)
The best I've seen recently was: // this is shit

Followed by a #region block (it's C# code): #region shit { ... }

This was done by a remote contractor on his last week on the project, which may explain his attitude. Regardless I nearly wet myself when I saw it!

"Beware of bugs in the above code; I have only proved it correct, not tried it."

- Donald Knuth

    /*
    thisIsCodeBlock(1);
    moreCode();
    /*/
    thisIsCodeBlock(2);
    andMore();
    //*/
One of those reminded me of the following legend that gets passed around here at work.

A codebase had been maintained by a single person, who then left the company. When the other engineers took over responsibility for the project, they discovered, to their dismay, that it was almost entirely bereft of comments.

Amongst the tens of thousands of lines of code, they found only one comment, preceding an unintuitive bitmask operation:

    /* gok */
Nobody could work out what on earth "gok" could mean, let alone why the previous engineer had chosen to leave that comment when they found no reason to comment any other part of the project.

Years later, somebody bumped into this chap at a conference and managed to ask him about the project and the significance of "gok."

"Oh, that's easy. It stands for 'god only knows.'".

  // Maybe these two lines will crush everything.
Whatever it referred to was no longer there.
I think the best one that I didn't write was a long back-and-forth argument in a C header file where TRUE was defined as 0 and FALSE as non-zero. The original author of this product apparently had screaming fights about that being THE RIGHT WAY. Of course that surprised a lot of developers over the years and had been "fixed" several times only to be reverted back.
From tunefs(1) on older SunOS

        .\" Take this out and a Unix Demon will dog your steps from now until
        .\" the time_t's wrap around.
        .sp
        You can tune a file system, but you can't tune a fish.
Here's something I recently discovered I had written when revisiting some code. Swallowing exceptions FTW :)

    try
    {
        //some code that frequently dies
    }
    catch (Exception)
    {
        // "If he dies, he dies" - Ivan Dragor
    }
''WARNING! DO NOT REMOVE OR MODIFY THE FOLLOWING COMMENTED LINES!

With no explanation why. But then it is vb6 so who knows, perhaps the comments do make a difference. ;)

In a unit test:

   # And what father is there among you, who,
   # if his son asks for a slice of bread,
   # will offer him a stone?
   # or if he asks for a fish,
   # will instead of a fish offer him a snake?
   
   my $fish = 'one-fish two-fish red-fish blue-fish';
   my $snake = 'oooh! a snake! ooh! snake! ooooooooo!";
(Unit test proceeds to insert both $snake and $fish into a cache object, does a little bit of extra manipulation to recreate the error condition, requests 'fish' back, and -- until the code was fixed -- got the contents of $snake instead.)

That's right. A successful combination of biblical allusion with Dr. Seuss and _Badger Badger Mushroom Mushroom_.

(comment deleted)
I think is the all time classic:

  /*
  * 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.
  */
Ad company I work for buys one of our traffic partners. I'm code reviewing their system to document it and find a comment describing how they defraud us.

That got awkward fast.

That sounds like an interesting story. Are there any more details that you're willing/at liberty to divulge?
Standard advertising fraud with faking traffic data. I handed it off to my manager who sent it to the CTO and from there it was dealt with at the executive level. Not sure all the details but I know the CEO of the other company went from picking furnishings for a new larger office to packing a box within a day or two and most of the rest of the acquired company was let go a short time later.
(comment deleted)
I had a line of code in one of my C projects which read:

    free(self); /* so liberating */