[comments] What is the best comment in source code you have ever encountered?

What is the best comment in source code you have ever encountered?

This question is related to comments

The answer is


I am particularly guilty of this, embedding non-constructive comments, code poetry and little jokes into most of my projects (although I usually have enough sense to remove anything directly offensive before releasing the code). Here's one I'm particulary fond of, placed far, far down a poorly-designed 'God Object':

/**
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
*/

I'M SORRY!!!! I just couldn't help myself.....!

And another, which I'll admit I haven't actually released into the wild, even though I am very tempted to do so in one of my less intuitive classes:

// 
// Dear maintainer:
// 
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
// 
// total_hours_wasted_here = 42
// 

// but the "real" solution is much more complicated

from jpgraph


on js code:

// hack for ie browser (assuming that ie is a browser)

//Mr. Compiler, please do not read this.

Had a programmer working for me once that put "Style" comments throughout his code where he codified his internal debates about the particular implementation details and to take parting shots when he was overruled on a particular coding decision.

Examples:

'STYLE 'It's arguable which is better, but I pass the image handle rather than simply 'passing the scaling values in order to keep the calling code simpler (by a 'couple of declarations statements). Alternatively, I could pass these data 'members directly from the calling code, but that would violate encapsulation.

'STYLE 'As I have done elsewhere, I will register my offical protest (just give me the 'forms to fill out) regarding the implementation of annotation serialization as 'a property rather than a pair of Load/Save methods. Again, this is probably a 'matter of style and eminently debatable.


I just checked this in the other day...

/// <STERNLY-WORDED-WARNING>
/// Pay attention to this or I will hunt you down.
/// ...
/// </STERNLY-WORDED-WARNING>

Where ("..." == "proprietary stuff that I can't post"). I just liked my STERNLY-WORDED-WARNING element.


'Major changes: Everthing! - Removed all Cornoud's code !

int main(void)
/* Program starts here */

/* My lawyer told me not to reveal */

// The following array may contain either TexturedObjects or ColoredObjects.
// I know, it sucks.

Some years ago I was working in a large code base that had no unit-testing to speak of.

There was a method buried deep within the code that performed some calendar calculations. It was somewhat broken, had to deal with daylight savings in a very clumsy way due to some unfortunate circumstances.

We had to fix it a couple of times, and every time, we would find something broken some months after.

After spending a whole day fixing it and analyzing it, I put the code in source control, along with a comment that said something like this:

// this code was written after a version trying to do {this} failed because of {reason},
// previously we were doing {this} which failed because of {reason}. This is 
// now written {this} way so that {lots of reasons here}. If you want to touch
// this code, please make sure that it produces the right answers when tested with:
//
// {some sort of unit test}

Ultimately, my team was outsourced. Some days I wonder what happened to this code :)


I saw this once:

//this used to be a comment

From Joomla! source:

// fudge the group stuff

/*
 * You may think you know what the following code does.
 * But you dont. Trust me.
 * Fiddle with it, and youll spend many a sleepless
 * night cursing the moment you thought youd be clever
 * enough to "optimize" the code below.
 * Now close this file and go play with something else.
 */ 

When coding MAPPER Apps we had some standards and one of these was that there was a list of standard variables in use throughout the suite. One of these - 'V43' was always used to hold a Surname. So imagine my annoyance when the only comment in a big cryptic chunk of MAPPER code I'd been asked to fix was:

Here V43 contains the Surname

Many years ago (about 1994) I was working on a Oracle PRO*C application for a large multi-national software company that you will have heard of. The app I was working on was a massive Oracle application and they had a utility that ran overnight tidying up data and doing all sorts of aggregate calculations. Every time anything needed doing as a batch job, it got shoved into this utility and as you can imagine it became an absolute monstrosity. It was also notable for the tiny number of comments that it had for such a massive program.

One of the few comments it did have remains the finest comment I have ever seen for pure WTF'ness... I was trying to find a bug in a function which was hundreds of lines long and right in the middle of it was the only comment in the function:

/* I did this the other way */

To this day it is still the finest comment I have ever seen.


//Time log says you've been here for 15 hours GO HOME, your code is hobo

Back when I worked for Reuters there was a comment in one of our feed handlers that made some people think the Almighty was helping us out...

// Jesus told me to skip to the end of the message here

We found out later that there was a Latin-American contact named Jesus (HeyZus).


// Sorry dirty code

/* My lawyer told me not to reveal */

// drunk, fix later

Wish I were kidding. And knowing the developer who wrote the code, I think he meant it literally.


} catch (PartInitException pie) {
    // Mmm... pie

Repeat
    ...
Until (JesusChristsReturn) ' Not sure

// simply copied from another code

/* Hammer Time! */

I have no idea why or whether he was wearing ripstop nylon parachute pants while writing the code


In the header of an XSLT file:

DON'T TOUCH THIS SCRIPT -> XSLT is like arcane, black magic

 * ...and don't just declare it volatile and think you've solved
 * the problem. You young punks think you know what volatile
 * means... why in my day we had to cast it volatile uphill
 * both ways, and the code still didn't work! Whippersnappers...

Best one so far:

"This code makes baby Jesus very sad!". 

It was refering an String iniciatilization like this:

String blankSpaces="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //100 whitespaces
                   "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //200 Whitespaces
                   ...
                   "                                        " //100 whitespaces

Well you get the idea.


It's not strictly speaking a comment, but...

It was the mid-1990s and I was working on a big migration: small software vendor, big client, lots of pressure. We had a lot of shifting-goalpost stuff; the project was very hard to control. I was the key developer, but new to the system, and the other developer was the vendor's owner/founder.

After a few months of not quite making deadlines and not quite satisfying the client, the owner/founder brought on another developer, who was working remotely. (I'm gonna go out on a limb and say the new developer had lesser skills and experience than me.)

Well, the new guy made some changes in code that I'd already worked on, and then a month or two later I was back in the same area of the code, and there were variables I hadn't seen before. With names like StupidMark.

Dude, that's just not right. I mean, there's teamwork considerations, but also: in this environment, variable names can show up in runtime error messages. I'm just saying.

In my opinion at the time, the new guy's code wasn't getting us much closer to a deliverable product anyway, which made the insult sting a little more.


// HACK ! COPY/PASTE this and look for another job

From a lad that clearly had been watching Monty Python:

> // And now, for something completely
> // different:

class theLarch{


From Python/ceval.c:

/* This is gonna seem *real weird*, but if you put some other code between
   PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
   the test in the if statements in Misc/gdbinit (pystack and pystackv). */

'Do not optimize these next two lines. Compiler bugs lurk.

And they did. Compacting the variable into the expression on the second line resulted in jumping into the middle of the heap and trying to execute data.


Many years ago I picked up the job to provide support to a project that ran real time on a Z80 and was in assembly (is there any other way to do Z80??) Anyway, the original author was a Nigerian guy by the name of Moses. Maybe I should just stop there. Anyway, scattered throughout the code was this:

XRA A    ;MT

Took me awhile to figure out what this was. The instruction itself does nothing more than clear the accumulator. It's a slick way, although I'm not sure if there is an advantage or not. you can just do:

LDA 0

But maybe

XRA A

saves a byte or something. What is does is exclusive or the accumulator with itself. The result is, of course, always zero.

Back to the MT - Empty (get it?)

That's the best I've run across.


/*
 * You may think you know what the following code does.
 * But you dont. Trust me.
 * Fiddle with it, and youll spend many a sleepless
 * night cursing the moment you thought youd be clever
 * enough to "optimize" the code below.
 * Now close this file and go play with something else.
 */ 

/*
    FIXME:  why the fuck did anyone ever think this kind of expensive iteration
                    was a good idea?

public GetRandomNumber()
{
    // Chosen by a fairly rolen dice
    return 12;
}

I think I had something of this sort:


if (case1) { // trivial
...
}
else { // we are screwed
 /* fill in later */
}

ok, so I might have used a stronger word than screwed


In the header of a code file heavily edited by everyone on the dev team:

'Avert your eyes, it may take on other forms!

Good ol' Flanders.


long time; /* just seems that way */

From a unit testing class in C#:

#region quis custodiet ipsos custodes?

[Fact]
public void TestPositive()
{
    Assert.Equal(4, 2 + 2);
}

[Fact]
public void TestNegative()
{
    Assert.Equal(5, 2 + 2);
}

#endregion

/*
* TODO: Remove this function

function remove($customer_id)
    {
        $this->Customer->remove($id);
    }

*/

when :orientation
## Avoid matching gay people with straight people - they hate it, they do, they really do.
query_parameter = "(users.orientation = 'Bi' OR (users.orientation = 'Straight' AND users.gender IN ('#{user.opposite_genders.join('\',\'')}')) OR (users.orientation = 'Gay' AND users.gender IN ('#{user.same_genders.join('\',\'')}')))"

From a dating website...


Control + A, Rewrite

This was a comment added to source control on a previous project as the check in comment.


// If you're reading this, that means you have been put in charge of my previous project.
// I am so, so sorry for you. God speed.

Best comment I ever saw was

/* 
  There is no accounting for pointers 
*/

// set break point here - you'll never reach it

Comment in our Enterprise Class system used for Government purposes

'RH 5/24/06 burn me if this dosn't work.. :)

Good ole RH.....company Prez/Lead Developer


I found this

// This is a kind of magic...

// Replaces with spaces the braces in cases where braces in places cause stasis 
   $str = str_replace(array("\{","\}")," ",$str);

// Holy moses! I've never seen anything so ridiculous in all my life. 

// Why do we need to query the AlarmIDs table twice.

// Please tell me sir; I would really like to know. 

// This like all the other services have been mangled

// to the point where they are nearly impossible to determine what kind of side affects might occur.

// I am making the smallest changes I can to this code. 

// The GetAlarmId method gets the alarm id from the AlarmIDs table.

// Novel idea, why didn't we query for the values be get below all in the same place.

// This should be changed, but right now it will have to remain as is due to time constraints.

// This like all other services really don't do anything fantastically hard, but after the original coders got

// done with them; they are difficult to work with and have an acceptable comfort level.


$you = live("free") or die("hard");


In a large investment bank that required all application outages be logged and commented I saw

Without a crash 

Or mighty bang 

The sync disk 

Did it's process hang

Not quite a comment but a goto label

ICantBelieveImUsingAGoto:

This seems to stop morons from messing my code...

// Autogenerated, do not edit. All changes will be undone.

// Any maintenance developer who can't quote entire Monty Python
// movies from memory has no business being a developer. 
const string LancelotsFavoriteColor = "$0204FB"

/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}

Never rely on a comment...


// I love the smell of dirty XML in the morning
xml = xml.Replace("xmlns=\"urn:bsd.orion/inventory\"", "");

// Sorry dirty code

Next to a local variable that had to be declared just to pass a constant to a library function:

// This only exists because Scott doesn't know how to use const correctly

From a classic from usenet:

Deep inside the Teradyne hardware modeler code is a routine that feeds a whole bunch of hex numbers into a SYS$QIO call. The only comment is 'Weird magic happens here'.


/* Here I sit, Joe broken hearted, came to do some sh*t, but only just started. */

In regards to some heavy regular expression input validation.


/* Please work */

//Iterate by one
$i++;

Unfortunately it was mine, during my "Must comment everything phase".


/*
 * You may think you know what the following code does.
 * But you dont. Trust me.
 * Fiddle with it, and youll spend many a sleepless
 * night cursing the moment you thought youd be clever
 * enough to "optimize" the code below.
 * Now close this file and go play with something else.
 */ 

// human madable inconvenient. Way too sucks.

I still don't fully understand what it means, but I have found it to be very true about a lot of code.


// fix for groupid > 9 
// if groupid ever gets to 100 everything will break (again)

if (groupid < 10) {
groupid = "0" + groupid;
}

... or die // bitch


/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}

Never rely on a comment...


From the UNIX Version 6 Source Code, circa 1975:

/* You are not expected to understand this. */

The below code was seen in a mock tutorial for Python.

# This is my rifle.
def rifle(type='hunting'):
    print('This is my (%s) rifle.' % type)

# This is my gun.
def gun(type='hand'):
    print('This is my (%s) gun.' % type)

# This is for fighting.
def fighting(type='illegal'):
    print('This is for (%s) fighting.' % type)

# This is for fun.
def fun(type='gaming'):
    print('This is for (%s) fun.' % type)

The author must have been a fan of Family Guy. ^_^


here are 4, in no order:

// Father, forgive me, for I am sinning

// heaven help me

// horse string-length into correctitude 
(from a textbook)

// what, me worry?

Quite a while ago I came across some connection script and while I don't remember the syntax I do recall the comments as I'm a Pink Floyd fan.

//Attempt Handshake: Hello? This is London calling. Are we reaching you?


//Handshake Failed: I don't understand...he just hung up.

From Joomla! source:

// this is daggy??

I really almost like the oh_my_gawd tag better than the comment...

    /*
     * IOC3 is fucked fucked beyond believe ...  Don't even give the
     * generic PCI code a chance to look at it for real ...
     */
    if (cf == (PCI_VENDOR_ID_SGI | (PCI_DEVICE_ID_SGI_IOC3 b_type0_cfg_dev[slot].f[fn].c[where ^ (4 - size)];

    if (size == 1)
        res = get_dbe(*value, (u8 *) addr);
    else if (size == 2)
        res = get_dbe(*value, (u16 *) addr);
    else
        res = get_dbe(*value, (u32 *) addr);

    return res ? PCIBIOS_DEVICE_NOT_FOUND : PCIBIOS_SUCCESSFUL;

oh_my_gawd:

    /*
     * IOC3 is fucked fucked beyond believe ...  Don't even give the
     * generic PCI code a chance to look at the wrong register.
     */
    if ((where >= 0x14 && where = 0x48)) {
        *value = 0;
        return PCIBIOS_SUCCESSFUL;
    }

In some really crappy vb code (I know it is all crappy but) I found this a comment in an empty if control block that said something like:

If bFound Then
     'I love it when I write kick ass code like this
Else
  .
  .

Just added this one today:

// Hardcoded this for time sake ... will make andrew fix later :)

Simple but effective comment, before a less than safe hack in some C++ code

// yikes

// Jay knows what's going on here, but will he remember in a year? Not very likely, this code sucks, but it works so do not change it.

This comment was posted above a huge while-if-for block... Oh, and it manipulated an object array of object arrays of object arrays of strings that could be strings or numbers, depending on at least 3 factors... (yes, I had to debug this code and change it and I wrote the comment, however I did not write the original code). ;)


One of the most classic ones is the comment made by Pierre de Fermat about his well-known "Last theorem": "The margin of this page is a bit too small to write down the proof".

It took more than 350 years before the proof was found...

(According to wikipedia this is the original text:)

Cubum autem in duos cubos, aut quadratoquadratum in duos quadratoquadratos, et generaliter nullam in infinitum ultra quadratum potestatem in duos eiusdem nominis fas est dividere cuius rei demonstrationem mirabilem sane detexi. Hanc marginis exiguitas non caperet.

...and translated into English:

(It is impossible to separate a cube into two cubes, or a fourth power into two fourth powers, or in general, any power higher than the second into two like powers. I have discovered a truly marvellous proof of this, which this margin is too narrow to contain.)


/* Emits a 7-Hz tone for 10 seconds.
  True story: 7 Hz is the resonant frequency of a
  chicken's skull cavity. This was determined
  empirically in Australia, where a new factory
  generating 7-Hz tones was located too close to a
  chicken ranch: When the factory started up, all the
  chickens died.
  Your PC may not be able to emit a 7-Hz tone. */

main()
{
    sound(7);
    delay(10000);
    nosound();
}

(the sound function in the Turbo C version 2.0 Reference Guide)


aComment = 'this is not aComment' # this is aComment
class T(object):
    def f(this):
        this is not aComment

In eMule, Preferences.cpp, in the method that forces a minimum upload speed limit proportional to your download speed limit:

uint16 CPreferences::GetMaxDownload(){
//dont be a Lam3r :)
    uint16 maxup=(GetMaxUpload()==UNLIMITED)?GetMaxGraphUploadRate():GetMaxUpload();
    if( maxup < 4 )
        return (( (maxup < 10) && (maxup*3 < prefs->maxdownload) )? maxup*3 : prefs->maxdownload);
    return (( (maxup < 10) && (maxup*4 < prefs->maxdownload) )? maxup*4 : prefs->maxdownload);
}

'this next if statement - just how it is. don't try to understand it because you won't. :)

That's job security right there.


Catch (Exception e) {
 //who cares?
} 

// This code sucks.

struct core_unlocker
{
    core_unlocker(lock)
    {
        m_lock = lock
        unlock(lock)  //Abandon All Locks, Ye Who Enter Core!
    }
    ~core_unlocker()
    {
        lock(m_lock)
    }  
    private:
    Corelock m_lock;
}

/* Please work */

var something TBoolean; //Pickins

/* You are not meant to understand this */ 

Actually saw this the other day, on some code that was written when there was a deadline rush.

//This was clearly written under duress

// The freshest corpse at the back please.
m_DeadCharacters.push_back( std::make_pair(character, 0.0f) );
// Get rid of the rotting surplus
while( m_DeadCharacters.size() > 3 )
    m_DeadCharacters.pop_front();

(A bunch of code that's really weird looking)  //Kludge.

In the header of an XSLT file:

DON'T TOUCH THIS SCRIPT -> XSLT is like arcane, black magic

This one was a living proof, in production code, of micro-management effects in our team:

// I am not responsible of this code.
// They made me write it, against my will.

... followed by less than optimal code, conceived by our beloved technical director, who was quite fond of forcing down both code and coding guidelines into developers' throats (*).

Of course, when the project leader searched for the cause of a bug, and found it was inside the "less than optimal code", he was less than amused...

(*) I am, of course, mentioning the Mighty VB King... If you want to assess the full magnitude of the power of the Mighty VB King, you can read the following SO post: What was the strangest coding standard rule that you were forced to follow? ...


I do not have a copy of the source but I have always remembered it:

// If you cannot figure it out, you should not be reading this


-- Change Log:  Not needed. The code is perfect 'cause I wrote it.
-- If you change it, it will break.

I'm in the middle of reviewing some code comments to check they make sense, and saw the modest line above.


I recently saw this:

// you just lost the game

if you don't know what the game is: http://en.wikipedia.org/wiki/The_Game_(mind_game) (it's very silly, but silly in a interesting in a way)


The original Doom had an engine with static walls that could not move; the result was that all doors opened vertically; nothing could ever move horizontally. I burst out laughing when, after the source code was released, I was looking through the code and saw this in the source file for handling doors, at the start of a big block of commented-out code:

// UNUSED
// Separate into p_slidoor.c?

#if 0           // ABANDONED TO THE MISTS OF TIME!!!
//
// EV_SlidingDoor : slide a door horizontally
// (animate midtexture, then set noblocking line)
//

//I am not sure why this works but it fixes the problem. 

This was before a set of code that technically did fix the problem it was meant to but broke 3 other things....


// Iced odnako
bool Iced{get;set;}

// but the "real" solution is much more complicated

from jpgraph


//MailBody builders for two outgoing messages
StringBuilder hanz = new StringBuilder();
StringBuilder franz = new StringBuilder();

I still chuckle a little when I read that one...


struct core_unlocker
{
    core_unlocker(lock)
    {
        m_lock = lock
        unlock(lock)  //Abandon All Locks, Ye Who Enter Core!
    }
    ~core_unlocker()
    {
        lock(m_lock)
    }  
    private:
    Corelock m_lock;
}

Next to a local variable that had to be declared just to pass a constant to a library function:

// This only exists because Scott doesn't know how to use const correctly

A compilation of my greatest hits:

// Thats the end of the While loop
// Clean up last row.  I really must program better than this.

// Note: You can't immediately tell if the line below works.

// Rounding - blech.  It's assumed that all .5s are rounded up.

// Sort out predictions first.  Seems like the right place for a prediction, 'first'.

// Let's interpret!

Try typing your favourite profanity into google code search, it whiles away many a dull hour. Some of my favourite examples:

/* These magic numbers are fucking stupid. */

/* Dear free software world, do you NOW see we are fucking
   things up?! This is insane! */

/* We will NOT put a fucking timestamp in the header here. Every
   time you put it back, I will come in and take it out again. */

# However, this only works if there are MULTIPLE checkboxes!
# The fucking JS DOM *changes* based on one or multiple boxes!?!?!
# Damn damn damn I hate the JavaScript DOM so damn much!!!!!!

/* TODO: this is obviously not right ... this whole fucking module
   sucks anyway */

/* FIXME: please god, when will the hurting stop? Thus function is so
   fucking broken it's not even funny. */

and my personal favourite

 # code below replaces code above - any problems?
 # yeah, it doesn't fucking work.

BerkeleyDB

/*
 * Chaos reigns within.
 * Reflect, repent, and reboot.
 * Order shall return.
 */
return (DB_RUNRECOVERY);

... or die // bitch


Not a comment but an attribute

[ThereBeDragons]

And one I have seen in an implementation of IHttpHandler

//What is this?
public bool IsReusable
{
    get{return false;}
}

//I'm sorry, but our princess is in another castle.

my favorite was something like this

 # commented out
 ...
 ### end of the formerly uncommented #2001-02-22 John Doe

# There is a bug in the next line.  $searchParameters != {} will always return true, because {} is creating
# a new hash reference on the fly, and the inequality operater is comparing the memory location of it
# to the memory location of $searchParameters, and they will always be different. 
# This means that the following code will always get executed as long as $nodes is defined.
# I'm leaving it there because it has always been there, and although I'm sure it was originally meant to
# mean %$searchParameters (essentially "is this hash not empty"), I'm afraid to change it.
if ( $nodes && $searchParameters != {} )
{

I once implemented some document workflow using MS SQL Server Developer 2000 (the human workflow stuff).

It consisted of a bunch of triggers that would be added to the database to make it follow workflow rules.

In one of the triggers, someone at Microsoft had written something along the lines of:

//Determine if the database has been "Grizzlified"

(The internal name of the product was "Grizzly", so I thought that was funny).


In the header of an XSLT file:

DON'T TOUCH THIS SCRIPT -> XSLT is like arcane, black magic

// This condition can't happen. Call the police or something.

I went through a sleep-deprived coding run and started only writing comments that were quotes from Fight Club.

Still trawling through the code years later I find a comment that makes me laugh. Most of them just random thoughts. I did however keep my comments to lines ratio pretty good!

// This shouldn't happen. The only way this can happen is if the
// <code>JFileChooser</code> has returned a <code>File</code> that doesn't exist
// on the system. If this happens we can't recover, and there is more than likely
// a rip in the space time continuum that the user is too distracted by to notice
// anything else.

 /**
   * This method leverages collective synergy to drive "outside of the box"
   * thinking and formulate key objectives into a win-win game plan with a
   * quality-driven approach that focuses on empowering key players to drive-up
   * their core competencies and increase expectations with an all-around
   * initiative to drive down the bottom-line. I really wanted to work the word
   * "mandrolic" in there, but that word always makes me want to punch myself in
   * the face.
   */
private void updateFileCountLabel() {

Something I saw in a .h file years ago.

// It may be a hack, but it works.

// Description : !!! TODO


// Holy moses! I've never seen anything so ridiculous in all my life. 

// Why do we need to query the AlarmIDs table twice.

// Please tell me sir; I would really like to know. 

// This like all the other services have been mangled

// to the point where they are nearly impossible to determine what kind of side affects might occur.

// I am making the smallest changes I can to this code. 

// The GetAlarmId method gets the alarm id from the AlarmIDs table.

// Novel idea, why didn't we query for the values be get below all in the same place.

// This should be changed, but right now it will have to remain as is due to time constraints.

// This like all other services really don't do anything fantastically hard, but after the original coders got

// done with them; they are difficult to work with and have an acceptable comfort level.

From a legacy Perl CGI script:

# This is convoluted and evil, sorry.

From Java 1.2 SwingUtilities:

doRun.run();  // ... "a doo run run".

Some of the very few comments in 5000+ lines of code in one file
I actually has an argument with the coder who defended his coding style...
No comment!
And there were no comments;-) (or very few)
Sadly this is production code.

offset=1;
for (i=0;i<=len;i++)
    {
    if ((i!=0)&&(i<len)) //-3
        {
        switch(mess[i])
            {
            case ETX:
            case ETB:
            case DLE:
                buf[offset]=DLE;
                offset++;
                break;
            }
        }
    buf[offset]=mess[i];
    offset++;
    }

I love the switch!

for (n=0;n<offset;n++)
{
    Sleep(TR);  //Modif A
    Sleep(T);//
    FWriteFile(hCom,buf+n,1,&dwMot,NULL);
    if (ECHO)
        FReadFile(hCom,tab,1,&dwMot,NULL);
}

and no, there are no comments explaining what "modif A" is in the header.

if (GetFileSize(hSlotFile,NULL)==3600)   //5*720

and what's 720?


Q: "What is the best comment in source code you have ever encountered?"

A: Easy - the one that helped me solve whatever problem I was having at the time, and there are lots of those!

Second best are those that help guide new development from avoiding known pitfalls.


try {

} finally { // should never happen 

}

I found this on Google Code Search

    // Constructs a tuple with 2 elements (fucking idiot, use std::pair instead!)
    template <typename T0,typename T1>
    inline tuple <T0,T1> make_tuple (const T0& t0,
            const T1& t1) {
            tuple <T0,T1> t;
            t.get<0>() = t0;
            t.get<1>() = t1;
            return t;
    }

  mov si, pCard      ; captain?

I don't remember exactly, but the idea was something like this:

Person p = new Person("John", "Doe", "male");
Collection women = new ArrayList();
women.insert(p.getTail());

It's dirty code ;)


Don't recall where I've seen these:

long time; /* know C */

and (in code to create some sort of UNIX daemon):

/* Be a real daemon: fork myself and kill my parent */

int Q13Factor = 8125; // 2^13 for Q13 

I always liked what Paul DiLascia wrote in his file headers:

// If this code works, it was written by Paul DiLascia. If not, I don't know
// who wrote it

/* Only break the connection if it actually exists. It is important to
 * check the timeslot saved in the SOURCE of the disconnect message. */

I wrote this comment, and now I can't remember WHY it's important...


// TODO: Implement this function!

'Mind boggling, gibberish version of a SQL statement, but it work's, so dont touch it

catch (Domain.ConcurrencyException)
{
    // somebody changed it between the time we loaded it and now.
    // weird, huh?
}

Some time ago I came across:

raise InvalidChild() # e.g. no legs

This is grotesque since "inwalida" in polish, means person with disability. silly me :)


My favorite is from the late, great Paul DiLascia:

// Author: If this code works, it was written by Paul DiLascia. If not then I don't know who wrote it.


//  Hey, your shoe's untied!

Followed by some dubious code, and within that code,

//  Keep looking!  I think it was the other shoe!

Finally,

//  How strange -- I must be seeing things.  Anyhow, I'm going to go take a shower, now...

//When I wrote this, only God and I understood what I was doing
//Now, God only knows

// I know the line below is wrong, but it came that way from our IP vendor, and 
// the driver won't work if you "fix" it. I've had to revert this change 4 times
// now. Leave it alone, or I will hunt you down and hurt you
if (r = 0) {
    /* bunch of code here */
}
else
{
   /* even more code here */
}

From the source code of the UNIX flavor of the Netscape web browser, circa 1997:

/* HP-UX sucks wet farts from dead pigeons' asses */

Such pearls were unfortunately removed before Moz went open-source ...


// GK Experimental

(GK being the initials of the coder)

Used to indicate parts of code which are, indeed, kind of experimental. :)

A great flag to know that when you hit it during debugging you're probably busy for the upcoming few hours fixing the hack.. ;)


//ALL YOUR BASE ARE BELONG TO US

...it made my boss think someone had hacked in. He didn't know the joke.


Spelunking through the Hardware Abstraction Layer while working for a certain Finnish Mobile Network Equipment Manufacturer I found 100+ occurrences of the Finnish word "puukko".

A 'puukko' is an all purpose knife that every Finn has in their toolbox or around the house. It is used for everything from pealing potatoes to performing computer repairs (my observations). I believe in this context it is the Finnish equivalent of the word 'Hack'.

My Finnish colleagues denied this and said it meant something more like 'surgical procedure/intervention'... and I almost believed them until I found the comment:

/* Perkele ISO Puukko! */ -> Fucking Big Hack!

In eMule, Preferences.cpp, in the method that forces a minimum upload speed limit proportional to your download speed limit:

uint16 CPreferences::GetMaxDownload(){
//dont be a Lam3r :)
    uint16 maxup=(GetMaxUpload()==UNLIMITED)?GetMaxGraphUploadRate():GetMaxUpload();
    if( maxup < 4 )
        return (( (maxup < 10) && (maxup*3 < prefs->maxdownload) )? maxup*3 : prefs->maxdownload);
    return (( (maxup < 10) && (maxup*4 < prefs->maxdownload) )? maxup*4 : prefs->maxdownload);
}

A German comment in some source-code, translated by machine or very tired human + Google

; Rechnen ja ; have faith in yes

I guess the original meant "assume true here" ... but ever since I've taken it as a mantra for my life.


Nice one in VB.NET that I ran into this morning, got a chuckle ...

''' <summary>
''' Represents an exception that was logged.  Since System.Exception implements IDictionary, it can't be
''' serialized, so I had to write this.  Pretty fucking stupid thing to have to do, System.Exception should
''' be serializable right out of the box, IMHO.
''' </summary>
''' <remarks></remarks>
Public Class LogException

double t = 0.0; /* that's generally my opinion of the diner, too. */

//Abandon all hope ye who enter beyond this point

/*
after hours of consulting the tome of google
i have discovered that by the will of unknown forces
without the below line, IE7 believes that 6px = 12px
*/
font-size: 0px;

'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
'
'  NOTE: DON'T SCREW WITH THIS CODE UNLESS YOU REALLY UNDERSTAND IT!
'
'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

/* Emits a 7-Hz tone for 10 seconds.
  True story: 7 Hz is the resonant frequency of a
  chicken's skull cavity. This was determined
  empirically in Australia, where a new factory
  generating 7-Hz tones was located too close to a
  chicken ranch: When the factory started up, all the
  chickens died.
  Your PC may not be able to emit a 7-Hz tone. */

main()
{
    sound(7);
    delay(10000);
    nosound();
}

(the sound function in the Turbo C version 2.0 Reference Guide)


From the Linux Kernel source:

linux/include/asm-i386/hw_irq.h:

/*
 * subtle. orig_eax is used by the signal code to distinct between
 * system calls and interrupted 'random user-space'. Thus we have
 * to put a negative value into orig_eax here. (the problem is that
 * both system calls and IRQs want to have small integer numbers in
 * orig_eax, and the syscall code has won the optimization conflict ;)
 *
 * Subtle as a pigs ear.  VY
 */

From a contractor in an application for a UK bank.

// i don't know how this works but it does so i'll leave it here anyway

He also added BNP (British very right wing party) as 1 of the dummy customers for testing... our immediate boss was of Asian ethnicity.


From one of our projects.
Somewhere at the end of one source file.

/*@                                    /\  /\
 * @                                  /  \/  \                        ----- |   | ----      |---\ |    | /--\  --- |   |  ---- /--\ /--\
 *  @                                /        --                        |   |   | |         |   / |    | |      |  |\  |  |    |    |
 *   \---\                          /           \                       |   |---| ----      |--/  |    |  \     |  | \ |  ----  \    \
 *    |   \------------------------/       /-\    \                     |   |   | |         |  \  |    |   -\   |  |  \|  |      -\   -\
 *    |                                    \-/     \                    |   |   | ----      |---/  \--/  \--/  --- |   \  ---- \--/ \--/
 *     \                                             ------O
 *      \                                                 /                 --- |   | ----  /--\        |--\   /--\   /--\
 *       |    |                    |    |                /                   |  |\  | |    |    |       |   | |    | |
 *       |    |                    |    |-----    -------                    |  | \ | ---- |    |       |   | |    | | /-\
 *       |    |\                  /|    |     \  WWWWWW/                     |  |  \| |    |    |       |   | |    | |    |
 *       |    | \                / |    |      \-------                     --- |   \ |     \--/        |--/   \--/   \--/
 *       |    |  \--------------/  |    |
 *      /     |                   /     |
 *      \      \                  \      \
 *       \-----/                   \-----/
 */

private static final Logger lager = new Logger();

<cftry>
...code...
<cfcatch>
  <!--- Gobble --->
</cfcatch>
<cftry>

It's all over my companies code base. It's ColdFusion and it simply ignores errors.


return 1; # returns 1

Some years ago I was working in a large code base that had no unit-testing to speak of.

There was a method buried deep within the code that performed some calendar calculations. It was somewhat broken, had to deal with daylight savings in a very clumsy way due to some unfortunate circumstances.

We had to fix it a couple of times, and every time, we would find something broken some months after.

After spending a whole day fixing it and analyzing it, I put the code in source control, along with a comment that said something like this:

// this code was written after a version trying to do {this} failed because of {reason},
// previously we were doing {this} which failed because of {reason}. This is 
// now written {this} way so that {lots of reasons here}. If you want to touch
// this code, please make sure that it produces the right answers when tested with:
//
// {some sort of unit test}

Ultimately, my team was outsourced. Some days I wonder what happened to this code :)


From Apache Xalan source code:

/**
 * As Gregor Samsa awoke one morning from uneasy dreams he found himself
 * transformed in his bed into a gigantic insect. He was lying on his hard,
 * as it were armour plated, back, and if he lifted his head a little he
 * could see his big, brown belly divided into stiff, arched segments, on
 * top of which the bed quilt could hardly keep in position and was about
 * to slide off completely. His numerous legs, which were pitifully thin
 * compared to the rest of his bulk, waved helplessly before his eyes.
 * "What has happened to me?", he thought. It was no dream....
 */
protected static String DEFAULT_TRANSLET_NAME = "GregorSamsa";

Further reading on The Daily WTF.


I discovered this gem when viewing the HTML source of an earlier iteration of the TVNZ website (from line 571 if you're playing along at home):

<!-- Hopfully we can do this otherwise the nav is going to be pretty plain and Hong will go postal. -->

int MyFunction()
{
    // There once was a man named Dave
    int Result = 0;

    // Whose code just wouldn't behave
    MyObject *Ptr = new MyObject();

    // He left to go to a meetin'
    Result = Ptr->DoSomething();

    // And left his memory a leakin'
    return Result;
}

C++ Comment


Great one from leaked Windows 2000 source code :

!!!!!!!IF YOU CHANGE TABS TO SPACES, YOU WILL BE KILLED!!!!!!! *
!!!!!!!!!!!!!!DOING SO FUCKS THE BUILD PROCESS!!!!!!!!!!!!!!!! *
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

http://www.kuro5hin.org/story/2004/2/15/71552/7795


// If this comment is removed the program will blow up 

//marco 2007.1.23
//I didn't do it

Sanitized:

//Forward declarations:

class X {}; // TODO: Remove {}  ! When we get X defined....

# let's pretend we are free, for a while

Found this one in front of a class. What followed was a (naive) try to implement an ORM. I still don't understand why he wrote that.


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

That one is by Donald Knuth.


Great one from leaked Windows 2000 source code :

!!!!!!!IF YOU CHANGE TABS TO SPACES, YOU WILL BE KILLED!!!!!!! *
!!!!!!!!!!!!!!DOING SO FUCKS THE BUILD PROCESS!!!!!!!!!!!!!!!! *
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

http://www.kuro5hin.org/story/2004/2/15/71552/7795


// I'm sorry.

# absolutely foul heuristic code.
# ..it's dirty, but you want it.

and:

# VERY USEFUL DEBUGGING AID, for when the above all goes pearshaped:

/* Halley's comment */

// I know the line below is wrong, but it came that way from our IP vendor, and 
// the driver won't work if you "fix" it. I've had to revert this change 4 times
// now. Leave it alone, or I will hunt you down and hurt you
if (r = 0) {
    /* bunch of code here */
}
else
{
   /* even more code here */
}

Using semi-colons in VB.NET

TextBox2.Visible = True';
For Each row In data.Tables(0).Rows
    If row("Customers.Id").ToString <> customerId Then
        customerId = row("Customers.ID").ToString';
        name = "Customer Name: " & row("Name").ToString & CrLf';
        address = "Address: " & row("Address").ToString & CrLf & CrLf';
        TextBox2.Text += name & address ';s
    End If';
Next';

class Act //That's me!!!
{

}

Just added this one today:

// Hardcoded this for time sake ... will make andrew fix later :)

in a completely uncommented 2000 line method

{ 
  { 
    while (.. ){ 
      if (..){
          }
      for (.. ){ 
          }
         .... (just putting in the control flow here, imagine another few hundred ifs)
      if(..)   {
            if(..)     {
                   if(..)   {
                ...
                (another few hundred brackets)
                       }
                  }
         } //endif

(I actually grepped out all the brackets one day just to see how bad it was, and, sans formatting, got this:

{{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}    {{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}

The endif showed up around line 800)


/* FIXME This must absolutely be removed before 4.0.7 release
 * TODO really remove this */

we have since released a 4.0.7, 4.0.8, 4.0.9 and 4.1 version...


// Any maintenance developer who can't quote entire Monty Python
// movies from memory has no business being a developer. 
const string LancelotsFavoriteColor = "$0204FB"

//Abandon all hope ye who enter beyond this point

//Code sanitized to protect the foolish.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Web.UI;

namespace Mobile.Web.Control
{
    /// <summary>
    /// Class used to work around Richard being a fucking idiot
    /// </summary>
    /// <remarks>
    /// The point of this is to work around his poor design so that paging will 
    /// work on a mobile control. The main problem is the BindCompany() method, 
    /// which he hoped would be able to do everything. I hope he dies.
    /// </remarks>
    public abstract class RichardIsAFuckingIdiotControl : MobileBaseControl, ICompanyProfileControl
    {
        protected abstract Pager Pager { get; }

        public void BindCompany(int companyId) { }

        public RichardIsAFuckingIdiotControl()
        {
            MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity();
        }

        private void MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity()
        {
            // Make sure nobody is actually using that fucking bindcompany method
            MethodInfo m = this.GetType().GetMethod("BindCompany", BindingFlags.DeclaredOnly | 
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (m != null)
            {
                throw new RichardIsAFuckingIdiotException("No!! Don't use the fucking BindCompany method!!!");
            }
            // P.S. this method is a joke ... the rest of the class is fucking serious
        }

        /// <summary>
        /// This returns true if this control is supposed to be doing anything
        /// at all for this request. Richard thought it was a good idea to load
        /// the entire website during every request and have things turn themselves
        /// off. He also thought bandanas and aviator sunglasses were "fuckin' 
        /// gnarly, dude."
        /// </summary>
        protected bool IsThisTheRightPageImNotSureBecauseRichardIsDumb()
        {
            return Request.QueryString["Section"] == this.MenuItemKey;
        }

        protected override void OnLoad(EventArgs e)
        {
            if (IsThisTheRightPageImNotSureBecauseRichardIsDumb())
            {
                Page.LoadComplete += new EventHandler(Page_LoadComplete);
                Pager.RowCount = GetRowCountBecauseRichardIsDumb();
            }
            base.OnLoad(e);
        }

        protected abstract int GetRowCountBecauseRichardIsDumb();
        protected abstract void BindDataBecauseRichardIsDumb();

        void Page_LoadComplete(object sender, EventArgs e)
        {
            BindDataBecauseRichardIsDumb();
        }

        // the rest of his reduh-ndant interface members
        public abstract string MenuItemName { get; set; }
        public abstract string MenuItemKey { get; set; }
        public abstract bool IsCapable(CapabilityCheck checker, int companyId);
        public abstract bool ShowInMenu { get; }
        public virtual Control CreateHeaderControl()
        {
            return null;
        }
    }
}

Update: The original author of the code has outed himself so I must give credit where it is due. Dan McKinley left the company I was with shortly after I started, and he talks more about the code, explaining some background and a few more "WTF's" that 'Richard' wrote.


// HACK ! COPY/PASTE this and look for another job

   // Some wanker in ISO got rid of ifstream(int), ofstream(int), and
   // fstream(int).  Twit.

Not code comments, but SVN commit comments on the same file:

First commit (following of dozens of others after results coming back from testers):

Squashed some IPR mod bugs. The were big and juicy ones, too.

2nd commit:

Squashed some more mod bugs. Those are some nasty bugs, them mod bugs...

3rd:

Squashed some more mod bugs. They are like cockroaches: they'll live through a nuclear war.

4th:

Squashed some more John bugs. They too are like cockroaches: they appear anywhere John goes. Wait. That doesn't sound right.

And 5th:

Same John bug. It didn't die, just played 'possum.

Yes, I was tired of "Fixed bug".


/*
This isn't the right way to deal with this, but today is my last day, Ron
just spilled coffee on my desk, and I'm hungry, so this will have to do...
*/

return 12; // 12 is my lucky number

I've just placed this comment:

// this control (Resistance) is FUTILE! 

long long ago; /* in a galaxy far far away */ 

Well-written Lisp is one of the easiest to read languages and I love it. But poorly written Lisp can be a nightmare so much worse than bad Java, etc.

Here, we need to create a "group file" if there exist 3 variants of an original file named with the suffixes a, b and c. I had been trying to track down a strange bug where we were getting unnecessary group files...

  (let ((varianta (format nil "~aa" problem))
        (variantb (format nil "~ab" problem))
        (variantc (format nil "~ac" problem)))
    ;;if the A and B variants exist, create a group file
    ;;(why not just check for a? I don't know, this just feels right)
    (when (and (probe-file varianta)
               (probe-file variantb))
      ...)))

Bug: 1, Gut: 0.

Apparently it didn't occur to whoever wrote this that perhaps checking for all three variants would be a good idea. Of course, that was the bug I ended up tracking down a decade after this code was originally written (it predates the first SVN log).


//The following code is commented out
//(a load of commented out code followed)

/* Hammer Time! */

I have no idea why or whether he was wearing ripstop nylon parachute pants while writing the code


Some years ago I was working in a large code base that had no unit-testing to speak of.

There was a method buried deep within the code that performed some calendar calculations. It was somewhat broken, had to deal with daylight savings in a very clumsy way due to some unfortunate circumstances.

We had to fix it a couple of times, and every time, we would find something broken some months after.

After spending a whole day fixing it and analyzing it, I put the code in source control, along with a comment that said something like this:

// this code was written after a version trying to do {this} failed because of {reason},
// previously we were doing {this} which failed because of {reason}. This is 
// now written {this} way so that {lots of reasons here}. If you want to touch
// this code, please make sure that it produces the right answers when tested with:
//
// {some sort of unit test}

Ultimately, my team was outsourced. Some days I wonder what happened to this code :)


Exhibit a:

return 0; // Happy ending

Exhibit B:

int32_t Interpolate1DSignal(
  Array1D<float64>::Handle hfInputSamples,         // samples to be interpolated
  Array1D<float64>::Handle hfInterpolationFilter,  // polyphase filter coefficients,
  int32_t iFilterInterpolationFactor,              // # of "rows" in polyphase filter
  int32_t iFilterLength,                           // Length of each row in filter
  float64 fInterpolationFactor,                    // Factor to interpolate the
                                                   // signal by
  float64 fTimingOffset,                           // Offset into the signal (units   
                                                   // of samples)
  Array1D<float64>::Handle hfOutputSamples         // left as an exercise for the reader
);

Found over a complex code -

//Jesus and this code have one thing in common: both were resurrected


// I know the line below is wrong, but it came that way from our IP vendor, and 
// the driver won't work if you "fix" it. I've had to revert this change 4 times
// now. Leave it alone, or I will hunt you down and hurt you
if (r = 0) {
    /* bunch of code here */
}
else
{
   /* even more code here */
}

// now swap like a <explicative removed>

I posted this "license statement" in a WordPress template I released. I thought it was funny, anyhow.

/* The License:
You (from this point on referred to as The You) are hereby 
granted by me (from this point on referred to as The Me) 
license to knock yourself silly with this template. 
By using this template The You implicitly accepts this 
license and pledges solemnly to never claim creative 
ownership of any graphics, code, concepts, eggs, bacon, ideas, 
colors, shapes, hypertext-transfer protocols or other conduits 
of the visual splendor thatis this template. 

The Me, in turn, pledges equally solemnly to be far too 
lazy to ever check up on you, so if you do manage to pull 
some chicks The Me won't have a cow. 
However The Me would be sorely disappointed if The You 
were to try and sell or distribute this work without 
acknowledging The Me. Seriously. The Me will come down on 
The You like a large quantitiy of hard and heavy objects 
that in large quantities may be harmful and possibly even 
lethal to The You; So don't even think about it, The Buster.
*/

return 1; # returns 1

<!-- THIS IS THE MAIN CONFIGURATION FILE FOR THE ENTIRE BLOODY DIRECTORY    -->
<!--    WHATEVER YOU DO, DO NOT EDIT THIS FILE WITHOUT TALKING TO ME FIRST  -->
<!--                                I'M SERIOUS                             -->
<!-- (scroll down) -->

// Any maintenance developer who can't quote entire Monty Python
// movies from memory has no business being a developer. 
const string LancelotsFavoriteColor = "$0204FB"

// I love the smell of dirty XML in the morning
xml = xml.Replace("xmlns=\"urn:bsd.orion/inventory\"", "");

// Magic. Do not touch.

-- Beyond this point, there'll be dragons

I find it more pleasingly illustrative with the longer saying ^^


catch (Ex as Exception)
{
     // oh crap, we should do something.
}

Nothing like an empty catch block to make one feel that the code is robust....


See this one:

'On Error Goto Hell.

// Description : !!! TODO


// If this comment is removed the program will blow up 

//The following 1056 lines of code in this next method 
//is a line by line port from VB.NET to C#.
//I ported this code but did not write the original code.
//It remains to me a mystery as to what
//the business logic is trying to accomplish here other than to serve as
//some sort of a compensation shell game invented by a den of thieves.
//Oh well, everyone wants this stuff to work the same as before.
//I guess the devil you know is better than the devil you don't.

A funny typo that was strangely appropriate:

assert(0); // should never shit this point


public boolean isDirty() {
    //Why do you always go out and
    return dirty;
}

aComment = 'this is not aComment' # this is aComment
class T(object):
    def f(this):
        this is not aComment

In SJ CA back during the early days of the auction business I worked with a guy named Rick Dorin. He wrote compilers back when you had to poke at cards all day long. One of his error messages was

Too Many Errors... Make fewer!


/*
after hours of consulting the tome of google
i have discovered that by the will of unknown forces
without the below line, IE7 believes that 6px = 12px
*/
font-size: 0px;

// If I from the future read this I'll back in time and kill myself. 

Once I saw in another discussion something like this:

// I can't divide with zero, so I have to divide with something very similar
result = number / 0.00000000000001;

Clever solution, isn't it :) ? (It's a joke if someone's not sure)


The ascii-art skull and crossbones (which is too difficult to recreate here) in Gosling's Emacs source (warning that the ultra-hot screen management package he wrote was not easily understood).


Get This hack!

On a line of assembler code, after pages of uncommented code.


Back around the time the Hitchhiker's Guide game was new, I had a case where I was testing whether something was scrollable and whether the user was trying to scroll, in a language that restricted variable length. So:

if (scroll and noScroll) # or tea and no tea

i just noticed myself writing this

// not brilliant solution, but fair enough heh.

TextBox1.Text = TextBox1.Text; //Point less yes, who writes this crap?

//The following code is commented out
//(a load of commented out code followed)

A compilation of my greatest hits:

// Thats the end of the While loop
// Clean up last row.  I really must program better than this.

// Note: You can't immediately tell if the line below works.

// Rounding - blech.  It's assumed that all .5s are rounded up.

// Sort out predictions first.  Seems like the right place for a prediction, 'first'.

// Let's interpret!

I have used this one on more than one occasion, when I've done some kind of non-obvious simplification to a mathematical formula that I don't feel like documenting:

//this formula is right, work out the math yourself if you don't believe me

I just found this in some legacy code..

'CANNOT JUST QUIT!

From the Linux Kernel source:

linux/include/asm-i386/hw_irq.h:

/*
 * subtle. orig_eax is used by the signal code to distinct between
 * system calls and interrupted 'random user-space'. Thus we have
 * to put a negative value into orig_eax here. (the problem is that
 * both system calls and IRQs want to have small integer numbers in
 * orig_eax, and the syscall code has won the optimization conflict ;)
 *
 * Subtle as a pigs ear.  VY
 */

From C#

#region Hack - Shield Eyes Before Expanding

/// <summary>
/// A single uint with all of the bits set to represent the different tracing
/// </summary>
/// <remarks>
/// Ugly I know, so if you can think of a better way, feel free to rewrite.
/// </remarks>
[Browsable(false)]
public uint TraceBitfield
{
    // Snip
}

#endregion

Once I found this:

// I wish (boss name) could do this by him self.

// Okay, let's do the loop, yeah come on baby let's do the loop
// and it goes like this ...

From one of our projects.
Somewhere at the end of one source file.

/*@                                    /\  /\
 * @                                  /  \/  \                        ----- |   | ----      |---\ |    | /--\  --- |   |  ---- /--\ /--\
 *  @                                /        --                        |   |   | |         |   / |    | |      |  |\  |  |    |    |
 *   \---\                          /           \                       |   |---| ----      |--/  |    |  \     |  | \ |  ----  \    \
 *    |   \------------------------/       /-\    \                     |   |   | |         |  \  |    |   -\   |  |  \|  |      -\   -\
 *    |                                    \-/     \                    |   |   | ----      |---/  \--/  \--/  --- |   \  ---- \--/ \--/
 *     \                                             ------O
 *      \                                                 /                 --- |   | ----  /--\        |--\   /--\   /--\
 *       |    |                    |    |                /                   |  |\  | |    |    |       |   | |    | |
 *       |    |                    |    |-----    -------                    |  | \ | ---- |    |       |   | |    | | /-\
 *       |    |\                  /|    |     \  WWWWWW/                     |  |  \| |    |    |       |   | |    | |    |
 *       |    | \                / |    |      \-------                     --- |   \ |     \--/        |--/   \--/   \--/
 *       |    |  \--------------/  |    |
 *      /     |                   /     |
 *      \      \                  \      \
 *       \-----/                   \-----/
 */

-- Comment this later

That was line 2 of a 4000+ line PL/SQL procedure. And the only comment. 4 years after that procedure was developed, later still hadn't come...


int MyFunction()
{
    // There once was a man named Dave
    int Result = 0;

    // Whose code just wouldn't behave
    MyObject *Ptr = new MyObject();

    // He left to go to a meetin'
    Result = Ptr->DoSomething();

    // And left his memory a leakin'
    return Result;
}

C++ Comment


When coding MAPPER Apps we had some standards and one of these was that there was a list of standard variables in use throughout the suite. One of these - 'V43' was always used to hold a Surname. So imagine my annoyance when the only comment in a big cryptic chunk of MAPPER code I'd been asked to fix was:

Here V43 contains the Surname

// if the resultMap size is less than or equal to zero
// then the product is added
if (resultMap.size() <= 0)

This was actually made by me when I was implementing a prototype turned into real code:

// Abandon all hope you who needs to debug this

Yes, someone smarter than me actually refactored the code afterwards (it had to have a good ending).


//Woulda
if(x) {}
//Shoulda
else if(y) {}
//Coulda
else {}

// John! If you'll svn remove this once more,
// I'll shut you, for God's sake!
// That piece of code is not “something strange”!
// That is THE AUTH VALIDATION.

And what do you think? The code below was safely ‘svn removed’.


Quite a while ago I came across some connection script and while I don't remember the syntax I do recall the comments as I'm a Pink Floyd fan.

//Attempt Handshake: Hello? This is London calling. Are we reaching you?


//Handshake Failed: I don't understand...he just hung up.

I saw this once:

//this used to be a comment

A classic case of why you shouldn't off shore your software development:

public class Contact
{
    //...    

    /// <summary>
    /// Gets or sets the name of the first.
    /// </summary>
    /// <value>The name of the first.</value>
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
}

In a game where this object can be stepped on, or:

stepOff(); //bitch

Near the top of a unit:

// Oh what a tangled web we weave
// When first we practice to deceive
// ASTA

In a class named "Bar" (which was a UI Control with a less than descriptive name), the class header:

/// <summary>I pity the "foo".</summary>

And the Remove() method:

/// <summary>A "foo" and his money are soon parted.</summary>

Even worse, it was a business partner that pointed it out from the generated documentation. Even worse than that, is those are probably the closest things to useful documentation we ever got out of the guy.


I've just placed this comment:

// this control (Resistance) is FUTILE! 

Just added this one today:

// Hardcoded this for time sake ... will make andrew fix later :)

/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}

Never rely on a comment...


// I know the line below is wrong, but it came that way from our IP vendor, and 
// the driver won't work if you "fix" it. I've had to revert this change 4 times
// now. Leave it alone, or I will hunt you down and hurt you
if (r = 0) {
    /* bunch of code here */
}
else
{
   /* even more code here */
}

In drivers/net/sunhme.c (Linux kernel):

/* 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->frame,
            (FRAME_WRITE | (hp->paddr << 23) |
             ((reg & 0xff) << 18) | (value & 0xffff)));
while(!(hme_read32(hp, &tregs->frame) & 0x10000) && --tries)
        udelay(20);

/* Anything else? */
if(!tries)
        printk(KERN_ERR "happy meal: Aieee, transceiver MIF write bolixed\n");

/* Fifty-two cents is your change, have a nice day. */

"This will never happen".

Famous last words my friend...


//This code sucks, you know it and I know it.  
//Move on and call me an idiot later.

From one of our projects.
Somewhere at the end of one source file.

/*@                                    /\  /\
 * @                                  /  \/  \                        ----- |   | ----      |---\ |    | /--\  --- |   |  ---- /--\ /--\
 *  @                                /        --                        |   |   | |         |   / |    | |      |  |\  |  |    |    |
 *   \---\                          /           \                       |   |---| ----      |--/  |    |  \     |  | \ |  ----  \    \
 *    |   \------------------------/       /-\    \                     |   |   | |         |  \  |    |   -\   |  |  \|  |      -\   -\
 *    |                                    \-/     \                    |   |   | ----      |---/  \--/  \--/  --- |   \  ---- \--/ \--/
 *     \                                             ------O
 *      \                                                 /                 --- |   | ----  /--\        |--\   /--\   /--\
 *       |    |                    |    |                /                   |  |\  | |    |    |       |   | |    | |
 *       |    |                    |    |-----    -------                    |  | \ | ---- |    |       |   | |    | | /-\
 *       |    |\                  /|    |     \  WWWWWW/                     |  |  \| |    |    |       |   | |    | |    |
 *       |    | \                / |    |      \-------                     --- |   \ |     \--/        |--/   \--/   \--/
 *       |    |  \--------------/  |    |
 *      /     |                   /     |
 *      \      \                  \      \
 *       \-----/                   \-----/
 */

// I am not sure if we need this, but too scared to delete. 

From a classic from usenet:

Deep inside the Teradyne hardware modeler code is a routine that feeds a whole bunch of hex numbers into a SYS$QIO call. The only comment is 'Weird magic happens here'.


/* Hammer Time! */

I have no idea why or whether he was wearing ripstop nylon parachute pants while writing the code


# as you can see: I comment the code!


In a bunch of poorly cut & pasted source code for a content management web app:

// load image 1 - JPEG 240x320
img = f1.getImage();
if (check(img))
{
   load(img, Constants.JPEG_240x320);
}

// load image 2 - JPEG 128x128
img = f2.getImage();
if (check(img))
{
   load(img, Constants.JPEG_128x128);
}

...

// load image 13 - GIF 256x256
img = f13.getImage();
if (check(img))
{
   load(img, Constants.GIF256x256);
}

// loaded all of the f**king images

note: roughly translated from italian :-)


This was the only comment we found in a smartcard product that a previous employer bought in. A load of embedded C and assembler written by a bunch of Dutch cryptography PhDs

// echt halmaal gek - no way!

(It means something like "really completely stupid"...which didn't help us either)


{
This is a gathering place for all unit tests.
Create a TUnitTestWrapper, then call "RunAllUnitTests".

This class will create an instance of each thing to be tested, and call each of
their unit tests.

It does not really do any testing on it's own; it just gives a common place from
which to call everyone else's tests.

This way, one day, we can automate our testing with each build. [Cue laughter]
}

"This will never happen".

Famous last words my friend...


About the middle of a 30 page xslt

<!-- Here be dragons  -->

Linux Comments

There are heaps of good ones here ...

These are all comments in linux

http://lwn.net/1998/1015/a/f-word.html

My Favourites:

./arch/sparc/kernel/ptrace.c
/* Fuck me gently with a chainsaw... */

./drivers/scsi/qlogicpti.h
/* Am I fucking pedantic or what? */

' Oh man I'm pissed. I think I better go home.

where pissed = drunk


The ascii-art skull and crossbones (which is too difficult to recreate here) in Gosling's Emacs source (warning that the ultra-hot screen management package he wrote was not easily understood).


I cried when I read this one on a project I was given to maintain.

//Write Code Here

I still cringe :)


A comment I added to a PHP CMS I was working on a while back.

if (/*you*/ $_GET['action']) { //celebrate

// set break point here - you'll never reach it

Not code comments, but SVN commit comments on the same file:

First commit (following of dozens of others after results coming back from testers):

Squashed some IPR mod bugs. The were big and juicy ones, too.

2nd commit:

Squashed some more mod bugs. Those are some nasty bugs, them mod bugs...

3rd:

Squashed some more mod bugs. They are like cockroaches: they'll live through a nuclear war.

4th:

Squashed some more John bugs. They too are like cockroaches: they appear anywhere John goes. Wait. That doesn't sound right.

And 5th:

Same John bug. It didn't die, just played 'possum.

Yes, I was tired of "Fixed bug".


i tell a mentee to do at least SOME exception handling. This is what i get in return around every db call....

Catch (Exception e) {
    //eat it
}

This comment was in a unit containing interfaces which were used to bind communication between the main application and various 3rd party drivers.

//**************************************
// Dear code maintainer:
//
// This source contains COM interfaces, not to be confused with interfaces 
// of any other sort, please do not just willy-nilly add additional methods 
// to these interfaces as they are truely immutable, unlike the interfaces 
// that other software vendors like Microsoft maintain.  IF you need to add 
// new functionality, then go thru the trouble of creating a NEW interface 
// and implement this functionality on only the objects you need.  
//
// While the money is good for fixing all of the problems caused by not 
// following the rules, I would rather work on things which actually have
// an impact on the future of the product rather than curse and yell 
// obsenities at the screen because someone didn't bother to understand the
// true meaning of IMMUTABLE.  
//**************************************

//There can Only Be one HIGHLAN....err..Singleton
public class SomeSingleton
{
...
}

// TODO: what the hell is this all about?

And then some commented out code.

This was found in our code in work earlier today. I'm not sure if I should laugh or cry...


// Description : !!! TODO


Repeat
    ...
Until (JesusChristsReturn) ' Not sure

I once came up with what I thought was an elegant solution to a particularly sticky problem, in retrospect it was a bit of a mind-bender and made some heavy use of macro programmimg. Years later I found this comment from a maintenance programmer

/*
    Description: The Total Perspective Vortex derives its picture of the
                 whole Universe  on the principle of extrapolated matter
                 analyses.

                 To  explain  -  since every piece of matter in the Universe
                 is in some way affected by every other piece of matter in
                 the  Universe,  it  is  in  theory possible to extrapolate
                 the whole of creation - every sun, every planet, their
                 orbits, their composition and their economic and social
                 history from, say, one small Macro.

                 The man who invented the Total Perspective Vortex did so
                 basically in order to annoy the IT department.

                 Steve Weet - for that was his name - was a dreamer, a
                 thinker, a speculative philosopher or, as some would have
                 it, a slacker.

                 And they would nag him incessantly about the utterly
                 inordinate amount of time he spent staring out into space,
                 or mulling over the mechanics of Chelsea FC, or doing
                 spectrographic analyses of macros.

                 "Have  some  sense  of  proportion!"  they would say,
                 sometimes as often as thirty-eight times in a single day.

                 And so he built the Total Perspective Vortex - just to show
                 them.

                 And into one end he plugged the whole of reality as
                 extrapolated  from one  macro, and into the other
                 end he plugged the IT department: so that when he turned it
                 on they saw in one instant the whole infinity of creation 
                 and theirselves in relation to it.

                 To  Steve Weet's horror, the shock completely annihilated '
                 their brains; but to his satisfaction he realized that he
                 had proved conclusively that if life is going to exist in a
                 Universe of this size, then the one thing it cannot afford
                 to have is a sense of proportion.

*/

here are 4, in no order:

// Father, forgive me, for I am sinning

// heaven help me

// horse string-length into correctitude 
(from a textbook)

// what, me worry?

In a large investment bank that required all application outages be logged and commented I saw

Without a crash 

Or mighty bang 

The sync disk 

Did it's process hang

I once implemented some document workflow using MS SQL Server Developer 2000 (the human workflow stuff).

It consisted of a bunch of triggers that would be added to the database to make it follow workflow rules.

In one of the triggers, someone at Microsoft had written something along the lines of:

//Determine if the database has been "Grizzlified"

(The internal name of the product was "Grizzly", so I thought that was funny).


From an absolutely lovely project I worked on up until recently (yes, I admit, some of those are mine, but I won't tell you which):

if(FAILED(hr))
{
    char fuck[256];
    sprintf(fuck, "GetBuffer() fucking fucked the fuck: %d", hr);
    MessageBoxA(0, fuck, fuck, MB_OK | MB_ICONERROR);
    return;
}


// This is for Chris, since he gets all hot and horny over "uint" instead of "unsigned int"
// ... or maybe he's just a lazy fuck. Who knows!?
using Ogre::uint; 
// movable texts, fucktory
MovableObjectTextFactory* m_pMovableObjectTextFactory;


// diarrhea... shitting CR from the string. complete run...

What he meant was that he's splitting the string by carriage returns to render separately.

// unlock shit (duh, this comment is useless)
pixelBuffer->unlock();


// :HACK: remove me after demo is shipped
Of course, it's still in there ;)


// it's 4am and I can't think of a decent error message.
// my lead just fell asleep at his desk, so I can't ask him.
// [name] went home because he didn't want to get divorced.
// and so it's little ol' me, sitting here, comin up with an
// error message for something that should never ever happen.
ASSERT0(in_len == max_in, "http://www.youtube.com/watch?v=oHg5SJYRHA0"); 


// you want hungarian, you GET hungarian!
for(int fcknglpidxcntvrI = 0; fcknglpidxcntvrI &lt; len; fcknglpidxcntvrI++)


bool bKillSomethingAlive = false; // beating the dead horse instead

Of course, we also have a nice collection of interesting ways to say "Hack":

// HACKOMATIC 
// HMM... HACKXOR?
// HACK'O'ROONY
// AR; yeah I know it's HACKsoup
// HACK SHOT! DOMINATING!
// HACK'KIDO
// HACKku. sepukku. harakiri. kamikaze. ninja.
// HACK'o'NEIL
// HACKsaw

Found in the JUnit API:

/**
 * ...as the moon sets over the early morning Merlin, Oregon
 * mountains, our intrepid adventurers type...
 */
public Test createTest(Class theClass, String name) {
    ...
}

I had to add this one to our old datatable-driven rules engine before I decided to replace it with a scripting language.

        /************************************************************
        *                                                           *
        *  .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
        *   |                     ______                     |      *
        *   |                  .-"      "-.                  |      *
        *   |                 /            \                 |      *
        *   |     _          |              |          _     |      *
        *   |    ( \         |,  .-.  .-.  ,|         / )    |      *
        *   |     > "=._     | )(__/  \__)( |     _.=" <     |      *
        *   |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
        *   |           "=._"(_     ^^     _)"_.="           |      *
        *   |               "=\__|IIIIII|__/="               |      *
        *   |              _.="| \IIIIII/ |"=._              |      *
        *   |    _     _.="_.="\          /"=._"=._     _    |      *
        *   |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
        *   |    > _.="                            "=._ <    |      *
        *   |   (_/                                    \_)   |      *
        *   |                                                |      *
        *   '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
        *                                                           *
        *      LASCIATE OGNI SPERANZA, VOI CH'ENTRATE               *
        *************************************************************/

$dnstime = time() + 60 * 60 * 24 * 7 * 2; //how long are you staying for vacation on mars? twooo weeeeeks. give dees people air

int Q13Factor = 8125; // 2^13 for Q13 

From Joomla! source:

// fudge the group stuff

Tweet tweet = (Tweet) tweets.get(i); // Poetic.

In an LKM:

/*
* Dear Richard Stallman,
*
* This one's for you.
*
* Sincerely,
* Me
*
*/
MODULE_LICENSE( "GPL" );

I found this when re-using a PHP class I wrote a fair amount of time ago. I still cant remember what went there and I still have found no use for it... I actually don't even remember me writing that comment; so I literally laughed out loud when I found it.

try
{               
    // Some database logic
}
catch (Exception $ex)
{
    // sure, it looks silly and I honestly cant remember what code used to go here... but i swear i will
    // find a use for this code.... eventually....
    throw $ex;
}

def leppard
# what, i cant have my own convention?
end

my favorite was something like this

 # commented out
 ...
 ### end of the formerly uncommented #2001-02-22 John Doe

Great one from leaked Windows 2000 source code :

!!!!!!!IF YOU CHANGE TABS TO SPACES, YOU WILL BE KILLED!!!!!!! *
!!!!!!!!!!!!!!DOING SO FUCKS THE BUILD PROCESS!!!!!!!!!!!!!!!! *
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

http://www.kuro5hin.org/story/2004/2/15/71552/7795


I see this one a lot:

// TODO make this work

The favorite comment I ever wrote:

//the XML returned from this request is *mind-bogglingly* bad. Terrifyingly bad.
//a completed batch looks like this:
//<Batch>batchid=363777811 status=Done dateandtime=09/18/2007 09:53:10 PDT activateditems=335 numberofwarnings=0 itemsnotacivated=17 </Batch>
//and an incomplete batch like:
//<Batch>batchid=363778361 status=In Progress </Batch>
//so we'll just parse each item as a regex. Thanks Amazon.

And yes, Amazon actually returns XML like this.


/**
 * Not even your mum thinks you're special if you call this method
 */    
onlyYourMumThinksYoureSpecialIfYouCallThisMethod() {...}

/*************************** Drag And Drop Section - Start (you should be me to mess with this section)*********************************************/

// Empty constructor to satisfy the stupid compiler
 Public ServletHandlerClass () { } 

// The hackiest hack that ever did hack

It's in the WordPress blog engine (wp-admin/includes/user.php - if anyone actually wants to see the hacky hack itself).


{
This is a gathering place for all unit tests.
Create a TUnitTestWrapper, then call "RunAllUnitTests".

This class will create an instance of each thing to be tested, and call each of
their unit tests.

It does not really do any testing on it's own; it just gives a common place from
which to call everyone else's tests.

This way, one day, we can automate our testing with each build. [Cue laughter]
}

I don't have the exact code package anymore, but I remember the comment vividly.

// The code below needs to be changed immediately.
// I wish I was a little bit taller
// I wish I was a baller
// I wish I had a girl who looked good, I would call her.

Seen in the source code for LucasArts' computer game 'The Eidolon' (Which was wierd and wacky in it's own right)...

// He's dead, Jim!

/* You are not meant to understand this */ 

Not quite a comment but a goto label

ICantBelieveImUsingAGoto:


My favorite (which I must admit I've used many times):

// Yes...I know this is repulsive and stupid.
// But <%CompanyOwnerOrManagerToken%>, not knowing a thing about code,
// demanded I do it anyways. SO, go crap on their desk, not mine.
// K THX BYE 

Fix problem where Nulls don't work properly.  Stupid Microsoft!

Code converted Nulls to zero-length strings line by line in roundabout way because the stupid programmer did not understand what Nulls are and had never heard of the Nz() function.


Seen in the source code for LucasArts' computer game 'The Eidolon' (Which was wierd and wacky in it's own right)...

// He's dead, Jim!

double t = 0.0; /* that's generally my opinion of the diner, too. */

In the middle of a few thousand line JScript file after a completely arbitrary line...

// The world is a happy place.

//todo: never to be implemented

// I don't know why I need this, but it stops the people being upside-down

x = -x;

I've seen this code in a function FULL of Explicit weird casts:

// Since today's CPUs are really fast, this is dedicated to those who said:
// " You can't use Moore's Law as an excuse to write bad software. "

The code was horrendous :)


// If you're reading this, that means you have been put in charge of my previous project.
// I am so, so sorry for you. God speed.

// Bad Christian, No cookie

Cookie in this context does not refer to a browser cookie


/*
* After 36 hours, 2 holes in my wall and writing my code right beside the API
* this still doesn't work.
* function getMap():void takes in an event object @param: evt:mouseEvent
* I will now retire for the day with a bottle of rum and 2 hours of crying
*/

Catch (Exception e) {
 //who cares?
} 

/*
* Wirzenius wrote this portably, Torvalds fucked it up :-)
*/

//The following code is commented out
//(a load of commented out code followed)

Simple but effective comment, before a less than safe hack in some C++ code

// yikes

// The freshest corpse at the back please.
m_DeadCharacters.push_back( std::make_pair(character, 0.0f) );
// Get rid of the rotting surplus
while( m_DeadCharacters.size() > 3 )
    m_DeadCharacters.pop_front();

const int TEN=10; // As if the value of 10 will fluctuate... 

I like some of the comments in the GNU binutils. This one is from BFD som.c:

/* You'll never believe all this is necessary to handle relocations
   for function calls.  Having to compute and pack the argument
   relocation bits is the real nightmare.

   If you're interested in how this works, just forget it.  You really
   do not want to know about this braindamage.  */

This one too:

/* Don't ask about these magic sequences.  I took them straight
   from gas-1.36 which took them from the a.out man page.  */

...

/* Keep track of exactly where we are within a particular
   space.  This is necessary as the braindamaged HPUX
   loader will create holes between subspaces *and*
   subspace alignments are *NOT* preserved.  What a crock.  */

Another one:

/* We will NOT put a fucking timestamp in the header here. Every
   time you put it back, I will come in and take it out again. ... */

From gas:

/* Yes this is ugly (storing the broken_word pointer
   in the symbol slot).  Still, this whole chunk of
   code is ugly, and I don't feel like doing anything
   about it.  Think of it as stubbornness in action.  */

//When I wrote this, only God and I understood what I was doing
//Now, God only knows

The favorite comment I ever wrote:

//the XML returned from this request is *mind-bogglingly* bad. Terrifyingly bad.
//a completed batch looks like this:
//<Batch>batchid=363777811 status=Done dateandtime=09/18/2007 09:53:10 PDT activateditems=335 numberofwarnings=0 itemsnotacivated=17 </Batch>
//and an incomplete batch like:
//<Batch>batchid=363778361 status=In Progress </Batch>
//so we'll just parse each item as a regex. Thanks Amazon.

And yes, Amazon actually returns XML like this.


(A bunch of code that's really weird looking)  //Kludge.

If you have reached this part in the code, then this program sucks.

in a homework assignment in college for a teacher who was particularly adamant that we comment our code:

//I wonder if she actually reads these.

When the assignment was returned, in red pen next to that comment "Yes, I do"


i++; //increment i

 * ...and don't just declare it volatile and think you've solved
 * the problem. You young punks think you know what volatile
 * means... why in my day we had to cast it volatile uphill
 * both ways, and the code still didn't work! Whippersnappers...

/* Jeez, this is an ugly mess */

...comment from the X11R6 internals source code circa 1991.

//Dave chapelle reports errors.
function reporterror() {
  davechapelle.trace("FUCK!");
}

Not a comment but an attribute

[ThereBeDragons]

And one I have seen in an implementation of IHttpHandler

//What is this?
public bool IsReusable
{
    get{return false;}
}

// BEGIN HACK
...
// END HACK: I feel dirty.

Exhibit a:

return 0; // Happy ending

Exhibit B:

int32_t Interpolate1DSignal(
  Array1D<float64>::Handle hfInputSamples,         // samples to be interpolated
  Array1D<float64>::Handle hfInterpolationFilter,  // polyphase filter coefficients,
  int32_t iFilterInterpolationFactor,              // # of "rows" in polyphase filter
  int32_t iFilterLength,                           // Length of each row in filter
  float64 fInterpolationFactor,                    // Factor to interpolate the
                                                   // signal by
  float64 fTimingOffset,                           // Offset into the signal (units   
                                                   // of samples)
  Array1D<float64>::Handle hfOutputSamples         // left as an exercise for the reader
);

// fix for groupid > 9 
// if groupid ever gets to 100 everything will break (again)

if (groupid < 10) {
groupid = "0" + groupid;
}

 * ...and don't just declare it volatile and think you've solved
 * the problem. You young punks think you know what volatile
 * means... why in my day we had to cast it volatile uphill
 * both ways, and the code still didn't work! Whippersnappers...

long john; // silver

I just checked this in the other day...

/// <STERNLY-WORDED-WARNING>
/// Pay attention to this or I will hunt you down.
/// ...
/// </STERNLY-WORDED-WARNING>

Where ("..." == "proprietary stuff that I can't post"). I just liked my STERNLY-WORDED-WARNING element.


// Bad Christian, No cookie

Cookie in this context does not refer to a browser cookie


A few hours after showing a friend this post from Coding Horror, I saw this comment on his code:

// MrValdez is a violent Psychopath. Don't piss him off.


/// <summary>
/// The possible outcomes of an update operation (save or delete)
/// </summary>
public enum UpdateResult
{

    /// <summary>
    /// Updated successfully
    /// </summary>
    Success = 0,

    /// <summary>
    /// Updated successfully
    /// </summary>
    Failed = 1
}

on leaving my last job I embedded some ascii art into the source...


                                      ,_-=(!7(7/zs_.             
                                   .='  ' .`/,/!(=)Zm.           
                     .._,,._..  ,-`- `,\ ` -` -`\\7//WW.         
                ,v=~/.-,-\- -!|V-s.)iT-|s|\-.'   `///mK%.        
              v!`i!-.e]-g`bT/i(/[=.Z/m)K(YNYi..   /-]i44M.       
            v`/,`|v]-DvLcfZ/eV/iDLN\D/ZK@%8W[Z..   `/d!Z8m       
           //,c\(2(X/NYNY8]ZZ/bZd\()/\7WY%WKKW)   -'|(][%4.      
         ,\\i\c(e)WX@WKKZKDKWMZ8(b5/ZK8]Z7%ffVM,   -.Y!bNMi      
         /-iit5N)KWG%%8%%%%W8%ZWM(8YZvD)XN(@.  [   \]!/GXW[      
        / ))G8\NMN%W%%%%%%%%%%8KK@WZKYK*ZG5KMi,-   vi[NZGM[      
       i\!(44Y8K%8%%%**~YZYZ@%%%%%4KWZ/PKN)ZDZ7   c=//WZK%!      
      ,\v\YtMZW8W%%f`,`.t/bNZZK%%W%%ZXb*K(K5DZ   -c\\/KM48       
      -|c5PbM4DDW%f  v./c\[tMY8W%PMW%D@KW)Gbf   -/(=ZZKM8[       
      2(N8YXWK85@K   -'c|K4/KKK%@  V%@@WD8e~  .//ct)8ZK%8`       
      =)b%]Nd)@KM[  !'\cG!iWYK%%|   !M@KZf    -c\))ZDKW%`        
      YYKWZGNM4/Pb  '-VscP4]b@W%     'Mf`   -L\///KM(%W!         
      !KKW4ZK/W7)Z. '/cttbY)DKW%     -`  .',\v)K(5KW%%f          
      'W)KWKZZg)Z2/,!/L(-DYYb54%  ,,`, -\-/v(((KK5WW%f           
       \M4NDDKZZ(e!/\7vNTtZd)8\Mi!\-,-/i-v((tKNGN%W%%            
       'M8M88(Zd))///((|D\tDY\\KK-`/-i(=)KtNNN@W%%%@%[           
        !8%@KW5KKN4///s(\Pd!ROBY8/=2(/4ZdzKD%K%%%M8@%%           
         '%%%W%dGNtPK(c\/2\[Z(ttNYZ2NZW8W8K%%%%YKM%M%%.          
           *%%W%GW5@/%!e]_tZdY()v)ZXMZW%W%%%*5Y]K%ZK%8[          
            '*%%%%8%8WK\)[/ZmZ/Zi]!/M%%%%@f\ \Y/NNMK%%!          
              'VM%%%%W%WN5Z/Gt5/b)((cV@f`  - |cZbMKW%%|          
                 'V*M%%%WZ/ZG\t5((+)L\'-,,/  -)X(NWW%%           
                      `~`MZ/DZGNZG5(((\,    ,t\\Z)KW%@           
                         'M8K%8GN8\5(5///]i!v\K)85W%%f           
                           YWWKKKKWZ8G54X/GGMeK@WM8%@            
                            !M8%8%48WG@KWYbW%WWW%%%@             
                              VM%WKWK%8K%%8WWWW%%%@`             
                                ~*%%%%%%W%%%%%%%@~               
                                   ~*MM%%%%%%@f`                 
                                       '''''                     


// TODO - Comment this function

// If this comment is removed the program will blow up 

Next to a local variable that had to be declared just to pass a constant to a library function:

// This only exists because Scott doesn't know how to use const correctly

else
{
    //error situation
}

Get This hack!

On a line of assembler code, after pages of uncommented code.


// The following strings are meant to be funny.  Do not edit these strings
// unless you are funny, too.  If you don't know if you're funny, you're
// not funny.  If fewer than 2 people unrelated to you have told you that 
// you're funny, you're not funny.

It speaks volumes about our profession that when asked about the "best comment", we all answer with the worst comments we can find...


This is my favourite comment ever.

/// I intend to do this as shittily as possible because there are many better products that will totally blow this out of the water
/// and we don't have them so whatever

Later on in the file we have more fun like

/// sidestep a bug in WCF (that we can't send types across)
/// or, depending on how you look at, this issue is a Feature

And again later

if( where == null)//be nice

I found this when re-using a PHP class I wrote a fair amount of time ago. I still cant remember what went there and I still have found no use for it... I actually don't even remember me writing that comment; so I literally laughed out loud when I found it.

try
{               
    // Some database logic
}
catch (Exception $ex)
{
    // sure, it looks silly and I honestly cant remember what code used to go here... but i swear i will
    // find a use for this code.... eventually....
    throw $ex;
}

Well-written Lisp is one of the easiest to read languages and I love it. But poorly written Lisp can be a nightmare so much worse than bad Java, etc.

Here, we need to create a "group file" if there exist 3 variants of an original file named with the suffixes a, b and c. I had been trying to track down a strange bug where we were getting unnecessary group files...

  (let ((varianta (format nil "~aa" problem))
        (variantb (format nil "~ab" problem))
        (variantc (format nil "~ac" problem)))
    ;;if the A and B variants exist, create a group file
    ;;(why not just check for a? I don't know, this just feels right)
    (when (and (probe-file varianta)
               (probe-file variantb))
      ...)))

Bug: 1, Gut: 0.

Apparently it didn't occur to whoever wrote this that perhaps checking for all three variants would be a good idea. Of course, that was the bug I ended up tracking down a decade after this code was originally written (it predates the first SVN log).


# let's pretend we are free, for a while

Found this one in front of a class. What followed was a (naive) try to implement an ORM. I still don't understand why he wrote that.


here are 4, in no order:

// Father, forgive me, for I am sinning

// heaven help me

// horse string-length into correctitude 
(from a textbook)

// what, me worry?

aComment = 'this is not aComment' # this is aComment
class T(object):
    def f(this):
        this is not aComment

virgin = 0;     /* you're not a virgin anymore, sweety */

Get This hack!

On a line of assembler code, after pages of uncommented code.


/* Jeez, this is an ugly mess */

...comment from the X11R6 internals source code circa 1991.

//If the Current Record is Getting End Dated, We should not create New History Entry. 
//We Just need to Update the Previous History Entry
//If the History is already End Dated and the New Record is now removing End Date, Then 
//We should not update the Previous History End Date. 
//We Just need to Create the New History Record Only.
//Alright.. 
//Alright.... 
//Enough Comments. Code it. :-)

// If you're reading this, that means you have been put in charge of my previous project.
// I am so, so sorry for you. God speed.

#define SHIT_HAPPENED (BASE + 1)   /* generic shit happened */

catch (Ex as Exception)
{
     // oh crap, we should do something.
}

Nothing like an empty catch block to make one feel that the code is robust....


// TODO: Drive an ashen stake through the foul heart of this function.

And it was a foul function. I have nightmares about it to this day.


From one of our projects.
Somewhere at the end of one source file.

/*@                                    /\  /\
 * @                                  /  \/  \                        ----- |   | ----      |---\ |    | /--\  --- |   |  ---- /--\ /--\
 *  @                                /        --                        |   |   | |         |   / |    | |      |  |\  |  |    |    |
 *   \---\                          /           \                       |   |---| ----      |--/  |    |  \     |  | \ |  ----  \    \
 *    |   \------------------------/       /-\    \                     |   |   | |         |  \  |    |   -\   |  |  \|  |      -\   -\
 *    |                                    \-/     \                    |   |   | ----      |---/  \--/  \--/  --- |   \  ---- \--/ \--/
 *     \                                             ------O
 *      \                                                 /                 --- |   | ----  /--\        |--\   /--\   /--\
 *       |    |                    |    |                /                   |  |\  | |    |    |       |   | |    | |
 *       |    |                    |    |-----    -------                    |  | \ | ---- |    |       |   | |    | | /-\
 *       |    |\                  /|    |     \  WWWWWW/                     |  |  \| |    |    |       |   | |    | |    |
 *       |    | \                / |    |      \-------                     --- |   \ |     \--/        |--/   \--/   \--/
 *       |    |  \--------------/  |    |
 *      /     |                   /     |
 *      \      \                  \      \
 *       \-----/                   \-----/
 */

From Java 1.2 SwingUtilities:

doRun.run();  // ... "a doo run run".

// I am not sure if we need this, but too scared to delete. 

/**
 * Hexadecimal digit
 */
protected $version = -1;

// Hack-er-ama

// No women, no children... What movie???

A comment I added to a PHP CMS I was working on a while back.

if (/*you*/ $_GET['action']) { //celebrate

// now swap like a <explicative removed>

From /System/Library/Frameworks/AppKit.framework/Versions/C/Headers/NSTextView.h:

- (void)smartInsertForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace beforeString:(NSString **)beforeString afterString:(NSString **)afterString;
- (NSString *)smartInsertBeforeStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;
- (NSString *)smartInsertAfterStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;

/* Java note: The second and third methods are the primitives and are the 
methods exposed in Java.  The first method calls the other two.  All 
Objective-C code calls the first method.  In either Objective-C or Java any 
overriding should be done for the second and third methods, not the first 
method.  This will all work out correctly with the exception of existing code 
that overrides the first method.  Existing subclasses that do this will not 
have their implementations available to Java developers. Isn't Java wonderful? */

// woot, global var. I havent done this for a long time.

// Okay, let's do the loop, yeah come on baby let's do the loop
// and it goes like this ...

Found this recently in our code (we develop enterprise software):

// Instance of excel
Excel excel = this.CreateExcelInstance();
excel.Open(stream); // how to close it?!

Until that I was sure we're free of this "fun stuff" and we're doing it the right and ideologically correct way...


using namespace std;            // So sue me

%%return_median
hit_the_sweet_spot(Arg)->
.
.

/* Hammer Time! */

I have no idea why or whether he was wearing ripstop nylon parachute pants while writing the code


<cftry>
...code...
<cfcatch>
  <!--- Gobble --->
</cfcatch>
<cftry>

It's all over my companies code base. It's ColdFusion and it simply ignores errors.


For a memcache wrapper/handler interface pattern class I wrote, I had the following method implemented.

/**
*  Do not use, ever - left in place for testing purposes
*/
function  I_David_WillHuntYouDownAndHurtYou_Badly_IfIFindThisUsedAnyWhereInTheAppLibrary(){
...
}

This was basically a super nuke function to tell all the indvidual memcache services to completely flush themselves, and start over with the individual name space counters I used for keys ( ex .{_counter_key value}_.{_counter_key value} )

Another minor novella I wrote was for an automated downloader for a data vendor, detailing how much I hated this vendor and went to great lengths of postulating that their infrastructure's batch system was run by a gerbil, running on a wheel and after so many revolutions of the wheel the next queued task would be started. It was written over the course of 6 months of adding additional exception handling, estoric checks like ( if we got 768 Bytes of \s characters, that means the query to their DB timed out and the spaces are the result of empty failure print statements.


// This code sucks.

// barcore.cpp - MFC

//.....
HBRUSH CControlBar::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    LRESULT lResult;
    if (pWnd->SendChildNotifyLastMsg(&lResult))
        return (HBRUSH)lResult;     // eat it

//......

// Eat it - just like eat this.

// I dedicate all this code, all my work, to my wife, Darlene, who will 
// have to support me and our three children and the dog once it gets 
// released into the public.

Looking back at old code from classes is fun...

    cardDeck.push_back(*(new card((rank)r, (suit)s)));  // Push each card onto the deck
                                                        // Temp. objects are overrated

While going through some things, it makes me wish I left more comments at 4 AM when I was hacking together random code...


// long live COM'n'Roll
public enum StatusCode
{
        //success codes
        S_OK                                            = 1,
        S_NONE                                          = 2,
        S_SQL_OPERATIONS_LISTS_EMPTY                    = 3,

        //error codes
        E_NO_MATCHING_END_FOUND                         = -1,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_BEGINNING        = -2,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_END              = -3,
        E_FORWARD_AND_BACKWARD_OPS_COUNT_DO_NOT_MATCH   = -4,
        E_FORWARD_AND_BACKWARD_IDS_DO_NOT_MATCH         = -5,
        E_IDS_DO_NOT_MATCH                              = -6
}

'Mind boggling, gibberish version of a SQL statement, but it work's, so dont touch it

{
This is a gathering place for all unit tests.
Create a TUnitTestWrapper, then call "RunAllUnitTests".

This class will create an instance of each thing to be tested, and call each of
their unit tests.

It does not really do any testing on it's own; it just gives a common place from
which to call everyone else's tests.

This way, one day, we can automate our testing with each build. [Cue laughter]
}

A funny typo that was strangely appropriate:

assert(0); // should never shit this point


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

That one is by Donald Knuth.


//Maybe you should make anyone knows your code's purpose. 

// I dedicate all this code, all my work, to my wife, Darlene, who will 
// have to support me and our three children and the dog once it gets 
// released into the public.


$you = live("free") or die("hard");


Found in the main trigger code for transactions in an OLTP database:

-- This line negates the @inverseqty, which is the
-- negative of the @insertedquantity.  This works through the
-- magic of the trigger.  In fact, this code is a lot like
-- the bermuda triangle!
@negquantity = -1 * @inverseqty

// Caveat implementor

// I don't know why I need this, but it stops the people being upside-down

x = -x;

I see this one a lot:

// TODO make this work

From the sendmail config file. After pages and pages of what looked like simply line noise. I found this gem.

# insert this handy debugging line wherever you have problems
#R$*                $:$>99$1

Fix problem where Nulls don't work properly.  Stupid Microsoft!

Code converted Nulls to zero-length strings line by line in roundabout way because the stupid programmer did not understand what Nulls are and had never heard of the Nz() function.


This one was amusing for others but less so for me. I had inherited the code (which was ASP) from a developer who had himself inherited it. The first programmer had created some very hard to understand code. The second developer had added a comment as follows (names hidden to protect the not-so-innocent):

'This code was written by **************.
'I haven't a clue what it does. He hasn't a clue what it does.
'Nobody else has a clue what it does or how it does it.
'It is something to do with data but **** knows what.
'The ******* still works so please do not change this code,
'even though it is a complete pile of ****.

So why didn't I find it amusing? Well, it was ASP code for a customer's intranet.

...and it was the customer who highlighted the comment to me.

:-(


if(m_measures =/*=*/ --index)
{
    ....

//FIXME: fix this before the 1.0 release

they were on version 4


// Oh crap, i think i'm gonna yack

followed shortly thereafter by:

// TODO: end this lunacy

'NO COMMENT

.class {border:1px solid gold;} /* I pitty the fool */


// GK Experimental

(GK being the initials of the coder)

Used to indicate parts of code which are, indeed, kind of experimental. :)

A great flag to know that when you hit it during debugging you're probably busy for the upcoming few hours fixing the hack.. ;)


i tell a mentee to do at least SOME exception handling. This is what i get in return around every db call....

Catch (Exception e) {
    //eat it
}

A German comment in some source-code, translated by machine or very tired human + Google

; Rechnen ja ; have faith in yes

I guess the original meant "assume true here" ... but ever since I've taken it as a mantra for my life.


Mine fave was a variable name inside some of the business logic of a school project written in java.

int StupidJava = -1;

//
//3.4  JeK  My manager promised me a lap dance if I can fix this release
//3.5  JeK  Still waiting for that dance from my manager
//3.6  JeK  My manager got changed, the new manager is hairy, dont want the dance anymore
//3.7  Jek  Got that dance, yuck!
//

if(m_measures =/*=*/ --index)
{
    ....

Taken from the Quake III source, I stumbled across this in some random slashdot posting. Full source of the file can be found here. It's a particularly fast method of calculating an inverse square root. As for the best comment? It's a common one to be sure, but given that it's attached to the line that does the magic is what makes it great.

float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the fuck?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}

// This interface defines method signatures<br>
interface IWhatever { ... }

// I have to find a better job

I guess it got viral, I found the following in a daemon (Linux) that prevents the OOM killer from selecting it:

/*
 * Don't OOM me, bro!
 */

This was right after a mlockall() to prevent the process from swapping, commented:

/*
 * Don't swap me, bro!
 */

/*
* TODO: Remove this function

function remove($customer_id)
    {
        $this->Customer->remove($id);
    }

*/

This is a comment of mine which I found today while refactoring some code

if( year < 100 ): year += 2000 #lol, Y2K

When writing some Perl years ago, I added these comments at the top and bottom:

# <magic type="voodoo">

...

# </magic>

The next guy to look at it wasn't so hot at Perl, and spent a while searching documentation for what 'magic' and 'voodoo' did. Since then, I've tried to add more helpful comments...


//ha, you thought I was lazy didnt ya?!

def format_ticket_content(text, recursive = true)
  if text.is_a?(TicketNote)
    note = text
    text = note.content
  else
    note = nil
  end

  ## Safety pig has arrived!
  text = h(text)
  ##                               _
  ##  _._ _..._ .-',     _.._(`))
  ## '-. `     '  /-._.-'    ',/
  ##    )         \            '.
  ##   / _    _    |             \
  ##  |  a    a    /              |
  ##  \   .-.                     ;  
  ##   '-('' ).-'       ,'       ;
  ##      '-;           |      .'
  ##         \           \    /
  ##         | 7  .__  _.-\   \
  ##         | |  |  ``/  /`  /
  ##        /,_|  |   /,_/   /
  ##           /,_/      '`-'
  ## 

Dennis M Ritchie has a page about some of the ancient UNIX comments here


/* This is a replica of a horrible hack - many moons ago, the legacy PortfolioServer was modified to return cash trades in an "optionTrade" block, because the client side developer was too lazy to get their XPaths right. Their laziness echoes through the ages, and means we need a similar hack here...*/


// *** AAAAAHAHAHAH!!  What is this??

// This will save us ~0.5 sec for every user and please the machine spirits.

Before very long procedure :)


Actually saw this the other day, on some code that was written when there was a deadline rush.

//This was clearly written under duress

This is from an old IOCCC winning entry, I had to download the whole archive of winners -- a humongous 1.4 M -- and grep for several phrases I remembered wrong before finding it.

Syntactically this is probably not a comment. Or may be it is. I haven't figured it out. It definitely does not have comment delimiters, but it doesn't have String delimiters either.

C="Lint says "argument Manual isn't used."  What's that
mean?";

No prices for guessing the output from lint.

And for the curious, that entry is here.


switch(value)
{
   [...]
default:
   ASSERT(**true**); // if this is triggered, something really bad is happening.
}

// now that's compact!
list->insert(list->end(),**pitch)->IdxOfSample=(pitch->pos-Offset)*SamplingRate;

The original Doom had an engine with static walls that could not move; the result was that all doors opened vertically; nothing could ever move horizontally. I burst out laughing when, after the source code was released, I was looking through the code and saw this in the source file for handling doors, at the start of a big block of commented-out code:

// UNUSED
// Separate into p_slidoor.c?

#if 0           // ABANDONED TO THE MISTS OF TIME!!!
//
// EV_SlidingDoor : slide a door horizontally
// (animate midtexture, then set noblocking line)
//

I went through a sleep-deprived coding run and started only writing comments that were quotes from Fight Club.

Still trawling through the code years later I find a comment that makes me laugh. Most of them just random thoughts. I did however keep my comments to lines ratio pretty good!

// This shouldn't happen. The only way this can happen is if the
// <code>JFileChooser</code> has returned a <code>File</code> that doesn't exist
// on the system. If this happens we can't recover, and there is more than likely
// a rip in the space time continuum that the user is too distracted by to notice
// anything else.

 /**
   * This method leverages collective synergy to drive "outside of the box"
   * thinking and formulate key objectives into a win-win game plan with a
   * quality-driven approach that focuses on empowering key players to drive-up
   * their core competencies and increase expectations with an all-around
   * initiative to drive down the bottom-line. I really wanted to work the word
   * "mandrolic" in there, but that word always makes me want to punch myself in
   * the face.
   */
private void updateFileCountLabel() {

Best one so far:

"This code makes baby Jesus very sad!". 

It was refering an String iniciatilization like this:

String blankSpaces="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //100 whitespaces
                   "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //200 Whitespaces
                   ...
                   "                                        " //100 whitespaces

Well you get the idea.


#pragma region Crap that is kept for temporary reasons

    //  Huge chunk of commented code

#pragma endregion

 /**
   * Returns cookies according to the filters specified.
   * 
   * @return array  Cookies!  Nom nom nom nom nom.
   */
 public function data_getCookies($uid, $name) {

Somewhere from the facebook api.


We had a group project to create a Connect 4 AI using Min-Max trees. In our move-scoring function, we had it calculate a score for the board, and above that block of code there was this comment:

// This is kind of almost useless

But it gets better. Our instructor gave us some sample code from a crude AI he had made, and he left a great comment:

// We also add/subtract some points based on what's going on, on the bottom
// row. (I think this is retarded, but apparently when I coded this up 
// back in 1999 I didn't.)

/**
 * If you don't understand this code, you should be flipping burgers instead.
 */

All bugs added by David S. Miller


// Singleton object. Leave $me alone.
private static $me;

else
{
    // rien, c'est parfait.
}

Just found this one in some of our PHP code

$s=2; // chicken and bacon wrap for lunch

How useful, luckily $s was self explanatory


I found this when re-using a PHP class I wrote a fair amount of time ago. I still cant remember what went there and I still have found no use for it... I actually don't even remember me writing that comment; so I literally laughed out loud when I found it.

try
{               
    // Some database logic
}
catch (Exception $ex)
{
    // sure, it looks silly and I honestly cant remember what code used to go here... but i swear i will
    // find a use for this code.... eventually....
    throw $ex;
}

v.bpc     := v.pc;  -- Remember to jump back
v.baccu   := accu;  -- Yo dawg, heard you like runing instructions
                    -- so I took backup of your accu so you can run
                    -- instructions while you run instructions.
v.flags.i := false; -- No more interupts

THIS PROGRAM HAS CODE THAT DOES NOT MEET STANDARDS      

That comment is in nearly every program we have here....


I just checked this in the other day...

/// <STERNLY-WORDED-WARNING>
/// Pay attention to this or I will hunt you down.
/// ...
/// </STERNLY-WORDED-WARNING>

Where ("..." == "proprietary stuff that I can't post"). I just liked my STERNLY-WORDED-WARNING element.


From Java 1.2 SwingUtilities:

doRun.run();  // ... "a doo run run".

When writing some Perl years ago, I added these comments at the top and bottom:

# <magic type="voodoo">

...

# </magic>

The next guy to look at it wasn't so hot at Perl, and spent a while searching documentation for what 'magic' and 'voodoo' did. Since then, I've tried to add more helpful comments...


From: https://github.com/zepouet/Xee-xCode-4.5/blob/master/XeePhotoshopLoader.m#L108

// At this point, I'd like to take a moment to speak to you about the Adobe PSD
// format. PSD is not a good format. PSD is not even a bad format. Calling it
// such would be an insult to other bad formats, such as PCX or JPEG. No, PSD
// is an abysmal format. Having worked on this code for several weeks now, my
// hate for PSD has grown to a raging fire that burns with the fierce passion
// of a million suns.
//
// If there are two different ways of doing something, PSD will do both, in
// different places. It will then make up three more ways no sane human would
// think of, and do those too. PSD makes inconsistency an art form. Why, for
// instance, did it suddenly decide that *these* particular chunks should be
// aligned to four bytes, and that this alignement should *not* be included in
// the size? Other chunks in other places are either unaligned, or aligned with
// the alignment included in the size. Here, though, it is not included. Either
// one of these three behaviours would be fine. A sane format would pick one.
// PSD, of course, uses all three, and more.
//
// Trying to get data out of a PSD file is like trying to find something in the
// attic of your eccentric old uncle who died in a freak freshwater shark
// attack on his 58th birthday. That last detail may not be important for the
// purposes of the simile, but at this point I am spending a lot of time
// imagining amusing fates for the people responsible for this Rube Goldberg of
// a file format.
//
// Earlier, I tried to get a hold of the latest specs for the PSD file format.
// To do this, I had to apply to them for permission to apply to them to have
// them consider sending me this sacred tome. This would have involved faxing
// them a copy of some document or other, probably signed in blood. I can only
// imagine that they make this process so difficult because they are intensely
// ashamed of having created this abomination. I was naturally not gullible
// enough to go through with this procedure, but if I had done so, I would have
// printed out every single page of the spec, and set them all on fire. Were it
// within my power, I would gather every single copy of those specs, and launch
// them on a spaceship directly into the sun.
//
// PSD is not my favourite file format.

/* logic */
#ifndef TRUE
# define TRUE 1
#endif /* TRUE */
#ifndef FALSE
# define FALSE 0
#endif /* FALSE */
#define EOF_OK TRUE
#define EOF_NOT_OK FALSE

and the rest of the glorious mkentry.c at the IOCCC page. I can't keep laughing every time I read through this source.


// error codes
#define ERROR_SUCESS 0
#define ERROR_SUCCESS_IS_MISSPELLED 1

No other error codes defined.


I think I had something of this sort:


if (case1) { // trivial
...
}
else { // we are screwed
 /* fill in later */
}

ok, so I might have used a stronger word than screwed


// I love the smell of dirty XML in the morning
xml = xml.Replace("xmlns=\"urn:bsd.orion/inventory\"", "");

//Not a bug, parameter position can change..., if you think this is wrong, you are in fact wrong.

# To understand recursion, see the bottom of this file 

At the bottom of the file:

# To understand recursion, see the top of this file

While debugging someone else JavaScript I've seen the following comment:

// Notice: I feel so dirty doing this, but it's the only way to make it cross browser.

But while reading one post of Scott Hanselmen I came across the following quote that goes very well with the comments I found inside the code:

Every line of code you write that you feel gross about will ultimately come back to haunt you. Therefore, avoid writing code that makes you feel dirty.

That's funny :)


This is one from my own code, but it's still really funny, and I figure I might as well put it up because it's in public SVN.

// These were orginally up and down. When it was clear the names were
// inapplicable, they were renamed to retain the joke.
// Sorry if you were hoping for useful variable names.
quantum strange, charm;

Exhibit a:

return 0; // Happy ending

Exhibit B:

int32_t Interpolate1DSignal(
  Array1D<float64>::Handle hfInputSamples,         // samples to be interpolated
  Array1D<float64>::Handle hfInterpolationFilter,  // polyphase filter coefficients,
  int32_t iFilterInterpolationFactor,              // # of "rows" in polyphase filter
  int32_t iFilterLength,                           // Length of each row in filter
  float64 fInterpolationFactor,                    // Factor to interpolate the
                                                   // signal by
  float64 fTimingOffset,                           // Offset into the signal (units   
                                                   // of samples)
  Array1D<float64>::Handle hfOutputSamples         // left as an exercise for the reader
);

/* This is O(scary), but seems quick enough in practice. */ 

followed by four nested for-loops


/*************************** Drag And Drop Section - Start (you should be me to mess with this section)*********************************************/

# let's pretend we are free, for a while

Found this one in front of a class. What followed was a (naive) try to implement an ORM. I still don't understand why he wrote that.


For one project we had pwlib as a dependency, and at that time it's FreeBSD port was somewhat screwed so I had to build it manually from source. It didn't work out right away, and I had to look into the code; there was some complicated class hierarchy with parts of code generated by macros and its parent calss declaration started with

// The root of all evil ... umm classes

This whole function is pretty great (from the Linux sunhme.c driver, for the network card nicknamed the Happy Meal by Sun. Because the card that came before that was the "Big MAC". Get it? Get it?)

static void happy_meal_tcvr_write(struct happy_meal *hp,
                              void __iomem *tregs, int reg,
                              unsigned short value)
{
    int tries = TCVR_WRITE_TRIES;

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

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

    /* Would you like fries with that? */
    hme_write32(hp, tregs + TCVR_FRAME,
                (FRAME_WRITE | (hp->paddr << 23) |
                 ((reg & 0xff) << 18) | (value & 0xffff)));
    while (!(hme_read32(hp, tregs + TCVR_FRAME) & 0x10000) && --tries)
            udelay(20);

    /* Anything else? */
    if (!tries)
            printk(KERN_ERR "happy meal: Aieee, transceiver MIF write bolixed\n");

    /* Fifty-two cents is your change, have a nice day. */

}


// Added because boss changed his mind : 20020111,20020501,20020820, ...
// Commented out because boss changed his mind : 20020201,20020614,20020908, ...

In an ETL script between a mostly hacked RPG database and an SQL Server one. I had something like 10 or 20 occurences of this comment...


'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
'
'  NOTE: DON'T SCREW WITH THIS CODE UNLESS YOU REALLY UNDERSTAND IT!
'
'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

When writing some Perl years ago, I added these comments at the top and bottom:

# <magic type="voodoo">

...

# </magic>

The next guy to look at it wasn't so hot at Perl, and spent a while searching documentation for what 'magic' and 'voodoo' did. Since then, I've tried to add more helpful comments...


long john; // silver

Simple but effective comment, before a less than safe hack in some C++ code

// yikes

For a memcache wrapper/handler interface pattern class I wrote, I had the following method implemented.

/**
*  Do not use, ever - left in place for testing purposes
*/
function  I_David_WillHuntYouDownAndHurtYou_Badly_IfIFindThisUsedAnyWhereInTheAppLibrary(){
...
}

This was basically a super nuke function to tell all the indvidual memcache services to completely flush themselves, and start over with the individual name space counters I used for keys ( ex .{_counter_key value}_.{_counter_key value} )

Another minor novella I wrote was for an automated downloader for a data vendor, detailing how much I hated this vendor and went to great lengths of postulating that their infrastructure's batch system was run by a gerbil, running on a wheel and after so many revolutions of the wheel the next queued task would be started. It was written over the course of 6 months of adding additional exception handling, estoric checks like ( if we got 768 Bytes of \s characters, that means the query to their DB timed out and the spaces are the result of empty failure print statements.


An HORRIBLE patch for a decode (Translation by italian language):

/**
*@return the value 
*@param key: the id of the list of instruments
*@PS this function is a violation of all the laws of the 
*software engineering, 
*commons sense, highway code 
*and ONU decision about the coding.
That sh*t...
*/

In a large investment bank that required all application outages be logged and commented I saw

Without a crash 

Or mighty bang 

The sync disk 

Did it's process hang

From a unit testing class in C#:

#region quis custodiet ipsos custodes?

[Fact]
public void TestPositive()
{
    Assert.Equal(4, 2 + 2);
}

[Fact]
public void TestNegative()
{
    Assert.Equal(5, 2 + 2);
}

#endregion

Case 1:
   ...
   break;
   ...
//I don't want do do this but [my coworker] says it's part of the code standard
default:
   break;

Actually saw this the other day, on some code that was written when there was a deadline rush.

//This was clearly written under duress

That one is well-known but I like it (in sys/ufs/ufs_vnops.c):

/*
 * A virgin directory (no blushing please).
 */

in the FreeBSD kernel source tree (and even before, back into 4.xBSD)


managed to insert this bad pun into our code

for (bo_thans = 0 ; bo_thans < MAX ; bo_thans++)
{
    if(rs == thing[bo_thans])
    {
       found = true;
    }
}

if(!found)
{
   /* Failed to find rs with bo_thans */
   ...
}

Mine fave was a variable name inside some of the business logic of a school project written in java.

int StupidJava = -1;

Tweet tweet = (Tweet) tweets.get(i); // Poetic.

Try typing your favourite profanity into google code search, it whiles away many a dull hour. Some of my favourite examples:

/* These magic numbers are fucking stupid. */

/* Dear free software world, do you NOW see we are fucking
   things up?! This is insane! */

/* We will NOT put a fucking timestamp in the header here. Every
   time you put it back, I will come in and take it out again. */

# However, this only works if there are MULTIPLE checkboxes!
# The fucking JS DOM *changes* based on one or multiple boxes!?!?!
# Damn damn damn I hate the JavaScript DOM so damn much!!!!!!

/* TODO: this is obviously not right ... this whole fucking module
   sucks anyway */

/* FIXME: please god, when will the hurting stop? Thus function is so
   fucking broken it's not even funny. */

and my personal favourite

 # code below replaces code above - any problems?
 # yeah, it doesn't fucking work.

#define TRUE FALSE //Happy debugging suckers


(A bunch of code that's really weird looking)  //Kludge.

I don't remember exactly, but the idea was something like this:

Person p = new Person("John", "Doe", "male");
Collection women = new ArrayList();
women.insert(p.getTail());

It's dirty code ;)


/// <summary>
/// The possible outcomes of an update operation (save or delete)
/// </summary>
public enum UpdateResult
{

    /// <summary>
    /// Updated successfully
    /// </summary>
    Success = 0,

    /// <summary>
    /// Updated successfully
    /// </summary>
    Failed = 1
}

// For the sins I am about to commit, may James Gosling forgive me

Somebody complained that the "best" comment was bringing up the worst comments. IMHO, they're funnier, and so "better", but here's the honest best comment I've ever read:

/*
Major subtleties ahead:  Most hash schemes depend on having a "good" hash
function, in the sense of simulating randomness.  Python doesn't:  its most
important hash functions (for strings and ints) are very regular in common
cases:

>>> map(hash, (0, 1, 2, 3))
[0, 1, 2, 3]
>>> map(hash, ("namea", "nameb", "namec", "named"))
[-1658398457, -1658398460, -1658398459, -1658398462]
>>>

This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints.
The same is approximately true when keys are "consecutive" strings.  So this
gives better-than-random behavior in common cases, and that's very desirable.

OTOH, when collisions occur, the tendency to fill contiguous slices of the
hash table makes a good collision resolution strategy crucial.  Taking only
the last i bits of the hash code is also vulnerable:  for example, consider
[i << 16 for i in range(20000)] as a set of keys.  Since ints are their own
hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
hash code are all 0:  they *all* map to the same table index.

But catering to unusual cases should not slow the usual ones, so we just take
the last i bits anyway.  It's up to collision resolution to do the rest.  If
we *usually* find the key we're looking for on the first try (and, it turns
out, we usually do -- the table load factor is kept under 2/3, so the odds
are solidly in our favor), then it makes best sense to keep the initial index
computation dirt cheap.

The first half of collision resolution is to visit table indices via this
recurrence:

    j = ((5*j) + 1) mod 2**i

For any initial j in range(2**i), repeating that 2**i times generates each
int in range(2**i) exactly once (see any text on random-number generation for
proof).  By itself, this doesn't help much:  like linear probing (setting
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
order.  This would be bad, except that's not the only thing we do, and it's
actually *good* in the common cases where hash keys are consecutive.  In an
example that's really too small to make this entirely clear, for a table of
size 2**3 the order of indices is:

    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]

If two things come in at index 5, the first place we look after is index 2,
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
Linear probing is deadly in this case because there the fixed probe order
is the *same* as the order consecutive keys are likely to arrive.  But it's
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
and certain that consecutive hash codes do not.

The other half of the strategy is to get the other bits of the hash code
into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
full hash code, and changing the recurrence to:

    j = (5*j) + 1 + perturb;
    perturb >>= PERTURB_SHIFT;
    use j % 2**i as the next table index;

Now the probe sequence depends (eventually) on every bit in the hash code,
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
because it quickly magnifies small differences in the bits that didn't affect
the initial index.  Note that because perturb is unsigned, if the recurrence
is executed often enough perturb eventually becomes and remains 0.  At that
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
that's certain to find an empty slot eventually (since it generates every int
in range(2**i), and we make sure there's always at least one empty slot).

Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
small so that the high bits of the hash code continue to affect the probe
sequence across iterations; but you want it large so that in really bad cases
the high-order hash bits have an effect on early iterations.  5 was "the
best" in minimizing total collisions across experiments Tim Peters ran (on
both normal and pathological cases), but 4 and 6 weren't significantly worse.

Historical:  Reimer Behrends contributed the idea of using a polynomial-based
approach, using repeated multiplication by x in GF(2**n) where an irreducible
polynomial for each table size was chosen such that x was a primitive root.
Christian Tismer later extended that to use division by x instead, as an
efficient way to get the high bits of the hash code into play.  This scheme
also gave excellent collision statistics, but was more expensive:  two
if-tests were required inside the loop; computing "the next" index took about
the same number of operations but without as much potential parallelism
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
above, and then shifting perturb can be done while the table index is being
masked); and the dictobject struct required a member to hold the table's
polynomial.  In Tim's experiments the current scheme ran faster, produced
equally good collision statistics, needed less code & used less memory.

Theoretical Python 2.5 headache:  hash codes are only C "long", but
sizeof(Py_ssize_t) > sizeof(long) may be possible.  In that case, and if a
dict is genuinely huge, then only the slots directly reachable via indexing
by a C long can be the first slot in a probe sequence.  The probe sequence
will still eventually reach every slot in the table, but the collision rate
on initial probes may be much higher than this scheme was designed for.
Getting a hash code as fat as Py_ssize_t is the only real cure.  But in
practice, this probably won't make a lick of difference for many years (at
which point everyone will have terabytes of RAM on 64-bit boxes).
*/

At the top of a header file:

/* Project : XYZ (Please somebody shoot me!)
 *
 * File : $Id: defs.h,v 1.1 $
 *
 * Purpose : Create havoc rather than peace among many nations
 *
 * History : Back-ported changes that were not in CVS.  Please somebody,
 *  shoot us and put us all out of our misery.
 */

The "XYZ project" (name changed) was a seven-year ordeal. That last comment was written by the one stalwart soul who was involved from the very beginning through to the end.


REM Don't delete this print statement ****** will die

The process in question was a service in some legacy code


Sanitized:

//Forward declarations:

class X {}; // TODO: Remove {}  ! When we get X defined....

//Mr. Compiler, please do not read this.

/* Halley's comment */

// This interface defines method signatures<br>
interface IWhatever { ... }

// this is really complicated

with no other comments


Production source code:

// Remove this if you wanna be fired

// haack, phil haack

and:

/* hack, hack, hack, hack, hack hack, hack, hack
 * hackity hack, oh wonderful hacks
 * wonderful hacks, oh wonderful hack, hack, hack
 * hack hack hack... and spam 
 */

EDIT: Just found this in some of my code (the project wishes to remain anonymous):

// yikes, we need to:
/*
 *       o
 *      -|-     < US CROSSING PLATFORM
 *       |\ 
 ************************************************
 *       |          ^ PLATFORM           |
 *       |                           T   |
 *       |                      TROLL^   |
 */
// right now:
/*
 *   o ./_  | 
 *  -|-[]\  |  (_'_) () (\) | ) \|/ (S) < WALL
 *   |\     |    ^ FRIENDLY MESSAGE FROM YOUR FRIENDS AT MICROSOFT
 *  ***********************************************
 *        | ^PLATFORM                       |
 *      ^ SPRAY CAN (IN HAND)
 */
public static class DefaultFonts
{
    public static string SansSerifPath
    {
        get { return @"C:\Windows\Fonts\arial.ttf"; }
    }
    public static string SerifPath
    {
        get { return @"C:\Windows\Fonts\times.ttf"; }
    }
    public static string MonospacePath
    {
        get { return @"C:\Windows\Fonts\courier.ttf"; }
    }
}

How I love puns.


double penetration; // ouch

This one was amusing for others but less so for me. I had inherited the code (which was ASP) from a developer who had himself inherited it. The first programmer had created some very hard to understand code. The second developer had added a comment as follows (names hidden to protect the not-so-innocent):

'This code was written by **************.
'I haven't a clue what it does. He hasn't a clue what it does.
'Nobody else has a clue what it does or how it does it.
'It is something to do with data but **** knows what.
'The ******* still works so please do not change this code,
'even though it is a complete pile of ****.

So why didn't I find it amusing? Well, it was ASP code for a customer's intranet.

...and it was the customer who highlighted the comment to me.

:-(


// This part is more difficult

At the top of a method.

That was about 5 lines long.

And not very difficult.

It was the only comment.

In the entire application.


Found in the JUnit API:

/**
 * ...as the moon sets over the early morning Merlin, Oregon
 * mountains, our intrepid adventurers type...
 */
public Test createTest(Class theClass, String name) {
    ...
}


Just found this one in some of our PHP code

$s=2; // chicken and bacon wrap for lunch

How useful, luckily $s was self explanatory


here are 4, in no order:

// Father, forgive me, for I am sinning

// heaven help me

// horse string-length into correctitude 
(from a textbook)

// what, me worry?

I see this one a lot:

// TODO make this work

options.BatchSize = 300; //Madness? THIS IS SPARTA!

/* Look not upon this file lest your eyes be burnt from your head. */

What can I say? I was an intern and the summer was almost over. I was, shall we say, lacking in serious commitment to my documentation responsibilities.


"This will never happen".

Famous last words my friend...


A classic case of why you shouldn't off shore your software development:

public class Contact
{
    //...    

    /// <summary>
    /// Gets or sets the name of the first.
    /// </summary>
    /// <value>The name of the first.</value>
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
}

switch(value)
{
   [...]
default:
   ASSERT(**true**); // if this is triggered, something really bad is happening.
}

// THE LOOP THAT DO EVERYTHING!!!!!!!

catch
{     
    // you’re fucked
    // write out the file somewhere and start screaming “Connection down! Connection down!”
}

//MailBody builders for two outgoing messages
StringBuilder hanz = new StringBuilder();
StringBuilder franz = new StringBuilder();

I still chuckle a little when I read that one...


Our DBA found this in the middle of a 3000 line stored procedure written by a third party.

/* IF DOLPHINS ARE SO SMART, HOW COME THEY LIVE IN IGLOOS? */

try
{
...
}
catch(Exception ex)
{
//if this happens the world is going to end...
}

now guess what happened...


try {
  dataSource.close();
}
catch (SQLException ex) {
  // Do nothing, since we're going to trash this anyway
}

Of course, this sort of thing is actually a wtf in JDBC (or at least Oracle's JDBC driver) as it can throw SQLExceptions when closing a connection...


// All this code is yours, except gedit()...attempt no modifications there.

// Caveat implementor

at the end of a rather long and convoluted set of while loops and if blocks, the developer in question inserted this final comment:

else
{
    // wobbly wilson said this would *never* happen!!
}

a laconic mixture of wit and sarcasm :)


Linux Comments

There are heaps of good ones here ...

These are all comments in linux

http://lwn.net/1998/1015/a/f-word.html

My Favourites:

./arch/sparc/kernel/ptrace.c
/* Fuck me gently with a chainsaw... */

./drivers/scsi/qlogicpti.h
/* Am I fucking pedantic or what? */

// This procedure is really good for your dorsolateral prefrontal cortex.

For those of you who are, for some peculiar reason, unaware of the DPC, it's the part of your brain that lights-up when you're deeply engaged in learning something new.


Fresh out of college, I was eager to get my hands dirty. My first task was... "comment this code for me".

Fucker.

After awhile I got bored with it...

// this function doesn't actually calculated the profit, like it says --it really signals the mothership orbiting saturn that the planet is ripe for takeover

[later]

// I don't think anyone is going to read this

[various permutations on that last one]

on leaving my last job I embedded some ascii art into the source...


                                      ,_-=(!7(7/zs_.             
                                   .='  ' .`/,/!(=)Zm.           
                     .._,,._..  ,-`- `,\ ` -` -`\\7//WW.         
                ,v=~/.-,-\- -!|V-s.)iT-|s|\-.'   `///mK%.        
              v!`i!-.e]-g`bT/i(/[=.Z/m)K(YNYi..   /-]i44M.       
            v`/,`|v]-DvLcfZ/eV/iDLN\D/ZK@%8W[Z..   `/d!Z8m       
           //,c\(2(X/NYNY8]ZZ/bZd\()/\7WY%WKKW)   -'|(][%4.      
         ,\\i\c(e)WX@WKKZKDKWMZ8(b5/ZK8]Z7%ffVM,   -.Y!bNMi      
         /-iit5N)KWG%%8%%%%W8%ZWM(8YZvD)XN(@.  [   \]!/GXW[      
        / ))G8\NMN%W%%%%%%%%%%8KK@WZKYK*ZG5KMi,-   vi[NZGM[      
       i\!(44Y8K%8%%%**~YZYZ@%%%%%4KWZ/PKN)ZDZ7   c=//WZK%!      
      ,\v\YtMZW8W%%f`,`.t/bNZZK%%W%%ZXb*K(K5DZ   -c\\/KM48       
      -|c5PbM4DDW%f  v./c\[tMY8W%PMW%D@KW)Gbf   -/(=ZZKM8[       
      2(N8YXWK85@K   -'c|K4/KKK%@  V%@@WD8e~  .//ct)8ZK%8`       
      =)b%]Nd)@KM[  !'\cG!iWYK%%|   !M@KZf    -c\))ZDKW%`        
      YYKWZGNM4/Pb  '-VscP4]b@W%     'Mf`   -L\///KM(%W!         
      !KKW4ZK/W7)Z. '/cttbY)DKW%     -`  .',\v)K(5KW%%f          
      'W)KWKZZg)Z2/,!/L(-DYYb54%  ,,`, -\-/v(((KK5WW%f           
       \M4NDDKZZ(e!/\7vNTtZd)8\Mi!\-,-/i-v((tKNGN%W%%            
       'M8M88(Zd))///((|D\tDY\\KK-`/-i(=)KtNNN@W%%%@%[           
        !8%@KW5KKN4///s(\Pd!ROBY8/=2(/4ZdzKD%K%%%M8@%%           
         '%%%W%dGNtPK(c\/2\[Z(ttNYZ2NZW8W8K%%%%YKM%M%%.          
           *%%W%GW5@/%!e]_tZdY()v)ZXMZW%W%%%*5Y]K%ZK%8[          
            '*%%%%8%8WK\)[/ZmZ/Zi]!/M%%%%@f\ \Y/NNMK%%!          
              'VM%%%%W%WN5Z/Gt5/b)((cV@f`  - |cZbMKW%%|          
                 'V*M%%%WZ/ZG\t5((+)L\'-,,/  -)X(NWW%%           
                      `~`MZ/DZGNZG5(((\,    ,t\\Z)KW%@           
                         'M8K%8GN8\5(5///]i!v\K)85W%%f           
                           YWWKKKKWZ8G54X/GGMeK@WM8%@            
                            !M8%8%48WG@KWYbW%WWW%%%@             
                              VM%WKWK%8K%%8WWWW%%%@`             
                                ~*%%%%%%W%%%%%%%@~               
                                   ~*MM%%%%%%@f`                 
                                       '''''                     


const int TEN=10; // As if the value of 10 will fluctuate... 

My favorite comment of all time was used by a gay friend of mine. He liked to mark all of his TODO comments in VB.NET as

'TODO: Matt Damon

Sometimes additional information was provided but not usually.


Some of the very few comments in 5000+ lines of code in one file
I actually has an argument with the coder who defended his coding style...
No comment!
And there were no comments;-) (or very few)
Sadly this is production code.

offset=1;
for (i=0;i<=len;i++)
    {
    if ((i!=0)&&(i<len)) //-3
        {
        switch(mess[i])
            {
            case ETX:
            case ETB:
            case DLE:
                buf[offset]=DLE;
                offset++;
                break;
            }
        }
    buf[offset]=mess[i];
    offset++;
    }

I love the switch!

for (n=0;n<offset;n++)
{
    Sleep(TR);  //Modif A
    Sleep(T);//
    FWriteFile(hCom,buf+n,1,&dwMot,NULL);
    if (ECHO)
        FReadFile(hCom,tab,1,&dwMot,NULL);
}

and no, there are no comments explaining what "modif A" is in the header.

if (GetFileSize(hSlotFile,NULL)==3600)   //5*720

and what's 720?


I saw this comment on someone's code:

// This comment is self explanatory.

I guess he meant to say 'variable' but the mistake made one funny comment... Think of the circular logic here, and the futility of writing it.


I don't remember exactly, but the idea was something like this:

Person p = new Person("John", "Doe", "male");
Collection women = new ArrayList();
women.insert(p.getTail());

It's dirty code ;)


Near the top of a unit:

// Oh what a tangled web we weave
// When first we practice to deceive
// ASTA

at the end of a rather long and convoluted set of while loops and if blocks, the developer in question inserted this final comment:

else
{
    // wobbly wilson said this would *never* happen!!
}

a laconic mixture of wit and sarcasm :)


// TODO: Drive an ashen stake through the foul heart of this function.

And it was a foul function. I have nightmares about it to this day.


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

That one is by Donald Knuth.


// I'm sorry.

/* logic */
#ifndef TRUE
# define TRUE 1
#endif /* TRUE */
#ifndef FALSE
# define FALSE 0
#endif /* FALSE */
#define EOF_OK TRUE
#define EOF_NOT_OK FALSE

and the rest of the glorious mkentry.c at the IOCCC page. I can't keep laughing every time I read through this source.


// Iced odnako
bool Iced{get;set;}

// set break point here - you'll never reach it

A large project I worked on used StyleCop and FXCop in the automated build with rules to prevent people checking in code with uncommented fields, methods, properties etc., etc.

Someone got so pissed off with having to add comments like "Gets or sets the full name." to self-documenting properties like FullName, that they went to the effort of writing a macro to get around the rules.

The macro inserted XML summary tags for methods, properties etc. with a single non-displaying Unicode character as the tag content which would fool the build rules whilst simultaneously striking his minor blow against mindless insistence on commenting stuff for the sake of it...

...at least until they introduced another rule to check for Unicode characters in comments.


At the top of a header file:

/* Project : XYZ (Please somebody shoot me!)
 *
 * File : $Id: defs.h,v 1.1 $
 *
 * Purpose : Create havoc rather than peace among many nations
 *
 * History : Back-ported changes that were not in CVS.  Please somebody,
 *  shoot us and put us all out of our misery.
 */

The "XYZ project" (name changed) was a seven-year ordeal. That last comment was written by the one stalwart soul who was involved from the very beginning through to the end.


This one i found it in the package "twisted" for Python 2.5 (the file is tcp.py at line 371)

# Limit length of buffer to try to send, because some OSes are too
# stupid to do so themselves (ahem windows)
return self.socket.send(buffer(data, 0, self.SEND_LIMIT))

From Apache Xalan source code:

/**
 * As Gregor Samsa awoke one morning from uneasy dreams he found himself
 * transformed in his bed into a gigantic insect. He was lying on his hard,
 * as it were armour plated, back, and if he lifted his head a little he
 * could see his big, brown belly divided into stiff, arched segments, on
 * top of which the bed quilt could hardly keep in position and was about
 * to slide off completely. His numerous legs, which were pitifully thin
 * compared to the rest of his bulk, waved helplessly before his eyes.
 * "What has happened to me?", he thought. It was no dream....
 */
protected static String DEFAULT_TRANSLET_NAME = "GregorSamsa";

Further reading on The Daily WTF.


From a legacy Perl CGI script:

# This is convoluted and evil, sorry.

Taken from the Quake III source, I stumbled across this in some random slashdot posting. Full source of the file can be found here. It's a particularly fast method of calculating an inverse square root. As for the best comment? It's a common one to be sure, but given that it's attached to the line that does the magic is what makes it great.

float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the fuck?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}

// Hard to explain

It ended up being broken, too. No wonder it was hard to explain


// No women, no children... What movie???

// good luck!

// TODO: Implement this function!

// This code was written by a genius so don't try to understand it with
// your tiny little brain.

// nobody read comments!

# absolutely foul heuristic code.
# ..it's dirty, but you want it.

and:

# VERY USEFUL DEBUGGING AID, for when the above all goes pearshaped:

    /* Mark: If there's one thing you learn from this code, it is this...
   Never, ever fly Air France.  Their customer service is absolutely
   the worst.  I've never heard the words "That's not my problem" as 
   many times as I have from their staff -- It should, without doubt
   be their corporate motto if it isn't already.  Don't bother giving 
   them business because you're just a pain in their side and they
   will be sure to let you know the first time you speak to them.

   If you ever want to make me happy just tell me that you, too, will
   never fly Air France again either (in spite of their excellent
   cuisine). 

   Update by oej: The merger with KLM has transferred this
   behaviour to KLM as well. 
   Don't bother giving them business either...

   Only if you want to travel randomly without luggage, you
   might pick either of them.
   */

/////////////////////////////////////// this is a well commented line

Spelunking through the Hardware Abstraction Layer while working for a certain Finnish Mobile Network Equipment Manufacturer I found 100+ occurrences of the Finnish word "puukko".

A 'puukko' is an all purpose knife that every Finn has in their toolbox or around the house. It is used for everything from pealing potatoes to performing computer repairs (my observations). I believe in this context it is the Finnish equivalent of the word 'Hack'.

My Finnish colleagues denied this and said it meant something more like 'surgical procedure/intervention'... and I almost believed them until I found the comment:

/* Perkele ISO Puukko! */ -> Fucking Big Hack!

// Catching exceptions is for communists

From Mike Duncan's page on SQLite.


-- Comment this later

That was line 2 of a 4000+ line PL/SQL procedure. And the only comment. 4 years after that procedure was developed, later still hadn't come...


public static final void attachListener(Object listener) {

/* ======================= */

// This does nothing, continue searching

/* ======================= */

...

painful with listeners!


i just noticed myself writing this

// not brilliant solution, but fair enough heh.

Back when I worked for Reuters there was a comment in one of our feed handlers that made some people think the Almighty was helping us out...

// Jesus told me to skip to the end of the message here

We found out later that there was a Latin-American contact named Jesus (HeyZus).


Some of the very few comments in 5000+ lines of code in one file
I actually has an argument with the coder who defended his coding style...
No comment!
And there were no comments;-) (or very few)
Sadly this is production code.

offset=1;
for (i=0;i<=len;i++)
    {
    if ((i!=0)&&(i<len)) //-3
        {
        switch(mess[i])
            {
            case ETX:
            case ETB:
            case DLE:
                buf[offset]=DLE;
                offset++;
                break;
            }
        }
    buf[offset]=mess[i];
    offset++;
    }

I love the switch!

for (n=0;n<offset;n++)
{
    Sleep(TR);  //Modif A
    Sleep(T);//
    FWriteFile(hCom,buf+n,1,&dwMot,NULL);
    if (ECHO)
        FReadFile(hCom,tab,1,&dwMot,NULL);
}

and no, there are no comments explaining what "modif A" is in the header.

if (GetFileSize(hSlotFile,NULL)==3600)   //5*720

and what's 720?


i++; // increment variable i

//Mr. Compiler, please do not read this.

I saw this once:

//this used to be a comment

I always liked what Paul DiLascia wrote in his file headers:

// If this code works, it was written by Paul DiLascia. If not, I don't know
// who wrote it

This is so much nicer than the scary legal notices and disclaimers you see in many comment headers. From SQLite.

/*
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
*/

Q: "What is the best comment in source code you have ever encountered?"

A: Easy - the one that helped me solve whatever problem I was having at the time, and there are lots of those!

Second best are those that help guide new development from avoiding known pitfalls.


If you have reached this part in the code, then this program sucks.


This one, from Xee, an image browser.

    // At this point, I'd like to take a moment to speak to you about the Adobe PSD format.
    // PSD is not a good format. PSD is not even a bad format. Calling it such would be an
    // insult to other bad formats, such as PCX or JPEG. No, PSD is an abysmal format. Having
    // worked on this code for several weeks now, my hate for PSD has grown to a raging fire
    // that burns with the fierce passion of a million suns.
    // If there are two different ways of doing something, PSD will do both, in different
    // places. It will then make up three more ways no sane human would think of, and do those
    // too. PSD makes inconsistency an art form. Why, for instance, did it suddenly decide
    // that *these* particular chunks should be aligned to four bytes, and that this alignement
    // should *not* be included in the size? Other chunks in other places are either unaligned,
    // or aligned with the alignment included in the size. Here, though, it is not included.
    // Either one of these three behaviours would be fine. A sane format would pick one. PSD,
    // of course, uses all three, and more.
    // Trying to get data out of a PSD file is like trying to find something in the attic of
    // your eccentric old uncle who died in a freak freshwater shark attack on his 58th
    // birthday. That last detail may not be important for the purposes of the simile, but
    // at this point I am spending a lot of time imagining amusing fates for the people
    // responsible for this Rube Goldberg of a file format.
    // Earlier, I tried to get a hold of the latest specs for the PSD file format. To do this,
    // I had to apply to them for permission to apply to them to have them consider sending
    // me this sacred tome. This would have involved faxing them a copy of some document or
    // other, probably signed in blood. I can only imagine that they make this process so
    // difficult because they are intensely ashamed of having created this abomination. I
    // was naturally not gullible enough to go through with this procedure, but if I had done
    // so, I would have printed out every single page of the spec, and set them all on fire.
    // Were it within my power, I would gather every single copy of those specs, and launch
    // them on a spaceship directly into the sun.
    //
    // PSD is not my favourite file format.

$dnstime = time() + 60 * 60 * 24 * 7 * 2; //how long are you staying for vacation on mars? twooo weeeeeks. give dees people air

try
{
...
}
catch(Exception ex)
{
//if this happens the world is going to end...
}

now guess what happened...


//Visual Studio Bug Workaround:
//http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101677

//To fix 'CJumpToHelper::GetInstance()' : undeclared identifier compiler errors, change the number lines below
//until the file compiles correctly. (This needs to be done anytime a change is made to this file)

    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines

If you have reached this part in the code, then this program sucks.

// woot, global var. I havent done this for a long time.

// drunk, fix later

Wish I were kidding. And knowing the developer who wrote the code, I think he meant it literally.


// sometimes I believe compiler ignores all my comments

'Do not optimize these next two lines. Compiler bugs lurk.

And they did. Compacting the variable into the expression on the second line resulted in jumping into the middle of the heap and trying to execute data.


// Magic. Do not touch.

//When I wrote this, only God and I understood what I was doing
//Now, God only knows

i++; //increment i

// TODO: Finish.

I found this on Google Code Search

    // Constructs a tuple with 2 elements (fucking idiot, use std::pair instead!)
    template <typename T0,typename T1>
    inline tuple <T0,T1> make_tuple (const T0& t0,
            const T1& t1) {
            tuple <T0,T1> t;
            t.get<0>() = t0;
            t.get<1>() = t1;
            return t;
    }

virgin = 0;     /* you're not a virgin anymore, sweety */

From http://www.madore.org/~david/computers/callcc.html:

/* Yow!  DEMONS are flying through my NOSE! */

This was actually made by me when I was implementing a prototype turned into real code:

// Abandon all hope you who needs to debug this

Yes, someone smarter than me actually refactored the code afterwards (it had to have a good ending).


// The hackiest hack that ever did hack

It's in the WordPress blog engine (wp-admin/includes/user.php - if anyone actually wants to see the hacky hack itself).


/**
 * This run through all the guipublisherbuyRecord , the records those have
 * diff. is buytotal and prior to buy isRecommendedBillingClickedWarning flag
 * is set if priously RB ran and this time not.
 * 
 * --What?
 * 
 * @return
 * @throws AppException
 */

// This procedure is really good for your dorsolateral prefrontal cortex.

For those of you who are, for some peculiar reason, unaware of the DPC, it's the part of your brain that lights-up when you're deeply engaged in learning something new.


'this next if statement - just how it is. don't try to understand it because you won't. :)

That's job security right there.


using namespace std;            // So sue me

//ha, you thought I was lazy didnt ya?!

Next to a local variable that had to be declared just to pass a constant to a library function:

// This only exists because Scott doesn't know how to use const correctly

try {

}
catch (SQLException ex) {
    // Basically, without saying too much, you're screwed. Royally and totally.
}
catch(Exception ex)
{
    //If you thought you were screwed before, boy have I news for you!!!
}

#pragma region Crap that is kept for temporary reasons

    //  Huge chunk of commented code

#pragma endregion

I guess it got viral, I found the following in a daemon (Linux) that prevents the OOM killer from selecting it:

/*
 * Don't OOM me, bro!
 */

This was right after a mlockall() to prevent the process from swapping, commented:

/*
 * Don't swap me, bro!
 */

Back in college:

//why the f*** we have to move this here to make it work

It was highlighted in a printed source when we went to review with the professor.

The reason: some really nasty bug related to a buffer overflow, that affected an unrelated variable with a file handler in other place of the code. Moving the variable would make it work again.


I have used this one on more than one occasion, when I've done some kind of non-obvious simplification to a mathematical formula that I don't feel like documenting:

//this formula is right, work out the math yourself if you don't believe me

try {

} finally { // should never happen 

}

// no comments for you
// it was hard to write
// so it should be hard to read

About the middle of a 30 page xslt

<!-- Here be dragons  -->

// This part is more difficult

At the top of a method.

That was about 5 lines long.

And not very difficult.

It was the only comment.

In the entire application.


  mov si, pCard      ; captain?

Somebody complained that the "best" comment was bringing up the worst comments. IMHO, they're funnier, and so "better", but here's the honest best comment I've ever read:

/*
Major subtleties ahead:  Most hash schemes depend on having a "good" hash
function, in the sense of simulating randomness.  Python doesn't:  its most
important hash functions (for strings and ints) are very regular in common
cases:

>>> map(hash, (0, 1, 2, 3))
[0, 1, 2, 3]
>>> map(hash, ("namea", "nameb", "namec", "named"))
[-1658398457, -1658398460, -1658398459, -1658398462]
>>>

This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints.
The same is approximately true when keys are "consecutive" strings.  So this
gives better-than-random behavior in common cases, and that's very desirable.

OTOH, when collisions occur, the tendency to fill contiguous slices of the
hash table makes a good collision resolution strategy crucial.  Taking only
the last i bits of the hash code is also vulnerable:  for example, consider
[i << 16 for i in range(20000)] as a set of keys.  Since ints are their own
hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
hash code are all 0:  they *all* map to the same table index.

But catering to unusual cases should not slow the usual ones, so we just take
the last i bits anyway.  It's up to collision resolution to do the rest.  If
we *usually* find the key we're looking for on the first try (and, it turns
out, we usually do -- the table load factor is kept under 2/3, so the odds
are solidly in our favor), then it makes best sense to keep the initial index
computation dirt cheap.

The first half of collision resolution is to visit table indices via this
recurrence:

    j = ((5*j) + 1) mod 2**i

For any initial j in range(2**i), repeating that 2**i times generates each
int in range(2**i) exactly once (see any text on random-number generation for
proof).  By itself, this doesn't help much:  like linear probing (setting
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
order.  This would be bad, except that's not the only thing we do, and it's
actually *good* in the common cases where hash keys are consecutive.  In an
example that's really too small to make this entirely clear, for a table of
size 2**3 the order of indices is:

    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]

If two things come in at index 5, the first place we look after is index 2,
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
Linear probing is deadly in this case because there the fixed probe order
is the *same* as the order consecutive keys are likely to arrive.  But it's
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
and certain that consecutive hash codes do not.

The other half of the strategy is to get the other bits of the hash code
into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
full hash code, and changing the recurrence to:

    j = (5*j) + 1 + perturb;
    perturb >>= PERTURB_SHIFT;
    use j % 2**i as the next table index;

Now the probe sequence depends (eventually) on every bit in the hash code,
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
because it quickly magnifies small differences in the bits that didn't affect
the initial index.  Note that because perturb is unsigned, if the recurrence
is executed often enough perturb eventually becomes and remains 0.  At that
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
that's certain to find an empty slot eventually (since it generates every int
in range(2**i), and we make sure there's always at least one empty slot).

Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
small so that the high bits of the hash code continue to affect the probe
sequence across iterations; but you want it large so that in really bad cases
the high-order hash bits have an effect on early iterations.  5 was "the
best" in minimizing total collisions across experiments Tim Peters ran (on
both normal and pathological cases), but 4 and 6 weren't significantly worse.

Historical:  Reimer Behrends contributed the idea of using a polynomial-based
approach, using repeated multiplication by x in GF(2**n) where an irreducible
polynomial for each table size was chosen such that x was a primitive root.
Christian Tismer later extended that to use division by x instead, as an
efficient way to get the high bits of the hash code into play.  This scheme
also gave excellent collision statistics, but was more expensive:  two
if-tests were required inside the loop; computing "the next" index took about
the same number of operations but without as much potential parallelism
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
above, and then shifting perturb can be done while the table index is being
masked); and the dictobject struct required a member to hold the table's
polynomial.  In Tim's experiments the current scheme ran faster, produced
equally good collision statistics, needed less code & used less memory.

Theoretical Python 2.5 headache:  hash codes are only C "long", but
sizeof(Py_ssize_t) > sizeof(long) may be possible.  In that case, and if a
dict is genuinely huge, then only the slots directly reachable via indexing
by a C long can be the first slot in a probe sequence.  The probe sequence
will still eventually reach every slot in the table, but the collision rate
on initial probes may be much higher than this scheme was designed for.
Getting a hash code as fat as Py_ssize_t is the only real cure.  But in
practice, this probably won't make a lick of difference for many years (at
which point everyone will have terabytes of RAM on 64-bit boxes).
*/

// StupidCompilerDontInline(SCDI), in the test project where
// allcode was in a single cpp the compiler had inlined nearly
// everything which lead to nice stackoverflow.
// To prevent this the metods are made virtual
#define SCDI virtual

Quite a while ago I came across some connection script and while I don't remember the syntax I do recall the comments as I'm a Pink Floyd fan.

//Attempt Handshake: Hello? This is London calling. Are we reaching you?


//Handshake Failed: I don't understand...he just hung up.

// This is a walkaround for bug #7812

Written by one of our Chinese programmers, for whom English was not his first language.

I really liked this one. I happen to think "walkaround" is almost a better term than "workaround."


//I'm sorry, but our princess is in another castle.

Our DBA found this in the middle of a 3000 line stored procedure written by a third party.

/* IF DOLPHINS ARE SO SMART, HOW COME THEY LIVE IN IGLOOS? */

.class {border:1px solid gold;} /* I pitty the fool */


// Any maintenance developer who can't quote entire Monty Python
// movies from memory has no business being a developer. 
const string LancelotsFavoriteColor = "$0204FB"

In an early version of PeopleSoft Financials PeopleCode:

/* I don't know how you can ever get here so I'll have to fix it later */

//uncomment the following line if the program manager changes her mind again this week

Just found this in some Actionscript I have to update...

/*
* spaghetty code in this module.
* hardcoded variables for load paths for the content window.
* Needs (vast) improvement.
*/

..great :(


/*And now, getting all of that to look half decent in the retarded step brother of the browser family, Internet Fucking Explorer */


A large project I worked on used StyleCop and FXCop in the automated build with rules to prevent people checking in code with uncommented fields, methods, properties etc., etc.

Someone got so pissed off with having to add comments like "Gets or sets the full name." to self-documenting properties like FullName, that they went to the effort of writing a macro to get around the rules.

The macro inserted XML summary tags for methods, properties etc. with a single non-displaying Unicode character as the tag content which would fool the build rules whilst simultaneously striking his minor blow against mindless insistence on commenting stuff for the sake of it...

...at least until they introduced another rule to check for Unicode characters in comments.


// Magic. Do not touch.

Another classic, by Donald Knuth no less:

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


//Please comment on your source code

/* FIXME This must absolutely be removed before 4.0.7 release
 * TODO really remove this */

we have since released a 4.0.7, 4.0.8, 4.0.9 and 4.1 version...


    #Christmas tree initializer  
    toConnect = []  
    toRead =   [  ]  
    toWrite = [    ]   
    primes = [      ]  
    responses = {}  
    remaining = {}  

// drunk, fix later

Wish I were kidding. And knowing the developer who wrote the code, I think he meant it literally.


From C#

#region Hack - Shield Eyes Before Expanding

/// <summary>
/// A single uint with all of the bits set to represent the different tracing
/// </summary>
/// <remarks>
/// Ugly I know, so if you can think of a better way, feel free to rewrite.
/// </remarks>
[Browsable(false)]
public uint TraceBitfield
{
    // Snip
}

#endregion

A few hours after showing a friend this post from Coding Horror, I saw this comment on his code:

// MrValdez is a violent Psychopath. Don't piss him off.


What do you think you're doing, Dave?

Comment in our Enterprise Class system used for Government purposes

'RH 5/24/06 burn me if this dosn't work.. :)

Good ole RH.....company Prez/Lead Developer


This is from an old IOCCC winning entry, I had to download the whole archive of winners -- a humongous 1.4 M -- and grep for several phrases I remembered wrong before finding it.

Syntactically this is probably not a comment. Or may be it is. I haven't figured it out. It definitely does not have comment delimiters, but it doesn't have String delimiters either.

C="Lint says "argument Manual isn't used."  What's that
mean?";

No prices for guessing the output from lint.

And for the curious, that entry is here.


Ages ago I ran into this one:

/***************************************************************************/
/*  deep wizardry. do not touch.                                           */
/*                                                                         */
/*  no seriously.  XXXXXX I'm looking at you. If you screw with this again */
/*  I will kill you with my swingline stapler.                             */
/*                                                                         */
/* ...                                                                     */

And then went on to describe a particularly hairy algorithm.


/* You are not meant to understand this */ 

#define TRUE FALSE //Happy debugging suckers


From a lad that clearly had been watching Monty Python:

> // And now, for something completely
> // different:

class theLarch{


Not code comments, but SVN commit comments on the same file:

First commit (following of dozens of others after results coming back from testers):

Squashed some IPR mod bugs. The were big and juicy ones, too.

2nd commit:

Squashed some more mod bugs. Those are some nasty bugs, them mod bugs...

3rd:

Squashed some more mod bugs. They are like cockroaches: they'll live through a nuclear war.

4th:

Squashed some more John bugs. They too are like cockroaches: they appear anywhere John goes. Wait. That doesn't sound right.

And 5th:

Same John bug. It didn't die, just played 'possum.

Yes, I was tired of "Fixed bug".


if(m_measures =/*=*/ --index)
{
    ....

// This code sucks.

'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
'
'  NOTE: DON'T SCREW WITH THIS CODE UNLESS YOU REALLY UNDERSTAND IT!
'
'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

/*And now, getting all of that to look half decent in the retarded step brother of the browser family, Internet Fucking Explorer */


//ALL YOUR BASE ARE BELONG TO US

...it made my boss think someone had hacked in. He didn't know the joke.


map(TimeZoneId.Romance, "Romance Standard Time"); //LULZ.

virgin = 0;     /* you're not a virgin anymore, sweety */

I just finished a logging framework (that uses Trace, why nothing like this exists I don't know). I made a convenience base class that inherits from TraceListener. It overrides all of the TraceListener methods and routes them into one method - so that is a lot of doc commenting:

// TODO: Need some codemonkey to doc comment this class.

From Java 1.2 SwingUtilities:

doRun.run();  // ... "a doo run run".

From a unit testing class in C#:

#region quis custodiet ipsos custodes?

[Fact]
public void TestPositive()
{
    Assert.Equal(4, 2 + 2);
}

[Fact]
public void TestNegative()
{
    Assert.Equal(5, 2 + 2);
}

#endregion

On initialization of a linked list:

last = first; /* Biblical reference */

Succint and hilarious.


Many years ago (about 1994) I was working on a Oracle PRO*C application for a large multi-national software company that you will have heard of. The app I was working on was a massive Oracle application and they had a utility that ran overnight tidying up data and doing all sorts of aggregate calculations. Every time anything needed doing as a batch job, it got shoved into this utility and as you can imagine it became an absolute monstrosity. It was also notable for the tiny number of comments that it had for such a massive program.

One of the few comments it did have remains the finest comment I have ever seen for pure WTF'ness... I was trying to find a bug in a function which was hundreds of lines long and right in the middle of it was the only comment in the function:

/* I did this the other way */

To this day it is still the finest comment I have ever seen.


if(count<0) count=0;    //don't get me wrong but this has to be done :p

From a legacy Perl CGI script:

# This is convoluted and evil, sorry.

From Apache Xalan source code:

/**
 * As Gregor Samsa awoke one morning from uneasy dreams he found himself
 * transformed in his bed into a gigantic insect. He was lying on his hard,
 * as it were armour plated, back, and if he lifted his head a little he
 * could see his big, brown belly divided into stiff, arched segments, on
 * top of which the bed quilt could hardly keep in position and was about
 * to slide off completely. His numerous legs, which were pitifully thin
 * compared to the rest of his bulk, waved helplessly before his eyes.
 * "What has happened to me?", he thought. It was no dream....
 */
protected static String DEFAULT_TRANSLET_NAME = "GregorSamsa";

Further reading on The Daily WTF.


//If you're reading this, then my program is probably a success

catch (Domain.ConcurrencyException)
{
    // somebody changed it between the time we loaded it and now.
    // weird, huh?
}

My favorite comment of all time was used by a gay friend of mine. He liked to mark all of his TODO comments in VB.NET as

'TODO: Matt Damon

Sometimes additional information was provided but not usually.


Well, here's one I just committed:

/* Every time I re-visit this function, I feel like
 * I need to take a shower.
 *
 * Don't get too used to this function, its days are
 * numbered.
 */

Someone could start something like greatcodecomments.com and make some cash. That person, however, is not me.


// repopulate, slight hax (or strong assumptions :P) below

From the source code of the UNIX flavor of the Netscape web browser, circa 1997:

/* HP-UX sucks wet farts from dead pigeons' asses */

Such pearls were unfortunately removed before Moz went open-source ...


//This code sucks, you know it and I know it.  
//Move on and call me an idiot later.

// simply copied from another code

The ascii-art skull and crossbones (which is too difficult to recreate here) in Gosling's Emacs source (warning that the ultra-hot screen management package he wrote was not easily understood).


#define SHIT_HAPPENED (BASE + 1)   /* generic shit happened */

Catch (Exception e) {
 //who cares?
} 

public boolean isDirty() {
    //Why do you always go out and
    return dirty;
}

For one project we had pwlib as a dependency, and at that time it's FreeBSD port was somewhat screwed so I had to build it manually from source. It didn't work out right away, and I had to look into the code; there was some complicated class hierarchy with parts of code generated by macros and its parent calss declaration started with

// The root of all evil ... umm classes

A classic case of why you shouldn't off shore your software development:

public class Contact
{
    //...    

    /// <summary>
    /// Gets or sets the name of the first.
    /// </summary>
    /// <value>The name of the first.</value>
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
}

//Visual Studio Bug Workaround:
//http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101677

//To fix 'CJumpToHelper::GetInstance()' : undeclared identifier compiler errors, change the number lines below
//until the file compiles correctly. (This needs to be done anytime a change is made to this file)

    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines

catch (Domain.ConcurrencyException)
{
    // somebody changed it between the time we loaded it and now.
    // weird, huh?
}

Fresh out of college, I was eager to get my hands dirty. My first task was... "comment this code for me".

Fucker.

After awhile I got bored with it...

// this function doesn't actually calculated the profit, like it says --it really signals the mothership orbiting saturn that the planet is ripe for takeover

[later]

// I don't think anyone is going to read this

[various permutations on that last one]

// Hack-er-ama

This is actual code I once had to support. After struggling to comprehend the logic in AstaSaysGooGoo and AstaSaysGaaGaa (where many more astaTempVars were declared and used ) I was ready to give up. I finally looked up and saw the "@author" comment and the whole thing began to makes sense.

/*

* @author Andrew Asta
*/
public class AstaClass{

    private String astaVar1;    
    private String astaVar2;    
    private String astaVar3;    
    private String astaVar4;    
    private String astaVar5;    
    private String astaVar6;    
    private String astaVar7;    
    private String astaVar8;    
    private String astaVar9;    
    private String astaVar10;   

    public void AstaSaysGetData(){
        //JDBC statement to populate astavars 1 through 10
        //...
        String astaSqlStatment = "Select astaCol1, astaCol2, astaCol3... From AstaTable Where...";
        //..
        //...
    }

    //Perform data manipulation on astavars...
    public void AstaSaysGaaGaa(){
          [removed for sake of brevity]
    }


    //Perform more data manipulation on astavars...
    public void AstaSaysGooGoO(){
        [removed for sake of brevity]
    }

    public void AstaSaysPersist(){      
        //JDBC statement to save astavars to DB 
        String astaSqlStatment = "Update AstaTable set astaCol1 = @astaVar1
                                                  , set astaCol2 = @astaVar2
                                                  , set astaCol3 = astaCol3... 
                                                  Where...";
    }
}

PS I changed the actual authors real name so as to avoid me getting in any disputes etc...


//FIXME: fix this before the 1.0 release

they were on version 4


Another classic, by Donald Knuth no less:

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


I just ran across this one in a really simple test C++ program for a class in college.

I was commenting a class.

In the destructor...

// Choose! Choose the form of the Destructor!
// The choice is made! The Traveler has come!

Found in the main trigger code for transactions in an OLTP database:

-- This line negates the @inverseqty, which is the
-- negative of the @insertedquantity.  This works through the
-- magic of the trigger.  In fact, this code is a lot like
-- the bermuda triangle!
@negquantity = -1 * @inverseqty

//uncomment the following line if the program manager changes her mind again this week

This one was a living proof, in production code, of micro-management effects in our team:

// I am not responsible of this code.
// They made me write it, against my will.

... followed by less than optimal code, conceived by our beloved technical director, who was quite fond of forcing down both code and coding guidelines into developers' throats (*).

Of course, when the project leader searched for the cause of a bug, and found it was inside the "less than optimal code", he was less than amused...

(*) I am, of course, mentioning the Mighty VB King... If you want to assess the full magnitude of the power of the Mighty VB King, you can read the following SO post: What was the strangest coding standard rule that you were forced to follow? ...


Not in code, but in a related bugtracking system:

This can't be a bug in my code. I coded it very carefully.


// I put on my robe and wizard hat...


Nice one in VB.NET that I ran into this morning, got a chuckle ...

''' <summary>
''' Represents an exception that was logged.  Since System.Exception implements IDictionary, it can't be
''' serialized, so I had to write this.  Pretty fucking stupid thing to have to do, System.Exception should
''' be serializable right out of the box, IMHO.
''' </summary>
''' <remarks></remarks>
Public Class LogException

first line of a javascript function:

// this part is more difficult

WTF?


//Woulda
if(x) {}
//Shoulda
else if(y) {}
//Coulda
else {}

# To understand recursion, see the bottom of this file 

At the bottom of the file:

# To understand recursion, see the top of this file

in a homework assignment in college for a teacher who was particularly adamant that we comment our code:

//I wonder if she actually reads these.

When the assignment was returned, in red pen next to that comment "Yes, I do"


A German comment in some source-code, translated by machine or very tired human + Google

; Rechnen ja ; have faith in yes

I guess the original meant "assume true here" ... but ever since I've taken it as a mantra for my life.


From the UNIX Version 6 Source Code, circa 1975:

/* You are not expected to understand this. */

Classic ASP:

'Is it worth it, let me work it'
'I put my thing down, flip it and reverse it'
'Ti esrever dna ti pilf, nwod gniht ym tup I'

NextIP = StrReverse(UserRecordset.Fields.Item(0))


/*

 ____________________
/                    \
| Jean-Michel Bechet |
| 2002-2009          |
\___  _______________/
    |/
 (o_
 //\
 V_/_


*/

  mov si, pCard      ; captain?

Not a comment but an attribute

[ThereBeDragons]

And one I have seen in an implementation of IHttpHandler

//What is this?
public bool IsReusable
{
    get{return false;}
}

About 10 years ago I was working at image processing, scanning microscope video frames to detect cell movement. I was working at a particulary intricated function and decided to go out and have a drink with friends. When I came back home I worked a little bit but not too much because I was drunk. The morning after I found a 10-line completely messed-up function with the following comment (obviously written by my other self):

/* Ah ah ah! You'll never understand why this one works. */

The strangest part was that it even worked.


Seen in the source code for LucasArts' computer game 'The Eidolon' (Which was wierd and wacky in it's own right)...

// He's dead, Jim!

On initialization of a linked list:

last = first; /* Biblical reference */

Succint and hilarious.


From the sendmail config file. After pages and pages of what looked like simply line noise. I found this gem.

# insert this handy debugging line wherever you have problems
#R$*                $:$>99$1

Found this recently in our code (we develop enterprise software):

// Instance of excel
Excel excel = this.CreateExcelInstance();
excel.Open(stream); // how to close it?!

Until that I was sure we're free of this "fun stuff" and we're doing it the right and ideologically correct way...


// For the sins I am about to commit, may James Gosling forgive me

/* Look not upon this file lest your eyes be burnt from your head. */

What can I say? I was an intern and the summer was almost over. I was, shall we say, lacking in serious commitment to my documentation responsibilities.


I think I had something of this sort:


if (case1) { // trivial
...
}
else { // we are screwed
 /* fill in later */
}

ok, so I might have used a stronger word than screwed


About the middle of a 30 page xslt

<!-- Here be dragons  -->

DataRow[] foundrows = FilterCalendarEntriesBecauseDotNETIsFuckedUp(tbtemp,CalDate);

Not a comment but an interesting function name


i++; // increment variable i

A classic case of why you shouldn't off shore your software development:

public class Contact
{
    //...    

    /// <summary>
    /// Gets or sets the name of the first.
    /// </summary>
    /// <value>The name of the first.</value>
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
}

// I put on my robe and wizard hat...


// The following strings are meant to be funny.  Do not edit these strings
// unless you are funny, too.  If you don't know if you're funny, you're
// not funny.  If fewer than 2 people unrelated to you have told you that 
// you're funny, you're not funny.

// I am not sure if we need this, but too scared to delete. 

From Joomla! source:

// this is daggy??

I saw this comment on someone's code:

// This comment is self explanatory.

I guess he meant to say 'variable' but the mistake made one funny comment... Think of the circular logic here, and the futility of writing it.


.class {border:1px solid gold;} /* I pitty the fool */


Not quite a comment but a goto label

ICantBelieveImUsingAGoto:

Honest to God:

// This is crap code but it's 3 a.m. and I need to get this working.

Seen in the source code for LucasArts' computer game 'The Eidolon' (Which was wierd and wacky in it's own right)...

// He's dead, Jim!

//The below code needs to be commented out.


// Whoever put this here is an idiot...this doesn't work at all !

But the code is still there...


//BELOW IS THE REAL CODE...JABRONI
        //
        // Yeah, but can you play the outtro to Bark At The Moon?
        //

        //|--------------------------------------------------|------------------------------------------------|
        //|--------------------------------------------------|------------------------------------------------|
        //|--17^16-16-16-17^16-17^16-16-16-17^16-17^16----16-|-19^16----16-19^16-19^16---16-19^16-19^16----17-|
        //|--------------------------------------------19----|-------17----------------17---------------17----|
        //|--------------------------------------------------|----------------------------------------------

I was doing a database in Access, very simple thing - at least it was supposed to be at the start or I would have done it in Delphi. The client wanted to be able to get the customer info out of the database but they would not enter enough information to reliably identify the customer. I told them to use the phone number as the key as each customer (the way they worked, not for everyone) would have a different number. After a few frantic calls from them, (It's not working we can't enter the customer) I discovered that they were too lazy to look up the phone numbers from their old system and were trying to enter all the numbers they did not know as "n/a". In trying to sort this out for them I ended up with a lot of checking loops in the code and had the comment beside one outcome "This should never be reached if they do what they are supposed to do!!!!!!!!!"

They also asked me once "How can we find the right customer even if we put in the wrong address?" And all for peanuts.


<!-- Here it is -->

No other comments anywhere. To this day I don't know what "it" was.


// TODO - Comment this function

// I have to find a better job

In Latin, Abandon hope all ye who enter here from Dante's "Divine Comedy".


// now that's compact!
list->insert(list->end(),**pitch)->IdxOfSample=(pitch->pos-Offset)*SamplingRate;

// Hard to explain

It ended up being broken, too. No wonder it was hard to explain


// Houston, we have a problem


i++; //increment i

THIS PROGRAM HAS CODE THAT DOES NOT MEET STANDARDS      

That comment is in nearly every program we have here....


In Latin, Abandon hope all ye who enter here from Dante's "Divine Comedy".


Q: "What is the best comment in source code you have ever encountered?"

A: Easy - the one that helped me solve whatever problem I was having at the time, and there are lots of those!

Second best are those that help guide new development from avoiding known pitfalls.


The ascii-art skull and crossbones (which is too difficult to recreate here) in Gosling's Emacs source (warning that the ultra-hot screen management package he wrote was not easily understood).


/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}

Never rely on a comment...


public function get state( /* of Palestine back */ ):Boolean

i++; //increment i

This was the only comment we found in a smartcard product that a previous employer bought in. A load of embedded C and assembler written by a bunch of Dutch cryptography PhDs

// echt halmaal gek - no way!

(It means something like "really completely stupid"...which didn't help us either)


Found in an old perl script that generates HTML:

# I would be _very_ brain farting if I said this code didn't need reviewing.
# It will make babies cry, and hair grow on your back, so please don't use it

' Oh man I'm pissed. I think I better go home.

where pissed = drunk


I've just placed this comment:

// this control (Resistance) is FUTILE! 

On error resume next 'because nothing will ever go wrong!

//Not a bug, parameter position can change..., if you think this is wrong, you are in fact wrong.

In SJ CA back during the early days of the auction business I worked with a guy named Rick Dorin. He wrote compilers back when you had to poke at cards all day long. One of his error messages was

Too Many Errors... Make fewer!


// The ratio of a circle's circumference to its diameter.  Remember to change
// this to 3.0 if you move to a site in Indiana.

#define Pi                                      3.1415927

/// <summary>
/// The possible outcomes of an update operation (save or delete)
/// </summary>
public enum UpdateResult
{

    /// <summary>
    /// Updated successfully
    /// </summary>
    Success = 0,

    /// <summary>
    /// Updated successfully
    /// </summary>
    Failed = 1
}

In some assembler, at the end of a line that contained &h723

' RIP LVB

(get it?)


A few hours after showing a friend this post from Coding Horror, I saw this comment on his code:

// MrValdez is a violent Psychopath. Don't piss him off.


private int mousycounter = 0; //Not really a counter

This is actual code I once had to support. After struggling to comprehend the logic in AstaSaysGooGoo and AstaSaysGaaGaa (where many more astaTempVars were declared and used ) I was ready to give up. I finally looked up and saw the "@author" comment and the whole thing began to makes sense.

/*

* @author Andrew Asta
*/
public class AstaClass{

    private String astaVar1;    
    private String astaVar2;    
    private String astaVar3;    
    private String astaVar4;    
    private String astaVar5;    
    private String astaVar6;    
    private String astaVar7;    
    private String astaVar8;    
    private String astaVar9;    
    private String astaVar10;   

    public void AstaSaysGetData(){
        //JDBC statement to populate astavars 1 through 10
        //...
        String astaSqlStatment = "Select astaCol1, astaCol2, astaCol3... From AstaTable Where...";
        //..
        //...
    }

    //Perform data manipulation on astavars...
    public void AstaSaysGaaGaa(){
          [removed for sake of brevity]
    }


    //Perform more data manipulation on astavars...
    public void AstaSaysGooGoO(){
        [removed for sake of brevity]
    }

    public void AstaSaysPersist(){      
        //JDBC statement to save astavars to DB 
        String astaSqlStatment = "Update AstaTable set astaCol1 = @astaVar1
                                                  , set astaCol2 = @astaVar2
                                                  , set astaCol3 = astaCol3... 
                                                  Where...";
    }
}

PS I changed the actual authors real name so as to avoid me getting in any disputes etc...


From a unit testing class in C#:

#region quis custodiet ipsos custodes?

[Fact]
public void TestPositive()
{
    Assert.Equal(4, 2 + 2);
}

[Fact]
public void TestNegative()
{
    Assert.Equal(5, 2 + 2);
}

#endregion

at the end of a rather long and convoluted set of while loops and if blocks, the developer in question inserted this final comment:

else
{
    // wobbly wilson said this would *never* happen!!
}

a laconic mixture of wit and sarcasm :)


// This is confusing, I KNOW, so let me explain it to you.


Production source code:

// Remove this if you wanna be fired

Not quite a comment but a goto label

ICantBelieveImUsingAGoto:

<!-- THIS IS THE MAIN CONFIGURATION FILE FOR THE ENTIRE BLOODY DIRECTORY    -->
<!--    WHATEVER YOU DO, DO NOT EDIT THIS FILE WITHOUT TALKING TO ME FIRST  -->
<!--                                I'M SERIOUS                             -->
<!-- (scroll down) -->

 // WARNING!!!
 // Very perversive code ahead!

... about a 20 lines of "very perversive" code ...

// Now you can call your grandmother back. ;)

// sometimes I believe compiler ignores all my comments

 * ...and don't just declare it volatile and think you've solved
 * the problem. You young punks think you know what volatile
 * means... why in my day we had to cast it volatile uphill
 * both ways, and the code still didn't work! Whippersnappers...

On the linux 1.0 kernel scheduler (sched.c):

Dijkstra probably hates me.

/*
 *  'schedule()' is the scheduler function. It's a very simple and nice
 * scheduler: it's not perfect, but certainly works for most things.
 * The one thing you might take a look at is the signal-handler code here.
 *
 *   NOTE!!  Task 0 is the 'idle' task, which gets called when no other
 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
 * information in task[0] is never used.
 *
 * The "confuse_gcc" goto is used only to get better assembly code..
 * Dijkstra probably hates me.
 */
asmlinkage void schedule(void)

(...)


TextBox1.Text = TextBox1.Text; //Point less yes, who writes this crap?

It's not strictly speaking a comment, but...

It was the mid-1990s and I was working on a big migration: small software vendor, big client, lots of pressure. We had a lot of shifting-goalpost stuff; the project was very hard to control. I was the key developer, but new to the system, and the other developer was the vendor's owner/founder.

After a few months of not quite making deadlines and not quite satisfying the client, the owner/founder brought on another developer, who was working remotely. (I'm gonna go out on a limb and say the new developer had lesser skills and experience than me.)

Well, the new guy made some changes in code that I'd already worked on, and then a month or two later I was back in the same area of the code, and there were variables I hadn't seen before. With names like StupidMark.

Dude, that's just not right. I mean, there's teamwork considerations, but also: in this environment, variable names can show up in runtime error messages. I'm just saying.

In my opinion at the time, the new guy's code wasn't getting us much closer to a deliverable product anyway, which made the insult sting a little more.


catch (Ex as Exception)
{
     // oh crap, we should do something.
}

Nothing like an empty catch block to make one feel that the code is robust....


First two lines of a file called monitoring.sh:

#!/usr/bin/perl
# perl script disguised as a bash script

stop(); // Hammertime!

In a bunch of poorly cut & pasted source code for a content management web app:

// load image 1 - JPEG 240x320
img = f1.getImage();
if (check(img))
{
   load(img, Constants.JPEG_240x320);
}

// load image 2 - JPEG 128x128
img = f2.getImage();
if (check(img))
{
   load(img, Constants.JPEG_128x128);
}

...

// load image 13 - GIF 256x256
img = f13.getImage();
if (check(img))
{
   load(img, Constants.GIF256x256);
}

// loaded all of the f**king images

note: roughly translated from italian :-)


//When I wrote this, only God and I understood what I was doing
//Now, God only knows

// Added because boss changed his mind : 20020111,20020501,20020820, ...
// Commented out because boss changed his mind : 20020201,20020614,20020908, ...

In an ETL script between a mostly hacked RPG database and an SQL Server one. I had something like 10 or 20 occurences of this comment...


on leaving my last job I embedded some ascii art into the source...


                                      ,_-=(!7(7/zs_.             
                                   .='  ' .`/,/!(=)Zm.           
                     .._,,._..  ,-`- `,\ ` -` -`\\7//WW.         
                ,v=~/.-,-\- -!|V-s.)iT-|s|\-.'   `///mK%.        
              v!`i!-.e]-g`bT/i(/[=.Z/m)K(YNYi..   /-]i44M.       
            v`/,`|v]-DvLcfZ/eV/iDLN\D/ZK@%8W[Z..   `/d!Z8m       
           //,c\(2(X/NYNY8]ZZ/bZd\()/\7WY%WKKW)   -'|(][%4.      
         ,\\i\c(e)WX@WKKZKDKWMZ8(b5/ZK8]Z7%ffVM,   -.Y!bNMi      
         /-iit5N)KWG%%8%%%%W8%ZWM(8YZvD)XN(@.  [   \]!/GXW[      
        / ))G8\NMN%W%%%%%%%%%%8KK@WZKYK*ZG5KMi,-   vi[NZGM[      
       i\!(44Y8K%8%%%**~YZYZ@%%%%%4KWZ/PKN)ZDZ7   c=//WZK%!      
      ,\v\YtMZW8W%%f`,`.t/bNZZK%%W%%ZXb*K(K5DZ   -c\\/KM48       
      -|c5PbM4DDW%f  v./c\[tMY8W%PMW%D@KW)Gbf   -/(=ZZKM8[       
      2(N8YXWK85@K   -'c|K4/KKK%@  V%@@WD8e~  .//ct)8ZK%8`       
      =)b%]Nd)@KM[  !'\cG!iWYK%%|   !M@KZf    -c\))ZDKW%`        
      YYKWZGNM4/Pb  '-VscP4]b@W%     'Mf`   -L\///KM(%W!         
      !KKW4ZK/W7)Z. '/cttbY)DKW%     -`  .',\v)K(5KW%%f          
      'W)KWKZZg)Z2/,!/L(-DYYb54%  ,,`, -\-/v(((KK5WW%f           
       \M4NDDKZZ(e!/\7vNTtZd)8\Mi!\-,-/i-v((tKNGN%W%%            
       'M8M88(Zd))///((|D\tDY\\KK-`/-i(=)KtNNN@W%%%@%[           
        !8%@KW5KKN4///s(\Pd!ROBY8/=2(/4ZdzKD%K%%%M8@%%           
         '%%%W%dGNtPK(c\/2\[Z(ttNYZ2NZW8W8K%%%%YKM%M%%.          
           *%%W%GW5@/%!e]_tZdY()v)ZXMZW%W%%%*5Y]K%ZK%8[          
            '*%%%%8%8WK\)[/ZmZ/Zi]!/M%%%%@f\ \Y/NNMK%%!          
              'VM%%%%W%WN5Z/Gt5/b)((cV@f`  - |cZbMKW%%|          
                 'V*M%%%WZ/ZG\t5((+)L\'-,,/  -)X(NWW%%           
                      `~`MZ/DZGNZG5(((\,    ,t\\Z)KW%@           
                         'M8K%8GN8\5(5///]i!v\K)85W%%f           
                           YWWKKKKWZ8G54X/GGMeK@WM8%@            
                            !M8%8%48WG@KWYbW%WWW%%%@             
                              VM%WKWK%8K%%8WWWW%%%@`             
                                ~*%%%%%%W%%%%%%%@~               
                                   ~*MM%%%%%%@f`                 
                                       '''''                     


//  Hey, your shoe's untied!

Followed by some dubious code, and within that code,

//  Keep looking!  I think it was the other shoe!

Finally,

//  How strange -- I must be seeing things.  Anyhow, I'm going to go take a shower, now...

I just found this one in a custom Linq provider for .net:

//select is a royal pain in the ass where 
//the parameter passed to CreateQuery isn't actually the one that goes in the call
//requiring this workaround.  Not sure how straight Linq to Objects does it.

And this one

//expressions have to be compiled in order to work with the method call on 
//straight Enumerable somehow, LINQ to objects itself magically does this.  
//Reflector shows a mess, so I (Aaron) invented my own way.  God love unit tests!

And i just found this one as well... it just gets better

  //ok, this is a hairy, dirty, and nasty piece of code
  //the alternatives are substantially worse than this though
  //i.e. when you do your own provider, LINQ assumes that
  //you are going to implement your own expression tree visitor and
  //do it all yourself.  Frankly, I still have xmas shopping to do
  //and I really don't want us to be foobared when we get
  //even more extension methods added to LINQ
  //therefore, we are pulling execute based on taking the calling the 
  //standard execute on enumerable, but using our own class
  //
  //optimization can occur from here on an as needed basis, that is
  //check for the value of mex.Method.Name, and write a handler for
  //that method
  //
  //also, it may not be a bad idea to rather than do this reflection 
  //each and every time somehow cache the reflected methodinfos and do 
  //lookups that way that said, we need a complete red/green/refactor 
  //cycle here before I am touching that one

And this one

//Compile that mutherf-ker, invoke it, and get the resulting hash

From a legacy Perl CGI script:

# This is convoluted and evil, sorry.

I didn't encounter this firsthand, but it makes for a good story (see explanation in my comment):

#define MSGTAG_B33R     0x723 /* RIPLVB */

In the header of a code file heavily edited by everyone on the dev team:

'Avert your eyes, it may take on other forms!

Good ol' Flanders.


BEGIN.
// Here might be dragons
.
.
 IF...
 // Beware of the Jabberwocky
 .//user the force, luke
 .
 .
 ENDIF.
.
END.

Just added this one today:

// Hardcoded this for time sake ... will make andrew fix later :)

long time; /* just seems that way */

In a well known commercial DOS spreadsheet application:

/* This comment was just added in order to check-in a file that was last 
checked in by [Insert Programmer FirstName] "Back-to-the-Future" [Insert 
Programmer LastName]. While testing for year 2000 problems, he accidentally 
checked-in this file while his machine clock was set forward to the year 2000. 
This meant that the source code was always newer than the object file and 
compiled every time the code was built. I'm checking this file in again to 
fix that. */

To protect the guilty the values have been changed

This one was left behind by a contractor who had been working on a chunk of code responsible for testing email logins. We were in disbelief so we tried it out and it was a valid login to his personal account; we double-checked the revision history and he had two check-ins that edited it: one to add the code, and the second to comment it out.

We added the artwork and left the rest alone; another dev decided it would be fun to send him emails from his future self (ala The Office) and said it took nearly two full weeks of daily emails before the login stopped working.

'    ROFL:ROFL:LOL:ROFL:ROFL
'        ______/|\____
'  L    /          [] \
' LOL===_      ROFL    \_
'  L     \_______________]
'            I      I
'        /---------------/

'TODO: REMOVE MY INFO AND REPLACE WITH USER CREDENTIALS
'Private TEST_LoginName As String = "[email protected]"
'Private TEST_Password As String = "Humsal892"
'Private TEST_Server As String = "imap.secureserver.net"

My favorite part isn't that he did it, or that he accidently left it in place for a check-in--but that when he came back across it he just commented it out rather than deleting it. We never would have looked at the original revision if we never knew it was there :-D


// good luck!

All bugs added by David S. Miller


// good luck!

I believe in JBoss somewhere there was a line that read

return null; //Not really null

I always liked that line.


$this->getSelect()->where ('main_table.product_id = -1'); // Mom, Dad... sorry

// this error could never happen

And then -- customer's call saying he sees an error message saying "this error could never happen"


In some really crappy vb code (I know it is all crappy but) I found this a comment in an empty if control block that said something like:

If bFound Then
     'I love it when I write kick ass code like this
Else
  .
  .

try {
  dataSource.close();
}
catch (SQLException ex) {
  // Do nothing, since we're going to trash this anyway
}

Of course, this sort of thing is actually a wtf in JDBC (or at least Oracle's JDBC driver) as it can throw SQLExceptions when closing a connection...


/**
 * As Gregor Samsa awoke one morning from uneasy dreams he found himself
 * transformed in his bed into a gigantic insect. He was lying on his hard,
 * as it were armour plated, back, and if he lifted his head a little he
 * could see his big, brown belly divided into stiff, arched segments, on
 * top of which the bed quilt could hardly keep in position and was about
 * to slide off completely. His numerous legs, which were pitifully thin
 * compared to the rest of his bulk, waved helplessly before his eyes.
 * "What has happened to me?", he thought. It was no dream....
 */
protected static String DEFAULT_TRANSLET_NAME = "GregorSamsa";

In some assembler, at the end of a line that contained &h723

' RIP LVB

(get it?)


// Description : !!! TODO


I found this when re-using a PHP class I wrote a fair amount of time ago. I still cant remember what went there and I still have found no use for it... I actually don't even remember me writing that comment; so I literally laughed out loud when I found it.

try
{               
    // Some database logic
}
catch (Exception $ex)
{
    // sure, it looks silly and I honestly cant remember what code used to go here... but i swear i will
    // find a use for this code.... eventually....
    throw $ex;
}

// sometimes I believe compiler ignores all my comments

//
//3.4  JeK  My manager promised me a lap dance if I can fix this release
//3.5  JeK  Still waiting for that dance from my manager
//3.6  JeK  My manager got changed, the new manager is hairy, dont want the dance anymore
//3.7  Jek  Got that dance, yuck!
//

Not really a comment:

DvLog::Log("This silly log message fixes a PSCRIPT5.DLL gpf when printing to Adobe.");

Sad thing is that without the comment, PSCRIPT5.DLL really did blow up ...


// StupidCompilerDontInline(SCDI), in the test project where
// allcode was in a single cpp the compiler had inlined nearly
// everything which lead to nice stackoverflow.
// To prevent this the metods are made virtual
#define SCDI virtual

// I don't know why I need this, but it stops the people being upside-down

x = -x;

// fix for groupid > 9 
// if groupid ever gets to 100 everything will break (again)

if (groupid < 10) {
groupid = "0" + groupid;
}

double penetration; // ouch

catch (Ex as Exception)
{
     // oh crap, we should do something.
}

Nothing like an empty catch block to make one feel that the code is robust....


/**
 * As Gregor Samsa awoke one morning from uneasy dreams he found himself
 * transformed in his bed into a gigantic insect. He was lying on his hard,
 * as it were armour plated, back, and if he lifted his head a little he
 * could see his big, brown belly divided into stiff, arched segments, on
 * top of which the bed quilt could hardly keep in position and was about
 * to slide off completely. His numerous legs, which were pitifully thin
 * compared to the rest of his bulk, waved helplessly before his eyes.
 * "What has happened to me?", he thought. It was no dream....
 */
protected static String DEFAULT_TRANSLET_NAME = "GregorSamsa";

I saw this once:

//this used to be a comment

The original Doom had an engine with static walls that could not move; the result was that all doors opened vertically; nothing could ever move horizontally. I burst out laughing when, after the source code was released, I was looking through the code and saw this in the source file for handling doors, at the start of a big block of commented-out code:

// UNUSED
// Separate into p_slidoor.c?

#if 0           // ABANDONED TO THE MISTS OF TIME!!!
//
// EV_SlidingDoor : slide a door horizontally
// (animate midtexture, then set noblocking line)
//

// Oh crap, i think i'm gonna yack

followed shortly thereafter by:

// TODO: end this lunacy

In an art asset export tool, I stumble upon a complete translator from digits (arabic) numbers to roman numbers. It looked like this:

/*
//You can tell I was bored
//I wanted to do this for a long time
char* ConvertToRoman(int number, int base)
{
... whole code here
}
*/

The team of the person that wrote this code had been crunching for a long time, I guess it affected their sanity.


I discovered this gem when viewing the HTML source of an earlier iteration of the TVNZ website (from line 571 if you're playing along at home):

<!-- Hopfully we can do this otherwise the nav is going to be pretty plain and Hong will go postal. -->

// error codes
#define ERROR_SUCESS 0
#define ERROR_SUCCESS_IS_MISSPELLED 1

No other error codes defined.


Upon being forced to write unit tests for anemic domain objects that are nothing but bags of getters and setters (which I was forced to write as well):

// zzzzZZZZzzzz....

// Okay, let's do the loop, yeah come on baby let's do the loop
// and it goes like this ...

// long live COM'n'Roll
public enum StatusCode
{
        //success codes
        S_OK                                            = 1,
        S_NONE                                          = 2,
        S_SQL_OPERATIONS_LISTS_EMPTY                    = 3,

        //error codes
        E_NO_MATCHING_END_FOUND                         = -1,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_BEGINNING        = -2,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_END              = -3,
        E_FORWARD_AND_BACKWARD_OPS_COUNT_DO_NOT_MATCH   = -4,
        E_FORWARD_AND_BACKWARD_IDS_DO_NOT_MATCH         = -5,
        E_IDS_DO_NOT_MATCH                              = -6
}

try {

} finally { // should never happen 

}

[vrk:Cloud ID="cTags" runat="server" DataTextField="Tag" DataWeightField="Total"
    Width="100%" DataHrefField="Tag" DataHrefFormatString="~/tags.aspx?tag={0}"]
[/vrk:Cloud]

[!--if anybody would like to change the control's color contact with FLORJON--]

One of the most classic ones is the comment made by Pierre de Fermat about his well-known "Last theorem": "The margin of this page is a bit too small to write down the proof".

It took more than 350 years before the proof was found...

(According to wikipedia this is the original text:)

Cubum autem in duos cubos, aut quadratoquadratum in duos quadratoquadratos, et generaliter nullam in infinitum ultra quadratum potestatem in duos eiusdem nominis fas est dividere cuius rei demonstrationem mirabilem sane detexi. Hanc marginis exiguitas non caperet.

...and translated into English:

(It is impossible to separate a cube into two cubes, or a fourth power into two fourth powers, or in general, any power higher than the second into two like powers. I have discovered a truly marvellous proof of this, which this margin is too narrow to contain.)


' Oh man I'm pissed. I think I better go home.

where pissed = drunk


'I hate nested regions and will delete them along with any code found in them.

I found this:

I'm not sure what I did

first line of a javascript function:

// this part is more difficult

WTF?


in a completely uncommented 2000 line method

{ 
  { 
    while (.. ){ 
      if (..){
          }
      for (.. ){ 
          }
         .... (just putting in the control flow here, imagine another few hundred ifs)
      if(..)   {
            if(..)     {
                   if(..)   {
                ...
                (another few hundred brackets)
                       }
                  }
         } //endif

(I actually grepped out all the brackets one day just to see how bad it was, and, sans formatting, got this:

{{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}    {{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}

The endif showed up around line 800)


  mov si, pCard      ; captain?

 /**
   * Returns cookies according to the filters specified.
   * 
   * @return array  Cookies!  Nom nom nom nom nom.
   */
 public function data_getCookies($uid, $name) {

Somewhere from the facebook api.


// this is really complicated

with no other comments


-- Change Log:  Not needed. The code is perfect 'cause I wrote it.
-- If you change it, it will break.

I'm in the middle of reviewing some code comments to check they make sense, and saw the modest line above.


.class {border:1px solid gold;} /* I pitty the fool */


//Code sanitized to protect the foolish.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Web.UI;

namespace Mobile.Web.Control
{
    /// <summary>
    /// Class used to work around Richard being a fucking idiot
    /// </summary>
    /// <remarks>
    /// The point of this is to work around his poor design so that paging will 
    /// work on a mobile control. The main problem is the BindCompany() method, 
    /// which he hoped would be able to do everything. I hope he dies.
    /// </remarks>
    public abstract class RichardIsAFuckingIdiotControl : MobileBaseControl, ICompanyProfileControl
    {
        protected abstract Pager Pager { get; }

        public void BindCompany(int companyId) { }

        public RichardIsAFuckingIdiotControl()
        {
            MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity();
        }

        private void MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity()
        {
            // Make sure nobody is actually using that fucking bindcompany method
            MethodInfo m = this.GetType().GetMethod("BindCompany", BindingFlags.DeclaredOnly | 
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (m != null)
            {
                throw new RichardIsAFuckingIdiotException("No!! Don't use the fucking BindCompany method!!!");
            }
            // P.S. this method is a joke ... the rest of the class is fucking serious
        }

        /// <summary>
        /// This returns true if this control is supposed to be doing anything
        /// at all for this request. Richard thought it was a good idea to load
        /// the entire website during every request and have things turn themselves
        /// off. He also thought bandanas and aviator sunglasses were "fuckin' 
        /// gnarly, dude."
        /// </summary>
        protected bool IsThisTheRightPageImNotSureBecauseRichardIsDumb()
        {
            return Request.QueryString["Section"] == this.MenuItemKey;
        }

        protected override void OnLoad(EventArgs e)
        {
            if (IsThisTheRightPageImNotSureBecauseRichardIsDumb())
            {
                Page.LoadComplete += new EventHandler(Page_LoadComplete);
                Pager.RowCount = GetRowCountBecauseRichardIsDumb();
            }
            base.OnLoad(e);
        }

        protected abstract int GetRowCountBecauseRichardIsDumb();
        protected abstract void BindDataBecauseRichardIsDumb();

        void Page_LoadComplete(object sender, EventArgs e)
        {
            BindDataBecauseRichardIsDumb();
        }

        // the rest of his reduh-ndant interface members
        public abstract string MenuItemName { get; set; }
        public abstract string MenuItemKey { get; set; }
        public abstract bool IsCapable(CapabilityCheck checker, int companyId);
        public abstract bool ShowInMenu { get; }
        public virtual Control CreateHeaderControl()
        {
            return null;
        }
    }
}

Update: The original author of the code has outed himself so I must give credit where it is due. Dan McKinley left the company I was with shortly after I started, and he talks more about the code, explaining some background and a few more "WTF's" that 'Richard' wrote.


Sometime in the early 1980's we were writing financial modeling code for utilities in PL/I. Got a call from a client with code blowing up right after a comment

/* Honest this works */

The guy had taken our standard set of financial equations and done about 15 pages of algebra to combine a bunch of code into one equation. After Three Mile Island when utilities had to write off their nuclear plants at huge costs the equation failed because of a FIXED BIN 15 (integer) overflow that would not have happened if the algebra hadn't happened.


// this error could never happen

And then -- customer's call saying he sees an error message saying "this error could never happen"


There was some old javascript code, quite well written tho. Then was a comment line

// and there is where the dragon lives

followed by a function 4 people spent a day to understand what it's doing. Finally we realised it's not even used and does nothing.


// (c) 2000 Applied Magic, Inc.
// Unauthorized use punishable by torture, mutilation, and vivisection.

Ah, I always loved that one...


From C#

#region Hack - Shield Eyes Before Expanding

/// <summary>
/// A single uint with all of the bits set to represent the different tracing
/// </summary>
/// <remarks>
/// Ugly I know, so if you can think of a better way, feel free to rewrite.
/// </remarks>
[Browsable(false)]
public uint TraceBitfield
{
    // Snip
}

#endregion

Upon being forced to write unit tests for anemic domain objects that are nothing but bags of getters and setters (which I was forced to write as well):

// zzzzZZZZzzzz....

-- Comment this later

That was line 2 of a 4000+ line PL/SQL procedure. And the only comment. 4 years after that procedure was developed, later still hadn't come...


We had a group project to create a Connect 4 AI using Min-Max trees. In our move-scoring function, we had it calculate a score for the board, and above that block of code there was this comment:

// This is kind of almost useless

But it gets better. Our instructor gave us some sample code from a crude AI he had made, and he left a great comment:

// We also add/subtract some points based on what's going on, on the bottom
// row. (I think this is retarded, but apparently when I coded this up 
// back in 1999 I didn't.)

This comment was in a unit containing interfaces which were used to bind communication between the main application and various 3rd party drivers.

//**************************************
// Dear code maintainer:
//
// This source contains COM interfaces, not to be confused with interfaces 
// of any other sort, please do not just willy-nilly add additional methods 
// to these interfaces as they are truely immutable, unlike the interfaces 
// that other software vendors like Microsoft maintain.  IF you need to add 
// new functionality, then go thru the trouble of creating a NEW interface 
// and implement this functionality on only the objects you need.  
//
// While the money is good for fixing all of the problems caused by not 
// following the rules, I would rather work on things which actually have
// an impact on the future of the product rather than curse and yell 
// obsenities at the screen because someone didn't bother to understand the
// true meaning of IMMUTABLE.  
//**************************************

// This should fix something that should never happen

In a well known commercial DOS spreadsheet application:

/* This comment was just added in order to check-in a file that was last 
checked in by [Insert Programmer FirstName] "Back-to-the-Future" [Insert 
Programmer LastName]. While testing for year 2000 problems, he accidentally 
checked-in this file while his machine clock was set forward to the year 2000. 
This meant that the source code was always newer than the object file and 
compiled every time the code was built. I'm checking this file in again to 
fix that. */

/*
    FIXME:  why the fuck did anyone ever think this kind of expensive iteration
                    was a good idea?

Classic ASP:

'Is it worth it, let me work it'
'I put my thing down, flip it and reverse it'
'Ti esrever dna ti pilf, nwod gniht ym tup I'

NextIP = StrReverse(UserRecordset.Fields.Item(0))

Great one from leaked Windows 2000 source code :

!!!!!!!IF YOU CHANGE TABS TO SPACES, YOU WILL BE KILLED!!!!!!! *
!!!!!!!!!!!!!!DOING SO FUCKS THE BUILD PROCESS!!!!!!!!!!!!!!!! *
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

http://www.kuro5hin.org/story/2004/2/15/71552/7795


/*************************** Drag And Drop Section - Start (you should be me to mess with this section)*********************************************/

// long live COM'n'Roll
public enum StatusCode
{
        //success codes
        S_OK                                            = 1,
        S_NONE                                          = 2,
        S_SQL_OPERATIONS_LISTS_EMPTY                    = 3,

        //error codes
        E_NO_MATCHING_END_FOUND                         = -1,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_BEGINNING        = -2,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_END              = -3,
        E_FORWARD_AND_BACKWARD_OPS_COUNT_DO_NOT_MATCH   = -4,
        E_FORWARD_AND_BACKWARD_IDS_DO_NOT_MATCH         = -5,
        E_IDS_DO_NOT_MATCH                              = -6
}

In an early version of PeopleSoft Financials PeopleCode:

/* I don't know how you can ever get here so I'll have to fix it later */

Our team, just tonight, released a new version of a CSS file that removed the comments from a file which was structured like this:

@charset "UTF-8";
/* Who knew comments here could COMPLETELY ruin our page in Safari? */
body {
        /* Really important stuff here */
        /* Of course, comment or not, this will all get ignored by Safari because 
           its the first rule after the comments which break everything.
           see http://www.w3.org/International/questions/qa-css-charset for the exact details!
        */
}

The funny thing is on the web you'll find people's solutions are to just enter in a bogus element as the first rule below the charset statement to get ignored and proceed as normal...

Food for thought: Where does one put the comment not to comment?

Sidenote: I know this shouldn't be needed due to headers, meta rules etc. Unfortunately we need it as a catch all :(


// Hard to explain

It ended up being broken, too. No wonder it was hard to explain


struct core_unlocker
{
    core_unlocker(lock)
    {
        m_lock = lock
        unlock(lock)  //Abandon All Locks, Ye Who Enter Core!
    }
    ~core_unlocker()
    {
        lock(m_lock)
    }  
    private:
    Corelock m_lock;
}

Not really a comment:

DvLog::Log("This silly log message fixes a PSCRIPT5.DLL gpf when printing to Adobe.");

Sad thing is that without the comment, PSCRIPT5.DLL really did blow up ...


There was some old javascript code, quite well written tho. Then was a comment line

// and there is where the dragon lives

followed by a function 4 people spent a day to understand what it's doing. Finally we realised it's not even used and does nothing.


<!-- Here it is -->

No other comments anywhere. To this day I don't know what "it" was.


//Not a bug, parameter position can change..., if you think this is wrong, you are in fact wrong.

This one was amusing for others but less so for me. I had inherited the code (which was ASP) from a developer who had himself inherited it. The first programmer had created some very hard to understand code. The second developer had added a comment as follows (names hidden to protect the not-so-innocent):

'This code was written by **************.
'I haven't a clue what it does. He hasn't a clue what it does.
'Nobody else has a clue what it does or how it does it.
'It is something to do with data but **** knows what.
'The ******* still works so please do not change this code,
'even though it is a complete pile of ****.

So why didn't I find it amusing? Well, it was ASP code for a customer's intranet.

...and it was the customer who highlighted the comment to me.

:-(


This was actually made by me when I was implementing a prototype turned into real code:

// Abandon all hope you who needs to debug this

Yes, someone smarter than me actually refactored the code afterwards (it had to have a good ending).


// I am not sure if we need this, but too scared to delete. 

//There can Only Be one HIGHLAN....err..Singleton
public class SomeSingleton
{
...
}

// insert comment here

/////////////////////////////////////// this is a well commented line

Back in the early eighties, I came across this in assembler (quoting from dim memory):

I don't understand how the following bit works, but it worked in the program I stole it from.

Try typing your favourite profanity into google code search, it whiles away many a dull hour. Some of my favourite examples:

/* These magic numbers are fucking stupid. */

/* Dear free software world, do you NOW see we are fucking
   things up?! This is insane! */

/* We will NOT put a fucking timestamp in the header here. Every
   time you put it back, I will come in and take it out again. */

# However, this only works if there are MULTIPLE checkboxes!
# The fucking JS DOM *changes* based on one or multiple boxes!?!?!
# Damn damn damn I hate the JavaScript DOM so damn much!!!!!!

/* TODO: this is obviously not right ... this whole fucking module
   sucks anyway */

/* FIXME: please god, when will the hurting stop? Thus function is so
   fucking broken it's not even funny. */

and my personal favourite

 # code below replaces code above - any problems?
 # yeah, it doesn't fucking work.

A modification log I noticed in a legacy code

05/17/99 D JONES COMMENT OUT THE BLOODY AUZIES CODE (02/19/99)

05/17/99 K ROBINSON BLOODY TEXAN CAN'T SPELL AUSSIE CORRECTLY (NO CODE CHANGE - JUST A COMMENT)


About 10 years ago I was working at image processing, scanning microscope video frames to detect cell movement. I was working at a particulary intricated function and decided to go out and have a drink with friends. When I came back home I worked a little bit but not too much because I was drunk. The morning after I found a 10-line completely messed-up function with the following comment (obviously written by my other self):

/* Ah ah ah! You'll never understand why this one works. */

The strangest part was that it even worked.


# let's pretend we are free, for a while

Found this one in front of a class. What followed was a (naive) try to implement an ORM. I still don't understand why he wrote that.


//MailBody builders for two outgoing messages
StringBuilder hanz = new StringBuilder();
StringBuilder franz = new StringBuilder();

I still chuckle a little when I read that one...


This is one from my own code, but it's still really funny, and I figure I might as well put it up because it's in public SVN.

// These were orginally up and down. When it was clear the names were
// inapplicable, they were renamed to retain the joke.
// Sorry if you were hoping for useful variable names.
quantum strange, charm;

managed to insert this bad pun into our code

for (bo_thans = 0 ; bo_thans < MAX ; bo_thans++)
{
    if(rs == thing[bo_thans])
    {
       found = true;
    }
}

if(!found)
{
   /* Failed to find rs with bo_thans */
   ...
}

I once worked on the source code of Windows 3.0. (Not, I hasten to add, as a Microsoft employee!) There I came across a file loader that went re-entrant multiple times, and had one example of some nasty punning (just to show how clever the author was).

This mess of re-entrant code was executed with an Intel assembly jmp instruction (in the middle of C code), which went to the label "we_are_not_in_kansas_any_more_toto".


Ages ago I ran into this one:

/***************************************************************************/
/*  deep wizardry. do not touch.                                           */
/*                                                                         */
/*  no seriously.  XXXXXX I'm looking at you. If you screw with this again */
/*  I will kill you with my swingline stapler.                             */
/*                                                                         */
/* ...                                                                     */

And then went on to describe a particularly hairy algorithm.


This one was amusing for others but less so for me. I had inherited the code (which was ASP) from a developer who had himself inherited it. The first programmer had created some very hard to understand code. The second developer had added a comment as follows (names hidden to protect the not-so-innocent):

'This code was written by **************.
'I haven't a clue what it does. He hasn't a clue what it does.
'Nobody else has a clue what it does or how it does it.
'It is something to do with data but **** knows what.
'The ******* still works so please do not change this code,
'even though it is a complete pile of ****.

So why didn't I find it amusing? Well, it was ASP code for a customer's intranet.

...and it was the customer who highlighted the comment to me.

:-(


return 1; # returns 1

// TODO: Finish.

// Jay knows what's going on here, but will he remember in a year? Not very likely, this code sucks, but it works so do not change it.

This comment was posted above a huge while-if-for block... Oh, and it manipulated an object array of object arrays of object arrays of strings that could be strings or numbers, depending on at least 3 factors... (yes, I had to debug this code and change it and I wrote the comment, however I did not write the original code). ;)


From: https://github.com/zepouet/Xee-xCode-4.5/blob/master/XeePhotoshopLoader.m#L108

// At this point, I'd like to take a moment to speak to you about the Adobe PSD
// format. PSD is not a good format. PSD is not even a bad format. Calling it
// such would be an insult to other bad formats, such as PCX or JPEG. No, PSD
// is an abysmal format. Having worked on this code for several weeks now, my
// hate for PSD has grown to a raging fire that burns with the fierce passion
// of a million suns.
//
// If there are two different ways of doing something, PSD will do both, in
// different places. It will then make up three more ways no sane human would
// think of, and do those too. PSD makes inconsistency an art form. Why, for
// instance, did it suddenly decide that *these* particular chunks should be
// aligned to four bytes, and that this alignement should *not* be included in
// the size? Other chunks in other places are either unaligned, or aligned with
// the alignment included in the size. Here, though, it is not included. Either
// one of these three behaviours would be fine. A sane format would pick one.
// PSD, of course, uses all three, and more.
//
// Trying to get data out of a PSD file is like trying to find something in the
// attic of your eccentric old uncle who died in a freak freshwater shark
// attack on his 58th birthday. That last detail may not be important for the
// purposes of the simile, but at this point I am spending a lot of time
// imagining amusing fates for the people responsible for this Rube Goldberg of
// a file format.
//
// Earlier, I tried to get a hold of the latest specs for the PSD file format.
// To do this, I had to apply to them for permission to apply to them to have
// them consider sending me this sacred tome. This would have involved faxing
// them a copy of some document or other, probably signed in blood. I can only
// imagine that they make this process so difficult because they are intensely
// ashamed of having created this abomination. I was naturally not gullible
// enough to go through with this procedure, but if I had done so, I would have
// printed out every single page of the spec, and set them all on fire. Were it
// within my power, I would gather every single copy of those specs, and launch
// them on a spaceship directly into the sun.
//
// PSD is not my favourite file format.

On error resume next 'because nothing will ever go wrong!

Had a programmer working for me once that put "Style" comments throughout his code where he codified his internal debates about the particular implementation details and to take parting shots when he was overruled on a particular coding decision.

Examples:

'STYLE 'It's arguable which is better, but I pass the image handle rather than simply 'passing the scaling values in order to keep the calling code simpler (by a 'couple of declarations statements). Alternatively, I could pass these data 'members directly from the calling code, but that would violate encapsulation.

'STYLE 'As I have done elsewhere, I will register my offical protest (just give me the 'forms to fill out) regarding the implementation of annotation serialization as 'a property rather than a pair of Load/Save methods. Again, this is probably a 'matter of style and eminently debatable.


first line of a javascript function:

// this part is more difficult

WTF?


REM Don't delete this print statement ****** will die

The process in question was a service in some legacy code


Don't recall where I've seen these:

long time; /* know C */

and (in code to create some sort of UNIX daemon):

/* Be a real daemon: fork myself and kill my parent */

I had to add this one to our old datatable-driven rules engine before I decided to replace it with a scripting language.

        /************************************************************
        *                                                           *
        *  .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
        *   |                     ______                     |      *
        *   |                  .-"      "-.                  |      *
        *   |                 /            \                 |      *
        *   |     _          |              |          _     |      *
        *   |    ( \         |,  .-.  .-.  ,|         / )    |      *
        *   |     > "=._     | )(__/  \__)( |     _.=" <     |      *
        *   |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
        *   |           "=._"(_     ^^     _)"_.="           |      *
        *   |               "=\__|IIIIII|__/="               |      *
        *   |              _.="| \IIIIII/ |"=._              |      *
        *   |    _     _.="_.="\          /"=._"=._     _    |      *
        *   |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
        *   |    > _.="                            "=._ <    |      *
        *   |   (_/                                    \_)   |      *
        *   |                                                |      *
        *   '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
        *                                                           *
        *      LASCIATE OGNI SPERANZA, VOI CH'ENTRATE               *
        *************************************************************/

Stating the obvious?

/** Logger */
private Logger logger = Logger.getLogger();

Nice one in VB.NET that I ran into this morning, got a chuckle ...

''' <summary>
''' Represents an exception that was logged.  Since System.Exception implements IDictionary, it can't be
''' serialized, so I had to write this.  Pretty fucking stupid thing to have to do, System.Exception should
''' be serializable right out of the box, IMHO.
''' </summary>
''' <remarks></remarks>
Public Class LogException

// Whoever put this here is an idiot...this doesn't work at all !

But the code is still there...


//I am not sure why this works but it fixes the problem. 

This was before a set of code that technically did fix the problem it was meant to but broke 3 other things....


    /* Mark: If there's one thing you learn from this code, it is this...
   Never, ever fly Air France.  Their customer service is absolutely
   the worst.  I've never heard the words "That's not my problem" as 
   many times as I have from their staff -- It should, without doubt
   be their corporate motto if it isn't already.  Don't bother giving 
   them business because you're just a pain in their side and they
   will be sure to let you know the first time you speak to them.

   If you ever want to make me happy just tell me that you, too, will
   never fly Air France again either (in spite of their excellent
   cuisine). 

   Update by oej: The merger with KLM has transferred this
   behaviour to KLM as well. 
   Don't bother giving them business either...

   Only if you want to travel randomly without luggage, you
   might pick either of them.
   */

//This code sucks, you know it and I know it.  
//Move on and call me an idiot later.

'Do not optimize these next two lines. Compiler bugs lurk.

And they did. Compacting the variable into the expression on the second line resulted in jumping into the middle of the heap and trying to execute data.


//Maybe you should make anyone knows your code's purpose. 

// TODO - Comment this function

Not really a comment:

DvLog::Log("This silly log message fixes a PSCRIPT5.DLL gpf when printing to Adobe.");

Sad thing is that without the comment, PSCRIPT5.DLL really did blow up ...


else
{
    //error situation
}

From the source code of the UNIX flavor of the Netscape web browser, circa 1997:

/* HP-UX sucks wet farts from dead pigeons' asses */

Such pearls were unfortunately removed before Moz went open-source ...


Back around the time the Hitchhiker's Guide game was new, I had a case where I was testing whether something was scrollable and whether the user was trying to scroll, in a language that restricted variable length. So:

if (scroll and noScroll) # or tea and no tea

Something I saw in a .h file years ago.

// It may be a hack, but it works.

//Visual Studio Bug Workaround:
//http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101677

//To fix 'CJumpToHelper::GetInstance()' : undeclared identifier compiler errors, change the number lines below
//until the file compiles correctly. (This needs to be done anytime a change is made to this file)

    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines

See this one:

'On Error Goto Hell.

I like some of the comments in the GNU binutils. This one is from BFD som.c:

/* You'll never believe all this is necessary to handle relocations
   for function calls.  Having to compute and pack the argument
   relocation bits is the real nightmare.

   If you're interested in how this works, just forget it.  You really
   do not want to know about this braindamage.  */

This one too:

/* Don't ask about these magic sequences.  I took them straight
   from gas-1.36 which took them from the a.out man page.  */

...

/* Keep track of exactly where we are within a particular
   space.  This is necessary as the braindamaged HPUX
   loader will create holes between subspaces *and*
   subspace alignments are *NOT* preserved.  What a crock.  */

Another one:

/* We will NOT put a fucking timestamp in the header here. Every
   time you put it back, I will come in and take it out again. ... */

From gas:

/* Yes this is ugly (storing the broken_word pointer
   in the symbol slot).  Still, this whole chunk of
   code is ugly, and I don't feel like doing anything
   about it.  Think of it as stubbornness in action.  */

/* This is O(scary), but seems quick enough in practice. */ 

followed by four nested for-loops


My favorite is from the late, great Paul DiLascia:

// Author: If this code works, it was written by Paul DiLascia. If not then I don't know who wrote it.


I just found this in some legacy code..

'CANNOT JUST QUIT!

//  If you delete the credits, I will fucking kill you.

found in a joomla module.


on leaving my last job I embedded some ascii art into the source...


                                      ,_-=(!7(7/zs_.             
                                   .='  ' .`/,/!(=)Zm.           
                     .._,,._..  ,-`- `,\ ` -` -`\\7//WW.         
                ,v=~/.-,-\- -!|V-s.)iT-|s|\-.'   `///mK%.        
              v!`i!-.e]-g`bT/i(/[=.Z/m)K(YNYi..   /-]i44M.       
            v`/,`|v]-DvLcfZ/eV/iDLN\D/ZK@%8W[Z..   `/d!Z8m       
           //,c\(2(X/NYNY8]ZZ/bZd\()/\7WY%WKKW)   -'|(][%4.      
         ,\\i\c(e)WX@WKKZKDKWMZ8(b5/ZK8]Z7%ffVM,   -.Y!bNMi      
         /-iit5N)KWG%%8%%%%W8%ZWM(8YZvD)XN(@.  [   \]!/GXW[      
        / ))G8\NMN%W%%%%%%%%%%8KK@WZKYK*ZG5KMi,-   vi[NZGM[      
       i\!(44Y8K%8%%%**~YZYZ@%%%%%4KWZ/PKN)ZDZ7   c=//WZK%!      
      ,\v\YtMZW8W%%f`,`.t/bNZZK%%W%%ZXb*K(K5DZ   -c\\/KM48       
      -|c5PbM4DDW%f  v./c\[tMY8W%PMW%D@KW)Gbf   -/(=ZZKM8[       
      2(N8YXWK85@K   -'c|K4/KKK%@  V%@@WD8e~  .//ct)8ZK%8`       
      =)b%]Nd)@KM[  !'\cG!iWYK%%|   !M@KZf    -c\))ZDKW%`        
      YYKWZGNM4/Pb  '-VscP4]b@W%     'Mf`   -L\///KM(%W!         
      !KKW4ZK/W7)Z. '/cttbY)DKW%     -`  .',\v)K(5KW%%f          
      'W)KWKZZg)Z2/,!/L(-DYYb54%  ,,`, -\-/v(((KK5WW%f           
       \M4NDDKZZ(e!/\7vNTtZd)8\Mi!\-,-/i-v((tKNGN%W%%            
       'M8M88(Zd))///((|D\tDY\\KK-`/-i(=)KtNNN@W%%%@%[           
        !8%@KW5KKN4///s(\Pd!ROBY8/=2(/4ZdzKD%K%%%M8@%%           
         '%%%W%dGNtPK(c\/2\[Z(ttNYZ2NZW8W8K%%%%YKM%M%%.          
           *%%W%GW5@/%!e]_tZdY()v)ZXMZW%W%%%*5Y]K%ZK%8[          
            '*%%%%8%8WK\)[/ZmZ/Zi]!/M%%%%@f\ \Y/NNMK%%!          
              'VM%%%%W%WN5Z/Gt5/b)((cV@f`  - |cZbMKW%%|          
                 'V*M%%%WZ/ZG\t5((+)L\'-,,/  -)X(NWW%%           
                      `~`MZ/DZGNZG5(((\,    ,t\\Z)KW%@           
                         'M8K%8GN8\5(5///]i!v\K)85W%%f           
                           YWWKKKKWZ8G54X/GGMeK@WM8%@            
                            !M8%8%48WG@KWYbW%WWW%%%@             
                              VM%WKWK%8K%%8WWWW%%%@`             
                                ~*%%%%%%W%%%%%%%@~               
                                   ~*MM%%%%%%@f`                 
                                       '''''                     


Case 1:
   ...
   break;
   ...
//I don't want do do this but [my coworker] says it's part of the code standard
default:
   break;

I just found this one in a custom Linq provider for .net:

//select is a royal pain in the ass where 
//the parameter passed to CreateQuery isn't actually the one that goes in the call
//requiring this workaround.  Not sure how straight Linq to Objects does it.

And this one

//expressions have to be compiled in order to work with the method call on 
//straight Enumerable somehow, LINQ to objects itself magically does this.  
//Reflector shows a mess, so I (Aaron) invented my own way.  God love unit tests!

And i just found this one as well... it just gets better

  //ok, this is a hairy, dirty, and nasty piece of code
  //the alternatives are substantially worse than this though
  //i.e. when you do your own provider, LINQ assumes that
  //you are going to implement your own expression tree visitor and
  //do it all yourself.  Frankly, I still have xmas shopping to do
  //and I really don't want us to be foobared when we get
  //even more extension methods added to LINQ
  //therefore, we are pulling execute based on taking the calling the 
  //standard execute on enumerable, but using our own class
  //
  //optimization can occur from here on an as needed basis, that is
  //check for the value of mex.Method.Name, and write a handler for
  //that method
  //
  //also, it may not be a bad idea to rather than do this reflection 
  //each and every time somehow cache the reflected methodinfos and do 
  //lookups that way that said, we need a complete red/green/refactor 
  //cycle here before I am touching that one

And this one

//Compile that mutherf-ker, invoke it, and get the resulting hash

// I don't know why I need this, but it stops the people being upside-down

x = -x;

// (c) 2000 Applied Magic, Inc.
// Unauthorized use punishable by torture, mutilation, and vivisection.

Ah, I always loved that one...



A funny typo that was strangely appropriate:

assert(0); // should never shit this point


// fix for groupid > 9 
// if groupid ever gets to 100 everything will break (again)

if (groupid < 10) {
groupid = "0" + groupid;
}

From a google code project:

# This job would be great if it wasn't for the fucking customers.

Something I saw in a COBOL program that paralyzed me with fear

* All comments pertain to the lines which follow.

What does this mean?

  1. Someone was so uncomfortable with commenting that they had to write a meta-comment?

  2. Someone was in the habit of putting comments below the relevant code and had been told to put comments above? How did that happen?


This whole function is pretty great (from the Linux sunhme.c driver, for the network card nicknamed the Happy Meal by Sun. Because the card that came before that was the "Big MAC". Get it? Get it?)

static void happy_meal_tcvr_write(struct happy_meal *hp,
                              void __iomem *tregs, int reg,
                              unsigned short value)
{
    int tries = TCVR_WRITE_TRIES;

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

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

    /* Would you like fries with that? */
    hme_write32(hp, tregs + TCVR_FRAME,
                (FRAME_WRITE | (hp->paddr << 23) |
                 ((reg & 0xff) << 18) | (value & 0xffff)));
    while (!(hme_read32(hp, tregs + TCVR_FRAME) & 0x10000) && --tries)
            udelay(20);

    /* Anything else? */
    if (!tries)
            printk(KERN_ERR "happy meal: Aieee, transceiver MIF write bolixed\n");

    /* Fifty-two cents is your change, have a nice day. */

}


in a completely uncommented 2000 line method

{ 
  { 
    while (.. ){ 
      if (..){
          }
      for (.. ){ 
          }
         .... (just putting in the control flow here, imagine another few hundred ifs)
      if(..)   {
            if(..)     {
                   if(..)   {
                ...
                (another few hundred brackets)
                       }
                  }
         } //endif

(I actually grepped out all the brackets one day just to see how bad it was, and, sans formatting, got this:

{{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}    {{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}

The endif showed up around line 800)


Fresh out of college, I was eager to get my hands dirty. My first task was... "comment this code for me".

Fucker.

After awhile I got bored with it...

// this function doesn't actually calculated the profit, like it says --it really signals the mothership orbiting saturn that the planet is ripe for takeover

[later]

// I don't think anyone is going to read this

[various permutations on that last one]

/* Halley's comment */

//marco 2007.1.23
//I didn't do it

On the linux 1.0 kernel scheduler (sched.c):

Dijkstra probably hates me.

/*
 *  'schedule()' is the scheduler function. It's a very simple and nice
 * scheduler: it's not perfect, but certainly works for most things.
 * The one thing you might take a look at is the signal-handler code here.
 *
 *   NOTE!!  Task 0 is the 'idle' task, which gets called when no other
 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
 * information in task[0] is never used.
 *
 * The "confuse_gcc" goto is used only to get better assembly code..
 * Dijkstra probably hates me.
 */
asmlinkage void schedule(void)

(...)


// need a coffee to fix this.

Top of sqlite source files:

/*

** The author disclaims copyright to this source code.  In place of             
** a legal notice, here is a blessing:                                          
**                                                                              
**    May you do good and not evil.                                             
**    May you find forgiveness for yourself and forgive others.                 
**    May you share freely, never taking more than you give.

*/

Exception up = new Exception("Something is really wrong.");
throw up;  //ha ha

Found in the main trigger code for transactions in an OLTP database:

-- This line negates the @inverseqty, which is the
-- negative of the @insertedquantity.  This works through the
-- magic of the trigger.  In fact, this code is a lot like
-- the bermuda triangle!
@negquantity = -1 * @inverseqty

[onload_1;block=begin;when 1=0]

Some of the techinques in this template are rather obscure, just trust me, they need to be there.
OTOH a better sollution would be to create a few seperate templates and pick one in the php-script...

[onload_1;block=end]

// repopulate, slight hax (or strong assumptions :P) below

// The ratio of a circle's circumference to its diameter.  Remember to change
// this to 3.0 if you move to a site in Indiana.

#define Pi                                      3.1415927

[onload_1;block=begin;when 1=0]

Some of the techinques in this template are rather obscure, just trust me, they need to be there.
OTOH a better sollution would be to create a few seperate templates and pick one in the php-script...

[onload_1;block=end]

in a completely uncommented 2000 line method

{ 
  { 
    while (.. ){ 
      if (..){
          }
      for (.. ){ 
          }
         .... (just putting in the control flow here, imagine another few hundred ifs)
      if(..)   {
            if(..)     {
                   if(..)   {
                ...
                (another few hundred brackets)
                       }
                  }
         } //endif

(I actually grepped out all the brackets one day just to see how bad it was, and, sans formatting, got this:

{{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}    {{{{}}{}{}{}{}}{{}{{}{}{}{}{}{}{{}{}}{}{}{{}{}{}{}{}{}{}{}{}{}{}{{}}}{{}{{}}{{{}}}{{}{}{}{}{}{}{}{{}}{}{{{}}{}{{}{}}{{{}}{}{}{}{}}{{}}}{}{{}{}{}{{}{{}}{}}{{}}}{{}}{{}}{{}}{}{{}}{{}}{{}}{{}{}{}}{}{}{{{}}{{}}}{}{}{}{}}{{{}{{}{}{}{{}{}{}{}{}{}}{}}{{}}{{}{}}}{{}}{{}}}{{}}{{}}{}{}{}{}{{}}{{}{}{}{}}}}{}{}}{{}{{{}{}{}{}}}}{{}{{{}}}}{{}{{{}{{}}{}{{}}{}{{}{}}{{}}{}{{}}}{{}}}}{{}{}{}{}{}{{{}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}{}{{}}{}}}{}}{{}}{{}{}}{{}{{}{{}}}}{{{}{{{}}}}}{{{{{}}}}}{}{}{}{{{{}}}{}{}}{{}{{}}}}

The endif showed up around line 800)


// I dedicate all this code, all my work, to my wife, Darlene, who will 
// have to support me and our three children and the dog once it gets 
// released into the public.

# To understand recursion, see the bottom of this file 

At the bottom of the file:

# To understand recursion, see the top of this file

// The following strings are meant to be funny.  Do not edit these strings
// unless you are funny, too.  If you don't know if you're funny, you're
// not funny.  If fewer than 2 people unrelated to you have told you that 
// you're funny, you're not funny.

//Code sanitized to protect the foolish.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Web.UI;

namespace Mobile.Web.Control
{
    /// <summary>
    /// Class used to work around Richard being a fucking idiot
    /// </summary>
    /// <remarks>
    /// The point of this is to work around his poor design so that paging will 
    /// work on a mobile control. The main problem is the BindCompany() method, 
    /// which he hoped would be able to do everything. I hope he dies.
    /// </remarks>
    public abstract class RichardIsAFuckingIdiotControl : MobileBaseControl, ICompanyProfileControl
    {
        protected abstract Pager Pager { get; }

        public void BindCompany(int companyId) { }

        public RichardIsAFuckingIdiotControl()
        {
            MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity();
        }

        private void MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity()
        {
            // Make sure nobody is actually using that fucking bindcompany method
            MethodInfo m = this.GetType().GetMethod("BindCompany", BindingFlags.DeclaredOnly | 
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (m != null)
            {
                throw new RichardIsAFuckingIdiotException("No!! Don't use the fucking BindCompany method!!!");
            }
            // P.S. this method is a joke ... the rest of the class is fucking serious
        }

        /// <summary>
        /// This returns true if this control is supposed to be doing anything
        /// at all for this request. Richard thought it was a good idea to load
        /// the entire website during every request and have things turn themselves
        /// off. He also thought bandanas and aviator sunglasses were "fuckin' 
        /// gnarly, dude."
        /// </summary>
        protected bool IsThisTheRightPageImNotSureBecauseRichardIsDumb()
        {
            return Request.QueryString["Section"] == this.MenuItemKey;
        }

        protected override void OnLoad(EventArgs e)
        {
            if (IsThisTheRightPageImNotSureBecauseRichardIsDumb())
            {
                Page.LoadComplete += new EventHandler(Page_LoadComplete);
                Pager.RowCount = GetRowCountBecauseRichardIsDumb();
            }
            base.OnLoad(e);
        }

        protected abstract int GetRowCountBecauseRichardIsDumb();
        protected abstract void BindDataBecauseRichardIsDumb();

        void Page_LoadComplete(object sender, EventArgs e)
        {
            BindDataBecauseRichardIsDumb();
        }

        // the rest of his reduh-ndant interface members
        public abstract string MenuItemName { get; set; }
        public abstract string MenuItemKey { get; set; }
        public abstract bool IsCapable(CapabilityCheck checker, int companyId);
        public abstract bool ShowInMenu { get; }
        public virtual Control CreateHeaderControl()
        {
            return null;
        }
    }
}

Update: The original author of the code has outed himself so I must give credit where it is due. Dan McKinley left the company I was with shortly after I started, and he talks more about the code, explaining some background and a few more "WTF's" that 'Richard' wrote.


} catch (PartInitException pie) {
    // Mmm... pie

I have used this one on more than one occasion, when I've done some kind of non-obvious simplification to a mathematical formula that I don't feel like documenting:

//this formula is right, work out the math yourself if you don't believe me

Seen in some COBOL back in 1983:

   C   I don't know what this next bit does so I'll jump around it
       GOTO DONE.

# dont question, i just felt like throwing some globals in
# this is actually quite pointless as youll soon see

later in the code

#draw the circles (complicated)...dont question

even later...

# complicated process of drawing the circles in a
# somewhat symmetrical, 3-d pattern
# dont question again

and even later...

# will determine if user clicks on die
# i determined these values...dont worry about them

Classic ASP:

'Is it worth it, let me work it'
'I put my thing down, flip it and reverse it'
'Ti esrever dna ti pilf, nwod gniht ym tup I'

NextIP = StrReverse(UserRecordset.Fields.Item(0))

// The ratio of a circle's circumference to its diameter.  Remember to change
// this to 3.0 if you move to a site in Indiana.

#define Pi                                      3.1415927

catch (Exception ex)
{ 
    // just die already.
}

I am particularly guilty of this, embedding non-constructive comments, code poetry and little jokes into most of my projects (although I usually have enough sense to remove anything directly offensive before releasing the code). Here's one I'm particulary fond of, placed far, far down a poorly-designed 'God Object':

/**
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
*/

I'M SORRY!!!! I just couldn't help myself.....!

And another, which I'll admit I haven't actually released into the wild, even though I am very tempted to do so in one of my less intuitive classes:

// 
// Dear maintainer:
// 
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
// 
// total_hours_wasted_here = 42
// 

// If I from the future read this I'll back in time and kill myself. 

Just found this one in some of our PHP code

$s=2; // chicken and bacon wrap for lunch

How useful, luckily $s was self explanatory


A funny typo that was strangely appropriate:

assert(0); // should never shit this point


Linux Comments

There are heaps of good ones here ...

These are all comments in linux

http://lwn.net/1998/1015/a/f-word.html

My Favourites:

./arch/sparc/kernel/ptrace.c
/* Fuck me gently with a chainsaw... */

./drivers/scsi/qlogicpti.h
/* Am I fucking pedantic or what? */

public static final void attachListener(Object listener) {

/* ======================= */

// This does nothing, continue searching

/* ======================= */

...

painful with listeners!


I have used this one on more than one occasion, when I've done some kind of non-obvious simplification to a mathematical formula that I don't feel like documenting:

//this formula is right, work out the math yourself if you don't believe me

In an LKM:

/*
* Dear Richard Stallman,
*
* This one's for you.
*
* Sincerely,
* Me
*
*/
MODULE_LICENSE( "GPL" );

Not in code, but in a related bugtracking system:

This can't be a bug in my code. I coded it very carefully.


# absolutely foul heuristic code.
# ..it's dirty, but you want it.

and:

# VERY USEFUL DEBUGGING AID, for when the above all goes pearshaped:

/*
 * You may think you know what the following code does.
 * But you dont. Trust me.
 * Fiddle with it, and youll spend many a sleepless
 * night cursing the moment you thought youd be clever
 * enough to "optimize" the code below.
 * Now close this file and go play with something else.
 */ 

Classics from the old netscape mozilla code. Personally I like

just can't fuck around. Oh, also moving memory would doom us anyway, and it'll all just be too damn hard to figure out. So, I give up, the Mac just completely utterly sucks complete rocks

but there are a lot of other fun ones.


// Jay knows what's going on here, but will he remember in a year? Not very likely, this code sucks, but it works so do not change it.

This comment was posted above a huge while-if-for block... Oh, and it manipulated an object array of object arrays of object arrays of strings that could be strings or numbers, depending on at least 3 factors... (yes, I had to debug this code and change it and I wrote the comment, however I did not write the original code). ;)


I often found this one

// fix it!

This is one from my own code, but it's still really funny, and I figure I might as well put it up because it's in public SVN.

// These were orginally up and down. When it was clear the names were
// inapplicable, they were renamed to retain the joke.
// Sorry if you were hoping for useful variable names.
quantum strange, charm;

/*
This isn't the right way to deal with this, but today is my last day, Ron
just spilled coffee on my desk, and I'm hungry, so this will have to do...
*/

return 12; // 12 is my lucky number

DataRow[] foundrows = FilterCalendarEntriesBecauseDotNETIsFuckedUp(tbtemp,CalDate);

Not a comment but an interesting function name


I believe in JBoss somewhere there was a line that read

return null; //Not really null

I always liked that line.


// If this comment is removed the program will blow up 

// StupidCompilerDontInline(SCDI), in the test project where
// allcode was in a single cpp the compiler had inlined nearly
// everything which lead to nice stackoverflow.
// To prevent this the metods are made virtual
#define SCDI virtual

Back when I worked for Reuters there was a comment in one of our feed handlers that made some people think the Almighty was helping us out...

// Jesus told me to skip to the end of the message here

We found out later that there was a Latin-American contact named Jesus (HeyZus).


While working on some websites I found this at the start of the embedded JS:

I feel so dirty doing this but the guy wanted it in .NET


// Caveat implementor

I believe in JBoss somewhere there was a line that read

return null; //Not really null

I always liked that line.


Somebody complained that the "best" comment was bringing up the worst comments. IMHO, they're funnier, and so "better", but here's the honest best comment I've ever read:

/*
Major subtleties ahead:  Most hash schemes depend on having a "good" hash
function, in the sense of simulating randomness.  Python doesn't:  its most
important hash functions (for strings and ints) are very regular in common
cases:

>>> map(hash, (0, 1, 2, 3))
[0, 1, 2, 3]
>>> map(hash, ("namea", "nameb", "namec", "named"))
[-1658398457, -1658398460, -1658398459, -1658398462]
>>>

This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints.
The same is approximately true when keys are "consecutive" strings.  So this
gives better-than-random behavior in common cases, and that's very desirable.

OTOH, when collisions occur, the tendency to fill contiguous slices of the
hash table makes a good collision resolution strategy crucial.  Taking only
the last i bits of the hash code is also vulnerable:  for example, consider
[i << 16 for i in range(20000)] as a set of keys.  Since ints are their own
hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
hash code are all 0:  they *all* map to the same table index.

But catering to unusual cases should not slow the usual ones, so we just take
the last i bits anyway.  It's up to collision resolution to do the rest.  If
we *usually* find the key we're looking for on the first try (and, it turns
out, we usually do -- the table load factor is kept under 2/3, so the odds
are solidly in our favor), then it makes best sense to keep the initial index
computation dirt cheap.

The first half of collision resolution is to visit table indices via this
recurrence:

    j = ((5*j) + 1) mod 2**i

For any initial j in range(2**i), repeating that 2**i times generates each
int in range(2**i) exactly once (see any text on random-number generation for
proof).  By itself, this doesn't help much:  like linear probing (setting
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
order.  This would be bad, except that's not the only thing we do, and it's
actually *good* in the common cases where hash keys are consecutive.  In an
example that's really too small to make this entirely clear, for a table of
size 2**3 the order of indices is:

    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]

If two things come in at index 5, the first place we look after is index 2,
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
Linear probing is deadly in this case because there the fixed probe order
is the *same* as the order consecutive keys are likely to arrive.  But it's
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
and certain that consecutive hash codes do not.

The other half of the strategy is to get the other bits of the hash code
into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
full hash code, and changing the recurrence to:

    j = (5*j) + 1 + perturb;
    perturb >>= PERTURB_SHIFT;
    use j % 2**i as the next table index;

Now the probe sequence depends (eventually) on every bit in the hash code,
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
because it quickly magnifies small differences in the bits that didn't affect
the initial index.  Note that because perturb is unsigned, if the recurrence
is executed often enough perturb eventually becomes and remains 0.  At that
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
that's certain to find an empty slot eventually (since it generates every int
in range(2**i), and we make sure there's always at least one empty slot).

Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
small so that the high bits of the hash code continue to affect the probe
sequence across iterations; but you want it large so that in really bad cases
the high-order hash bits have an effect on early iterations.  5 was "the
best" in minimizing total collisions across experiments Tim Peters ran (on
both normal and pathological cases), but 4 and 6 weren't significantly worse.

Historical:  Reimer Behrends contributed the idea of using a polynomial-based
approach, using repeated multiplication by x in GF(2**n) where an irreducible
polynomial for each table size was chosen such that x was a primitive root.
Christian Tismer later extended that to use division by x instead, as an
efficient way to get the high bits of the hash code into play.  This scheme
also gave excellent collision statistics, but was more expensive:  two
if-tests were required inside the loop; computing "the next" index took about
the same number of operations but without as much potential parallelism
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
above, and then shifting perturb can be done while the table index is being
masked); and the dictobject struct required a member to hold the table's
polynomial.  In Tim's experiments the current scheme ran faster, produced
equally good collision statistics, needed less code & used less memory.

Theoretical Python 2.5 headache:  hash codes are only C "long", but
sizeof(Py_ssize_t) > sizeof(long) may be possible.  In that case, and if a
dict is genuinely huge, then only the slots directly reachable via indexing
by a C long can be the first slot in a probe sequence.  The probe sequence
will still eventually reach every slot in the table, but the collision rate
on initial probes may be much higher than this scheme was designed for.
Getting a hash code as fat as Py_ssize_t is the only real cure.  But in
practice, this probably won't make a lick of difference for many years (at
which point everyone will have terabytes of RAM on 64-bit boxes).
*/

[onload_1;block=begin;when 1=0]

Some of the techinques in this template are rather obscure, just trust me, they need to be there.
OTOH a better sollution would be to create a few seperate templates and pick one in the php-script...

[onload_1;block=end]

// No women, no children... What movie???

// somedev1 -  6/7/02 Adding temporary tracking of Login screen
// somedev2 -  5/22/07 Temporary my ass

In an LKM:

/*
* Dear Richard Stallman,
*
* This one's for you.
*
* Sincerely,
* Me
*
*/
MODULE_LICENSE( "GPL" );

A comment I added to a PHP CMS I was working on a while back.

if (/*you*/ $_GET['action']) { //celebrate

/* logic */
#ifndef TRUE
# define TRUE 1
#endif /* TRUE */
#ifndef FALSE
# define FALSE 0
#endif /* FALSE */
#define EOF_OK TRUE
#define EOF_NOT_OK FALSE

and the rest of the glorious mkentry.c at the IOCCC page. I can't keep laughing every time I read through this source.


In the middle of a few thousand line JScript file after a completely arbitrary line...

// The world is a happy place.

//If the Current Record is Getting End Dated, We should not create New History Entry. 
//We Just need to Update the Previous History Entry
//If the History is already End Dated and the New Record is now removing End Date, Then 
//We should not update the Previous History End Date. 
//We Just need to Create the New History Record Only.
//Alright.. 
//Alright.... 
//Enough Comments. Code it. :-)

Spelunking through the Hardware Abstraction Layer while working for a certain Finnish Mobile Network Equipment Manufacturer I found 100+ occurrences of the Finnish word "puukko".

A 'puukko' is an all purpose knife that every Finn has in their toolbox or around the house. It is used for everything from pealing potatoes to performing computer repairs (my observations). I believe in this context it is the Finnish equivalent of the word 'Hack'.

My Finnish colleagues denied this and said it meant something more like 'surgical procedure/intervention'... and I almost believed them until I found the comment:

/* Perkele ISO Puukko! */ -> Fucking Big Hack!

//open lid


//take sh!t


//close lid

Comments for a File open, data dump, file close...


//This code sucks, you know it and I know it.  
//Move on and call me an idiot later.

// insert comment here

i++; // increment variable i

virgin = 0;     /* you're not a virgin anymore, sweety */

When writing some Perl years ago, I added these comments at the top and bottom:

# <magic type="voodoo">

...

# </magic>

The next guy to look at it wasn't so hot at Perl, and spent a while searching documentation for what 'magic' and 'voodoo' did. Since then, I've tried to add more helpful comments...


// sometimes I believe compiler ignores all my comments

i++; // increment variable i

// Okay, let's do the loop, yeah come on baby let's do the loop
// and it goes like this ...

Back when I worked for Reuters there was a comment in one of our feed handlers that made some people think the Almighty was helping us out...

// Jesus told me to skip to the end of the message here

We found out later that there was a Latin-American contact named Jesus (HeyZus).


Comment in our Enterprise Class system used for Government purposes

'RH 5/24/06 burn me if this dosn't work.. :)

Good ole RH.....company Prez/Lead Developer


A few from the Linux kernel:

/* Sun, you just can't beat me, you just can't.  Stop trying,
* give up.  I'm serious, I am going to kick the living shit
* out of you, game over, lights out.
*/

-

/* 2,191 lines of complete and utter shit coming up... */

-

#if 0 /* XXX No fucking way dude... */

Somebody complained that the "best" comment was bringing up the worst comments. IMHO, they're funnier, and so "better", but here's the honest best comment I've ever read:

/*
Major subtleties ahead:  Most hash schemes depend on having a "good" hash
function, in the sense of simulating randomness.  Python doesn't:  its most
important hash functions (for strings and ints) are very regular in common
cases:

>>> map(hash, (0, 1, 2, 3))
[0, 1, 2, 3]
>>> map(hash, ("namea", "nameb", "namec", "named"))
[-1658398457, -1658398460, -1658398459, -1658398462]
>>>

This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints.
The same is approximately true when keys are "consecutive" strings.  So this
gives better-than-random behavior in common cases, and that's very desirable.

OTOH, when collisions occur, the tendency to fill contiguous slices of the
hash table makes a good collision resolution strategy crucial.  Taking only
the last i bits of the hash code is also vulnerable:  for example, consider
[i << 16 for i in range(20000)] as a set of keys.  Since ints are their own
hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
hash code are all 0:  they *all* map to the same table index.

But catering to unusual cases should not slow the usual ones, so we just take
the last i bits anyway.  It's up to collision resolution to do the rest.  If
we *usually* find the key we're looking for on the first try (and, it turns
out, we usually do -- the table load factor is kept under 2/3, so the odds
are solidly in our favor), then it makes best sense to keep the initial index
computation dirt cheap.

The first half of collision resolution is to visit table indices via this
recurrence:

    j = ((5*j) + 1) mod 2**i

For any initial j in range(2**i), repeating that 2**i times generates each
int in range(2**i) exactly once (see any text on random-number generation for
proof).  By itself, this doesn't help much:  like linear probing (setting
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
order.  This would be bad, except that's not the only thing we do, and it's
actually *good* in the common cases where hash keys are consecutive.  In an
example that's really too small to make this entirely clear, for a table of
size 2**3 the order of indices is:

    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]

If two things come in at index 5, the first place we look after is index 2,
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
Linear probing is deadly in this case because there the fixed probe order
is the *same* as the order consecutive keys are likely to arrive.  But it's
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
and certain that consecutive hash codes do not.

The other half of the strategy is to get the other bits of the hash code
into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
full hash code, and changing the recurrence to:

    j = (5*j) + 1 + perturb;
    perturb >>= PERTURB_SHIFT;
    use j % 2**i as the next table index;

Now the probe sequence depends (eventually) on every bit in the hash code,
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
because it quickly magnifies small differences in the bits that didn't affect
the initial index.  Note that because perturb is unsigned, if the recurrence
is executed often enough perturb eventually becomes and remains 0.  At that
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
that's certain to find an empty slot eventually (since it generates every int
in range(2**i), and we make sure there's always at least one empty slot).

Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
small so that the high bits of the hash code continue to affect the probe
sequence across iterations; but you want it large so that in really bad cases
the high-order hash bits have an effect on early iterations.  5 was "the
best" in minimizing total collisions across experiments Tim Peters ran (on
both normal and pathological cases), but 4 and 6 weren't significantly worse.

Historical:  Reimer Behrends contributed the idea of using a polynomial-based
approach, using repeated multiplication by x in GF(2**n) where an irreducible
polynomial for each table size was chosen such that x was a primitive root.
Christian Tismer later extended that to use division by x instead, as an
efficient way to get the high bits of the hash code into play.  This scheme
also gave excellent collision statistics, but was more expensive:  two
if-tests were required inside the loop; computing "the next" index took about
the same number of operations but without as much potential parallelism
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
above, and then shifting perturb can be done while the table index is being
masked); and the dictobject struct required a member to hold the table's
polynomial.  In Tim's experiments the current scheme ran faster, produced
equally good collision statistics, needed less code & used less memory.

Theoretical Python 2.5 headache:  hash codes are only C "long", but
sizeof(Py_ssize_t) > sizeof(long) may be possible.  In that case, and if a
dict is genuinely huge, then only the slots directly reachable via indexing
by a C long can be the first slot in a probe sequence.  The probe sequence
will still eventually reach every slot in the table, but the collision rate
on initial probes may be much higher than this scheme was designed for.
Getting a hash code as fat as Py_ssize_t is the only real cure.  But in
practice, this probably won't make a lick of difference for many years (at
which point everyone will have terabytes of RAM on 64-bit boxes).
*/

When I'm commenting out chunks of code that I THINK are no longer useful, but I might be wrong about (hence not deleting them) I will sometimes preface them with

// Wilted celery?

The idea being that this is like celery that is wilted, but you put it back in the fridge anyway. I just know that 10 years from now someone else will find these comments and say WTF?


I inherited a project that haad been delivered to the customer without any UAT. It was dropkicked over the fence and the money requested.

First time they used it, it naturally blew up. It was an interposing library that overrode any system calls that took a file name as a parameter rather than a file descriptor.

Many system calls had been forgotten.

When I got onboard the code was laced with such gems as:

/* core dumps around here but this is hardly ever called */

and

/* don't know why this works but it seeems to be ok */

Oh, and there were no unit tests. A colleague had started to add the missing system calls and unit tests.

And the bastards who'd written the code were still in the team and didn't care at all about the garbage that had been delivered!


What do you think you're doing, Dave?

public int hashCode() {
//sucks, but what're you gonna do

/*
int hash = 7;
for (int i = 0; i < array.length; i++)
    hash = hash * 31 * (null == array[i] ? 0 : array[i].hashCode());
return hash;
*/

return 0;
}

//open lid


//take sh!t


//close lid

Comments for a File open, data dump, file close...


first line of a javascript function:

// this part is more difficult

WTF?


on js code:

// hack for ie browser (assuming that ie is a browser)

//ALL YOUR BASE ARE BELONG TO US

...it made my boss think someone had hacked in. He didn't know the joke.


This comment is from an old project that i had to debug:

//Haleluya i can go home!

'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
'
'  NOTE: DON'T SCREW WITH THIS CODE UNLESS YOU REALLY UNDERSTAND IT!
'
'""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

/*
* Wirzenius wrote this portably, Torvalds fucked it up :-)
*/

I once worked on a project where I found this comment:

// Cabbage fart?

I have no idea what it was supposed to mean. Just glad my cube wasn't next to whoever wrote it.


Something I saw in a COBOL program that paralyzed me with fear

* All comments pertain to the lines which follow.

What does this mean?

  1. Someone was so uncomfortable with commenting that they had to write a meta-comment?

  2. Someone was in the habit of putting comments below the relevant code and had been told to put comments above? How did that happen?


-- Beyond this point, there'll be dragons

I find it more pleasingly illustrative with the longer saying ^^


Found in the JUnit API:

/**
 * ...as the moon sets over the early morning Merlin, Oregon
 * mountains, our intrepid adventurers type...
 */
public Test createTest(Class theClass, String name) {
    ...
}

i tell a mentee to do at least SOME exception handling. This is what i get in return around every db call....

Catch (Exception e) {
    //eat it
}

/* My lawyer told me not to reveal */

From the leaked Win2K source code:

// The magnitude of this hack compares favorably with that of the national debt.


try {

} finally { // should never happen 

}

The original Doom had an engine with static walls that could not move; the result was that all doors opened vertically; nothing could ever move horizontally. I burst out laughing when, after the source code was released, I was looking through the code and saw this in the source file for handling doors, at the start of a big block of commented-out code:

// UNUSED
// Separate into p_slidoor.c?

#if 0           // ABANDONED TO THE MISTS OF TIME!!!
//
// EV_SlidingDoor : slide a door horizontally
// (animate midtexture, then set noblocking line)
//

public GetRandomNumber()
{
    // Chosen by a fairly rolen dice
    return 12;
}

// but the "real" solution is much more complicated

from jpgraph


I saw this comment on someone's code:

// This comment is self explanatory.

I guess he meant to say 'variable' but the mistake made one funny comment... Think of the circular logic here, and the futility of writing it.


First at the beginning of an Update to a huge object:

/*General note to all who tread in the <ObjectName>() code...
 * The SetOriginals() method from the BaseEntity class should be called (and only called) right after the Get() method
 * call as seen above.  Calling the SetOriginals method elsewhere will result in bugs and all kinds of other nasty suprises.
 */

Then after some 200 lines of logic to update the object:

//Attempt to explain this confusing mess of code:
//First time you save an actual absence this is what happens:
//0. The first save saves to the <TableName> table (among other things). (Fig. A)
//1. The <CalculationMethod> method is called next which inserts to the <OtherTableName> table. 
//(This is the table that keeps track of credits to the case.) (Fig. B)
//2. So then you have to call <UpdateCalculations> to move the <TableName> records to the <ThirdTableName> table. (Fig. C)
//3. Then you go back and run calculations since you have the debits table (<ThirdTableName>) populated. (Fig D.)
//4. Then a final save to save the calculations back to the case. (Fig. E)
//Yeah, I know what you're thinking:  this sucks. 10/01/07 XXX

And the developer was right... This sucked HARD!


It's not strictly speaking a comment, but...

It was the mid-1990s and I was working on a big migration: small software vendor, big client, lots of pressure. We had a lot of shifting-goalpost stuff; the project was very hard to control. I was the key developer, but new to the system, and the other developer was the vendor's owner/founder.

After a few months of not quite making deadlines and not quite satisfying the client, the owner/founder brought on another developer, who was working remotely. (I'm gonna go out on a limb and say the new developer had lesser skills and experience than me.)

Well, the new guy made some changes in code that I'd already worked on, and then a month or two later I was back in the same area of the code, and there were variables I hadn't seen before. With names like StupidMark.

Dude, that's just not right. I mean, there's teamwork considerations, but also: in this environment, variable names can show up in runtime error messages. I'm just saying.

In my opinion at the time, the new guy's code wasn't getting us much closer to a deliverable product anyway, which made the insult sting a little more.


To protect the guilty the values have been changed

This one was left behind by a contractor who had been working on a chunk of code responsible for testing email logins. We were in disbelief so we tried it out and it was a valid login to his personal account; we double-checked the revision history and he had two check-ins that edited it: one to add the code, and the second to comment it out.

We added the artwork and left the rest alone; another dev decided it would be fun to send him emails from his future self (ala The Office) and said it took nearly two full weeks of daily emails before the login stopped working.

'    ROFL:ROFL:LOL:ROFL:ROFL
'        ______/|\____
'  L    /          [] \
' LOL===_      ROFL    \_
'  L     \_______________]
'            I      I
'        /---------------/

'TODO: REMOVE MY INFO AND REPLACE WITH USER CREDENTIALS
'Private TEST_LoginName As String = "[email protected]"
'Private TEST_Password As String = "Humsal892"
'Private TEST_Server As String = "imap.secureserver.net"

My favorite part isn't that he did it, or that he accidently left it in place for a check-in--but that when he came back across it he just commented it out rather than deleting it. We never would have looked at the original revision if we never knew it was there :-D


In the header of a code file heavily edited by everyone on the dev team:

'Avert your eyes, it may take on other forms!

Good ol' Flanders.


stop(); // Hammertime!

//There can Only Be one HIGHLAN....err..Singleton
public class SomeSingleton
{
...
}

try {
   doSomething();
} catch(err) {
   // Die quietly
   alert(err);
}

int MyFunction()
{
    // There once was a man named Dave
    int Result = 0;

    // Whose code just wouldn't behave
    MyObject *Ptr = new MyObject();

    // He left to go to a meetin'
    Result = Ptr->DoSomething();

    // And left his memory a leakin'
    return Result;
}

C++ Comment


An HORRIBLE patch for a decode (Translation by italian language):

/**
*@return the value 
*@param key: the id of the list of instruments
*@PS this function is a violation of all the laws of the 
*software engineering, 
*commons sense, highway code 
*and ONU decision about the coding.
That sh*t...
*/

Some of the very few comments in 5000+ lines of code in one file
I actually has an argument with the coder who defended his coding style...
No comment!
And there were no comments;-) (or very few)
Sadly this is production code.

offset=1;
for (i=0;i<=len;i++)
    {
    if ((i!=0)&&(i<len)) //-3
        {
        switch(mess[i])
            {
            case ETX:
            case ETB:
            case DLE:
                buf[offset]=DLE;
                offset++;
                break;
            }
        }
    buf[offset]=mess[i];
    offset++;
    }

I love the switch!

for (n=0;n<offset;n++)
{
    Sleep(TR);  //Modif A
    Sleep(T);//
    FWriteFile(hCom,buf+n,1,&dwMot,NULL);
    if (ECHO)
        FReadFile(hCom,tab,1,&dwMot,NULL);
}

and no, there are no comments explaining what "modif A" is in the header.

if (GetFileSize(hSlotFile,NULL)==3600)   //5*720

and what's 720?


On the linux 1.0 kernel scheduler (sched.c):

Dijkstra probably hates me.

/*
 *  'schedule()' is the scheduler function. It's a very simple and nice
 * scheduler: it's not perfect, but certainly works for most things.
 * The one thing you might take a look at is the signal-handler code here.
 *
 *   NOTE!!  Task 0 is the 'idle' task, which gets called when no other
 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
 * information in task[0] is never used.
 *
 * The "confuse_gcc" goto is used only to get better assembly code..
 * Dijkstra probably hates me.
 */
asmlinkage void schedule(void)

(...)


// Catching exceptions is for communists

From Mike Duncan's page on SQLite.


#ifdef TRACE
#undef TRACE     /* All your trace are belong to us. */
#endif
#define TRACE ....

Re eating one's own dogfood: We have the same term in our workplace (granted, only because I introduced it). My code is peppered with comments that say "TODO" and indicate something that ought to be done eventually, but a comment saying "DOGFOOD" (both keywords are always at the beginning of the comment, in all caps) means something that must be done before this program can be used even internally. It's a handy thing to search for, as the word "dogfood" is never going to appear in a quoted string - if it does, I can always just say "dog-food" or something - so even a case-insensitive search will come up with the right results.

Regarding zeroing the accumulator: I've done exactly the same thing when programming an Intel 80x86 (I started on the 8086 and moved up from there into the modern Pentiums). XORing a register with itself is the quickest and tightest way to clear it. Using "MOV AX,0" requires three bytes (opcode and two bytes of literal 16-bit zero), whereas "XOR AX,AX" is only two; it's even more noticeable with the 386-and-higher extended registers, where "MOV EAX,0" requires five bytes (four bytes of 32-bit zero). My C/C++ compiler always zeroes registers this way, so I'd assume it's still the best way (although I haven't studied opcode timing tables in ages, and probably both XOR reg,reg and MOV reg,imm take one clock).


-- Comment this later

That was line 2 of a 4000+ line PL/SQL procedure. And the only comment. 4 years after that procedure was developed, later still hadn't come...


I just ran across this one in a really simple test C++ program for a class in college.

I was commenting a class.

In the destructor...

// Choose! Choose the form of the Destructor!
// The choice is made! The Traveler has come!

In a GIGANTIC 800 line 'switch' statement, somewhere in the middle:

// Joe is sorry

A few hundred lines later...

// Harry is sorry too

This one, from Xee, an image browser.

    // At this point, I'd like to take a moment to speak to you about the Adobe PSD format.
    // PSD is not a good format. PSD is not even a bad format. Calling it such would be an
    // insult to other bad formats, such as PCX or JPEG. No, PSD is an abysmal format. Having
    // worked on this code for several weeks now, my hate for PSD has grown to a raging fire
    // that burns with the fierce passion of a million suns.
    // If there are two different ways of doing something, PSD will do both, in different
    // places. It will then make up three more ways no sane human would think of, and do those
    // too. PSD makes inconsistency an art form. Why, for instance, did it suddenly decide
    // that *these* particular chunks should be aligned to four bytes, and that this alignement
    // should *not* be included in the size? Other chunks in other places are either unaligned,
    // or aligned with the alignment included in the size. Here, though, it is not included.
    // Either one of these three behaviours would be fine. A sane format would pick one. PSD,
    // of course, uses all three, and more.
    // Trying to get data out of a PSD file is like trying to find something in the attic of
    // your eccentric old uncle who died in a freak freshwater shark attack on his 58th
    // birthday. That last detail may not be important for the purposes of the simile, but
    // at this point I am spending a lot of time imagining amusing fates for the people
    // responsible for this Rube Goldberg of a file format.
    // Earlier, I tried to get a hold of the latest specs for the PSD file format. To do this,
    // I had to apply to them for permission to apply to them to have them consider sending
    // me this sacred tome. This would have involved faxing them a copy of some document or
    // other, probably signed in blood. I can only imagine that they make this process so
    // difficult because they are intensely ashamed of having created this abomination. I
    // was naturally not gullible enough to go through with this procedure, but if I had done
    // so, I would have printed out every single page of the spec, and set them all on fire.
    // Were it within my power, I would gather every single copy of those specs, and launch
    // them on a spaceship directly into the sun.
    //
    // PSD is not my favourite file format.

/* Emits a 7-Hz tone for 10 seconds.
  True story: 7 Hz is the resonant frequency of a
  chicken's skull cavity. This was determined
  empirically in Australia, where a new factory
  generating 7-Hz tones was located too close to a
  chicken ranch: When the factory started up, all the
  chickens died.
  Your PC may not be able to emit a 7-Hz tone. */

main()
{
    sound(7);
    delay(10000);
    nosound();
}

(the sound function in the Turbo C version 2.0 Reference Guide)


// The following array may contain either TexturedObjects or ColoredObjects.
// I know, it sucks.

// TODO: Implement this function!

 // WARNING!!!
 // Very perversive code ahead!

... about a 20 lines of "very perversive" code ...

// Now you can call your grandmother back. ;)

// The following strings are meant to be funny.  Do not edit these strings
// unless you are funny, too.  If you don't know if you're funny, you're
// not funny.  If fewer than 2 people unrelated to you have told you that 
// you're funny, you're not funny.

There was some old javascript code, quite well written tho. Then was a comment line

// and there is where the dragon lives

followed by a function 4 people spent a day to understand what it's doing. Finally we realised it's not even used and does nothing.


In a well known commercial DOS spreadsheet application:

/* This comment was just added in order to check-in a file that was last 
checked in by [Insert Programmer FirstName] "Back-to-the-Future" [Insert 
Programmer LastName]. While testing for year 2000 problems, he accidentally 
checked-in this file while his machine clock was set forward to the year 2000. 
This meant that the source code was always newer than the object file and 
compiled every time the code was built. I'm checking this file in again to 
fix that. */

Try typing your favourite profanity into google code search, it whiles away many a dull hour. Some of my favourite examples:

/* These magic numbers are fucking stupid. */

/* Dear free software world, do you NOW see we are fucking
   things up?! This is insane! */

/* We will NOT put a fucking timestamp in the header here. Every
   time you put it back, I will come in and take it out again. */

# However, this only works if there are MULTIPLE checkboxes!
# The fucking JS DOM *changes* based on one or multiple boxes!?!?!
# Damn damn damn I hate the JavaScript DOM so damn much!!!!!!

/* TODO: this is obviously not right ... this whole fucking module
   sucks anyway */

/* FIXME: please god, when will the hurting stop? Thus function is so
   fucking broken it's not even funny. */

and my personal favourite

 # code below replaces code above - any problems?
 # yeah, it doesn't fucking work.

Once, I asked a coworker how to do something (forgot exactly what, some obscure technical calls) with our in-house framework. He said "easy, look HERE", then opens a .java file in his editor and shows me this comment in the middle of several pages of code:

// HERE

I just checked, the comment is still there in this file :)


//If only humans could leave things be.

//Please do not edit this code, 
//if you do you wont go to jail, you wont go directly to jail, 
//you wont pass go, you wont collect 200 dollars

Recompiling FreeTextBox3 for the first time in our application because we need IE8 support... And look what I've found:

// IE7 update. this is still bad code, but IE8 is probably a long way off :)

// if the resultMap size is less than or equal to zero
// then the product is added
if (resultMap.size() <= 0)

// Houston, we have a problem


{
This is a gathering place for all unit tests.
Create a TUnitTestWrapper, then call "RunAllUnitTests".

This class will create an instance of each thing to be tested, and call each of
their unit tests.

It does not really do any testing on it's own; it just gives a common place from
which to call everyone else's tests.

This way, one day, we can automate our testing with each build. [Cue laughter]
}

try {

}
catch (SQLException ex) {
    // Basically, without saying too much, you're screwed. Royally and totally.
}
catch(Exception ex)
{
    //If you thought you were screwed before, boy have I news for you!!!
}

/**
 * This run through all the guipublisherbuyRecord , the records those have
 * diff. is buytotal and prior to buy isRecommendedBillingClickedWarning flag
 * is set if priously RB ran and this time not.
 * 
 * --What?
 * 
 * @return
 * @throws AppException
 */

Nice one in VB.NET that I ran into this morning, got a chuckle ...

''' <summary>
''' Represents an exception that was logged.  Since System.Exception implements IDictionary, it can't be
''' serialized, so I had to write this.  Pretty fucking stupid thing to have to do, System.Exception should
''' be serializable right out of the box, IMHO.
''' </summary>
''' <remarks></remarks>
Public Class LogException

This is a comment of mine which I found today while refactoring some code

if( year < 100 ): year += 2000 #lol, Y2K

// human madable inconvenient. Way too sucks.

I still don't fully understand what it means, but I have found it to be very true about a lot of code.


//Code sanitized to protect the foolish.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Web.UI;

namespace Mobile.Web.Control
{
    /// <summary>
    /// Class used to work around Richard being a fucking idiot
    /// </summary>
    /// <remarks>
    /// The point of this is to work around his poor design so that paging will 
    /// work on a mobile control. The main problem is the BindCompany() method, 
    /// which he hoped would be able to do everything. I hope he dies.
    /// </remarks>
    public abstract class RichardIsAFuckingIdiotControl : MobileBaseControl, ICompanyProfileControl
    {
        protected abstract Pager Pager { get; }

        public void BindCompany(int companyId) { }

        public RichardIsAFuckingIdiotControl()
        {
            MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity();
        }

        private void MakeSureNobodyAccidentallyGetsBittenByRichardsStupidity()
        {
            // Make sure nobody is actually using that fucking bindcompany method
            MethodInfo m = this.GetType().GetMethod("BindCompany", BindingFlags.DeclaredOnly | 
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (m != null)
            {
                throw new RichardIsAFuckingIdiotException("No!! Don't use the fucking BindCompany method!!!");
            }
            // P.S. this method is a joke ... the rest of the class is fucking serious
        }

        /// <summary>
        /// This returns true if this control is supposed to be doing anything
        /// at all for this request. Richard thought it was a good idea to load
        /// the entire website during every request and have things turn themselves
        /// off. He also thought bandanas and aviator sunglasses were "fuckin' 
        /// gnarly, dude."
        /// </summary>
        protected bool IsThisTheRightPageImNotSureBecauseRichardIsDumb()
        {
            return Request.QueryString["Section"] == this.MenuItemKey;
        }

        protected override void OnLoad(EventArgs e)
        {
            if (IsThisTheRightPageImNotSureBecauseRichardIsDumb())
            {
                Page.LoadComplete += new EventHandler(Page_LoadComplete);
                Pager.RowCount = GetRowCountBecauseRichardIsDumb();
            }
            base.OnLoad(e);
        }

        protected abstract int GetRowCountBecauseRichardIsDumb();
        protected abstract void BindDataBecauseRichardIsDumb();

        void Page_LoadComplete(object sender, EventArgs e)
        {
            BindDataBecauseRichardIsDumb();
        }

        // the rest of his reduh-ndant interface members
        public abstract string MenuItemName { get; set; }
        public abstract string MenuItemKey { get; set; }
        public abstract bool IsCapable(CapabilityCheck checker, int companyId);
        public abstract bool ShowInMenu { get; }
        public virtual Control CreateHeaderControl()
        {
            return null;
        }
    }
}

Update: The original author of the code has outed himself so I must give credit where it is due. Dan McKinley left the company I was with shortly after I started, and he talks more about the code, explaining some background and a few more "WTF's" that 'Richard' wrote.


This is actual code I once had to support. After struggling to comprehend the logic in AstaSaysGooGoo and AstaSaysGaaGaa (where many more astaTempVars were declared and used ) I was ready to give up. I finally looked up and saw the "@author" comment and the whole thing began to makes sense.

/*

* @author Andrew Asta
*/
public class AstaClass{

    private String astaVar1;    
    private String astaVar2;    
    private String astaVar3;    
    private String astaVar4;    
    private String astaVar5;    
    private String astaVar6;    
    private String astaVar7;    
    private String astaVar8;    
    private String astaVar9;    
    private String astaVar10;   

    public void AstaSaysGetData(){
        //JDBC statement to populate astavars 1 through 10
        //...
        String astaSqlStatment = "Select astaCol1, astaCol2, astaCol3... From AstaTable Where...";
        //..
        //...
    }

    //Perform data manipulation on astavars...
    public void AstaSaysGaaGaa(){
          [removed for sake of brevity]
    }


    //Perform more data manipulation on astavars...
    public void AstaSaysGooGoO(){
        [removed for sake of brevity]
    }

    public void AstaSaysPersist(){      
        //JDBC statement to save astavars to DB 
        String astaSqlStatment = "Update AstaTable set astaCol1 = @astaVar1
                                                  , set astaCol2 = @astaVar2
                                                  , set astaCol3 = astaCol3... 
                                                  Where...";
    }
}

PS I changed the actual authors real name so as to avoid me getting in any disputes etc...


This was the only comment we found in a smartcard product that a previous employer bought in. A load of embedded C and assembler written by a bunch of Dutch cryptography PhDs

// echt halmaal gek - no way!

(It means something like "really completely stupid"...which didn't help us either)


catch (Domain.ConcurrencyException)
{
    // somebody changed it between the time we loaded it and now.
    // weird, huh?
}

//todo: never to be implemented

if(m_measures =/*=*/ --index)
{
    ....

Some old fortran code I saw:

     integer *4 one,two,three;

c    asssign one to 100 before entering the loop
     one=100;

Fresh out of college, I was eager to get my hands dirty. My first task was... "comment this code for me".

Fucker.

After awhile I got bored with it...

// this function doesn't actually calculated the profit, like it says --it really signals the mothership orbiting saturn that the planet is ripe for takeover

[later]

// I don't think anyone is going to read this

[various permutations on that last one]

// this is really complicated

with no other comments


# To understand recursion, see the bottom of this file 

At the bottom of the file:

# To understand recursion, see the top of this file

/* Please work */

This seems to stop morons from messing my code...

// Autogenerated, do not edit. All changes will be undone.

I am particularly guilty of this, embedding non-constructive comments, code poetry and little jokes into most of my projects (although I usually have enough sense to remove anything directly offensive before releasing the code). Here's one I'm particulary fond of, placed far, far down a poorly-designed 'God Object':

/**
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
*/

I'M SORRY!!!! I just couldn't help myself.....!

And another, which I'll admit I haven't actually released into the wild, even though I am very tempted to do so in one of my less intuitive classes:

// 
// Dear maintainer:
// 
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
// 
// total_hours_wasted_here = 42
// 

// Whoever put this here is an idiot...this doesn't work at all !

But the code is still there...


An old boss of mine was always going on about how we had to use our own products internally i.e. "Eat our own dog food..."

Many years later I found embedded in some source that a temporary coworker had done, every function he touched is tagged with:

/* NOT FIT FOR HUMAN CONSUMPTION */

THIS PROGRAM HAS CODE THAT DOES NOT MEET STANDARDS      

That comment is in nearly every program we have here....


I once got a call from the client years after working on a big budgeting system written in Paradox 3.5 -

"We've come across a bit of commenting that came up in a debug " -

// This shouldn't happen, if it does, then the bits that automagically 
// worked when I wrote it have stopped working

... !


When I was taking a CS class in Highschool, we were being taught in a regular classroom - no computers. All our tests were done on paper that we handed in - one class per sheet of paper. Our teacher was teaching the class in C++ for the first time and would occasionally switch into Pascal mode on the chalkboard. This was awkward, as few of us had interest in learning Pascal.

For larger than in class work, we would do them at home and hand in code + output printouts to be graded. After submitting a few code + output printouts, we collectively realized that the teacher wasn't actually reading the code - just the printouts. To test our theory, I put in a comment on the 3rd page of my code - right between some class declarations:

// If you are reading this, please place a checkmark here [  ]

Of course, I got it back with a big blue "A" on the front and no checkmark to be found.


// I have to find a better job

Here's a few that I've put in my code at various times. Some aren't technically comments, but they're the same sort of concept.

In a cross-platform project that needs some special code on one platform only:

//If defined, will include all the Windows-specific code.
#define LOSE

#ifdef LOSE
#include <windows.h> //WIN32. Duh.
#endif


---------------------------------------------------


//Stolen from other_project_name.cpp


---------------------------------------------------


/*
 * These comments have been lifted from propagate() and, though they no longer apply to the code, they may still be of value somewhere. Original tabbing and structural elements have been preserved.
 */
    //CAUTION: This has a major Bobby Tables risk. Even if a rulebuilder is used, there's still the risk of something getting corrupted in the database itself.
    //Reading text from anywhere and simply slotting it into an SQL statement is a major security risk. (With thanks to xkcd for the name "Bobby Tables".)
    //Requirement: Eliminate one Bobby Tables by changing [redacted] to be not just straight SQL.
[lots more comments that are not as funny]
/*
 * End of lifted comments. There should not be any executable code between these markers.
 */


---------------------------------------------------


        /*
        Okay. It's unrecognized. Why is this a fatal error? It's actually very closely akin to the miswart of botched #includes being a fatal. When writing a C/C++
        program, you need your headers, and if you don't have one, chances are there'll be a million cascaded errors; so by making "unable to open asdf.h" a fatal,
        the compiler suppresses all those errors about undefined symbols and potentially misspelled type names.
        */


---------------------------------------------------


    //If someone tries to import 'id' as a field name, it won't work. (We already have our own id.) But I think the probability is so low that I can afford to be funny.
    if (!stricmp(ptr,"id")) {warn(0,"Import","","'id' is a reserved word and cannot be used as a column name. (Try 'ego' or 'superego'.)"); return;}


---------------------------------------------------


//Need a place to squirrel away SQL statements somewhere
char *uts[1024]; //Unified Temporary Storage. (Why? Because I said so.)
int nuts=0; //What is it that squirrels keep? Ha!
int utsid[sizeof uts/sizeof *uts];


---------------------------------------------------


        /**************************************\
         * NOTE: This sets tilde.action. If a *
         * tilde header does not exist in the *
         * import file (not the _content_, if *
         * the entire column isn't there), it *
         * will duplicate down through all of *
         * the rows. This is fine for ~id, as *
         * that will never be changed; and if *
         * ~Quantity is blank, that throws an *
         * error in 'Add'. With ~Action, I am *
         * not so certain. I THINK it'd be OK *
         * to dup-down most of the time... if *
         * the user only ever imports Adds or *
         * Revises, but never both at once in *
         * a single import. So for safety, to *
         * allow a blank ~Action to revise OR *
         * add, I'm breaking the check out to *
         * a new variable - the curaction. In *
         * most cases, it won't be needed, so *
         * it's a waste; but it isn't like it *
         * has to copy the entire tilde.*, so *
         * it's only a small waste. So it can *
         * waste a register... big deal. OK ! *
        \**************************************/


---------------------------------------------------


            //if (!response) // we're going to crash
            //if (!items) // we're going to crash
            //TODO: Don't crash


---------------------------------------------------

A lot of my comments contain obscure references to films or musicals, but they won't be nearly as funny if you don't know the show.


// THE LOOP THAT DO EVERYTHING!!!!!!!

In drivers/net/sunhme.c (Linux kernel):

/* 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->frame,
            (FRAME_WRITE | (hp->paddr << 23) |
             ((reg & 0xff) << 18) | (value & 0xffff)));
while(!(hme_read32(hp, &tregs->frame) & 0x10000) && --tries)
        udelay(20);

/* Anything else? */
if(!tries)
        printk(KERN_ERR "happy meal: Aieee, transceiver MIF write bolixed\n");

/* Fifty-two cents is your change, have a nice day. */

// This code was written by a genius so don't try to understand it with
// your tiny little brain.

stop(); // Hammertime!

this has turned up in my own code a few times. obviously I touched it more than once:

// TODO: Fix this.  Fix what?

From the 2004 Windows leak,

__inline BOOL
SearchOneDirectory(
                  IN  LPSTR Directory,
                  IN  LPSTR FileToFind,
                  IN  LPSTR SourceFullName,
                  IN  LPSTR SourceFilePart,
                  OUT PBOOL FoundInTree
                  )
{
    //
    // This was way too slow. Just say we didn't find the file.
    //
    *FoundInTree = FALSE;
    return(TRUE);
}

using namespace std;            // So sue me

long john; // silver

I once got a call from the client years after working on a big budgeting system written in Paradox 3.5 -

"We've come across a bit of commenting that came up in a debug " -

// This shouldn't happen, if it does, then the bits that automagically 
// worked when I wrote it have stopped working

... !


Another classic, by Donald Knuth no less:

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


In a large investment bank that required all application outages be logged and commented I saw

Without a crash 

Or mighty bang 

The sync disk 

Did it's process hang

In SJ CA back during the early days of the auction business I worked with a guy named Rick Dorin. He wrote compilers back when you had to poke at cards all day long. One of his error messages was

Too Many Errors... Make fewer!


About the middle of a 30 page xslt

<!-- Here be dragons  -->

// This will save us ~0.5 sec for every user and please the machine spirits.

Before very long procedure :)


I went through a sleep-deprived coding run and started only writing comments that were quotes from Fight Club.

Still trawling through the code years later I find a comment that makes me laugh. Most of them just random thoughts. I did however keep my comments to lines ratio pretty good!

// This shouldn't happen. The only way this can happen is if the
// <code>JFileChooser</code> has returned a <code>File</code> that doesn't exist
// on the system. If this happens we can't recover, and there is more than likely
// a rip in the space time continuum that the user is too distracted by to notice
// anything else.

 /**
   * This method leverages collective synergy to drive "outside of the box"
   * thinking and formulate key objectives into a win-win game plan with a
   * quality-driven approach that focuses on empowering key players to drive-up
   * their core competencies and increase expectations with an all-around
   * initiative to drive down the bottom-line. I really wanted to work the word
   * "mandrolic" in there, but that word always makes me want to punch myself in
   * the face.
   */
private void updateFileCountLabel() {

Using semi-colons in VB.NET

TextBox2.Visible = True';
For Each row In data.Tables(0).Rows
    If row("Customers.Id").ToString <> customerId Then
        customerId = row("Customers.ID").ToString';
        name = "Customer Name: " & row("Name").ToString & CrLf';
        address = "Address: " & row("Address").ToString & CrLf & CrLf';
        TextBox2.Text += name & address ';s
    End If';
Next';

First two lines of a file called monitoring.sh:

#!/usr/bin/perl
# perl script disguised as a bash script

'I hate nested regions and will delete them along with any code found in them.

A large project I worked on used StyleCop and FXCop in the automated build with rules to prevent people checking in code with uncommented fields, methods, properties etc., etc.

Someone got so pissed off with having to add comments like "Gets or sets the full name." to self-documenting properties like FullName, that they went to the effort of writing a macro to get around the rules.

The macro inserted XML summary tags for methods, properties etc. with a single non-displaying Unicode character as the tag content which would fool the build rules whilst simultaneously striking his minor blow against mindless insistence on commenting stuff for the sake of it...

...at least until they introduced another rule to check for Unicode characters in comments.


//Please comment on your source code

Sometime in the early 1980's we were writing financial modeling code for utilities in PL/I. Got a call from a client with code blowing up right after a comment

/* Honest this works */

The guy had taken our standard set of financial equations and done about 15 pages of algebra to combine a bunch of code into one equation. After Three Mile Island when utilities had to write off their nuclear plants at huge costs the equation failed because of a FIXED BIN 15 (integer) overflow that would not have happened if the algebra hadn't happened.


aComment = 'this is not aComment' # this is aComment
class T(object):
    def f(this):
        this is not aComment

// set break point here - you'll never reach it

Top of sqlite source files:

/*

** The author disclaims copyright to this source code.  In place of             
** a legal notice, here is a blessing:                                          
**                                                                              
**    May you do good and not evil.                                             
**    May you find forgiveness for yourself and forgive others.                 
**    May you share freely, never taking more than you give.

*/

// This code sucks.

// no comments for you
// it was hard to write
// so it should be hard to read

This is from an old IOCCC winning entry, I had to download the whole archive of winners -- a humongous 1.4 M -- and grep for several phrases I remembered wrong before finding it.

Syntactically this is probably not a comment. Or may be it is. I haven't figured it out. It definitely does not have comment delimiters, but it doesn't have String delimiters either.

C="Lint says "argument Manual isn't used."  What's that
mean?";

No prices for guessing the output from lint.

And for the curious, that entry is here.


//Time log says you've been here for 15 hours GO HOME, your code is hobo

On initialization of a linked list:

last = first; /* Biblical reference */

Succint and hilarious.


/// <summary>
/// The possible outcomes of an update operation (save or delete)
/// </summary>
public enum UpdateResult
{

    /// <summary>
    /// Updated successfully
    /// </summary>
    Success = 0,

    /// <summary>
    /// Updated successfully
    /// </summary>
    Failed = 1
}

// for 8 or 12 threads this does not affect much.
// Strange are the situations if not understood properly.
// Yoda strikes again

In a mutli-threading module! :)


Our team, just tonight, released a new version of a CSS file that removed the comments from a file which was structured like this:

@charset "UTF-8";
/* Who knew comments here could COMPLETELY ruin our page in Safari? */
body {
        /* Really important stuff here */
        /* Of course, comment or not, this will all get ignored by Safari because 
           its the first rule after the comments which break everything.
           see http://www.w3.org/International/questions/qa-css-charset for the exact details!
        */
}

The funny thing is on the web you'll find people's solutions are to just enter in a bogus element as the first rule below the charset statement to get ignored and proceed as normal...

Food for thought: Where does one put the comment not to comment?

Sidenote: I know this shouldn't be needed due to headers, meta rules etc. Unfortunately we need it as a catch all :(


Honest to God:

// This is crap code but it's 3 a.m. and I need to get this working.

An HORRIBLE patch for a decode (Translation by italian language):

/**
*@return the value 
*@param key: the id of the list of instruments
*@PS this function is a violation of all the laws of the 
*software engineering, 
*commons sense, highway code 
*and ONU decision about the coding.
That sh*t...
*/

    #Christmas tree initializer  
    toConnect = []  
    toRead =   [  ]  
    toWrite = [    ]   
    primes = [      ]  
    responses = {}  
    remaining = {}  

From Apache Xalan source code:

/**
 * As Gregor Samsa awoke one morning from uneasy dreams he found himself
 * transformed in his bed into a gigantic insect. He was lying on his hard,
 * as it were armour plated, back, and if he lifted his head a little he
 * could see his big, brown belly divided into stiff, arched segments, on
 * top of which the bed quilt could hardly keep in position and was about
 * to slide off completely. His numerous legs, which were pitifully thin
 * compared to the rest of his bulk, waved helplessly before his eyes.
 * "What has happened to me?", he thought. It was no dream....
 */
protected static String DEFAULT_TRANSLET_NAME = "GregorSamsa";

Further reading on The Daily WTF.


catch (Exception ex)
{ 
    // just die already.
}

stop(); // Hammertime!

Found in an old perl script that generates HTML:

# I would be _very_ brain farting if I said this code didn't need reviewing.
# It will make babies cry, and hair grow on your back, so please don't use it

var arbitraryNumber = 10;
//I don't know why. Just move on.

I found this:

I'm not sure what I did

Get This hack!

On a line of assembler code, after pages of uncommented code.


In a well known commercial DOS spreadsheet application:

/* This comment was just added in order to check-in a file that was last 
checked in by [Insert Programmer FirstName] "Back-to-the-Future" [Insert 
Programmer LastName]. While testing for year 2000 problems, he accidentally 
checked-in this file while his machine clock was set forward to the year 2000. 
This meant that the source code was always newer than the object file and 
compiled every time the code was built. I'm checking this file in again to 
fix that. */

 // WARNING!!!
 // Very perversive code ahead!

... about a 20 lines of "very perversive" code ...

// Now you can call your grandmother back. ;)

Fix problem where Nulls don't work properly.  Stupid Microsoft!

Code converted Nulls to zero-length strings line by line in roundabout way because the stupid programmer did not understand what Nulls are and had never heard of the Nz() function.


I didn't encounter this firsthand, but it makes for a good story (see explanation in my comment):

#define MSGTAG_B33R     0x723 /* RIPLVB */

/**
 * If you don't understand this code, you should be flipping burgers instead.
 */

// Caveat implementor

Exhibit a:

return 0; // Happy ending

Exhibit B:

int32_t Interpolate1DSignal(
  Array1D<float64>::Handle hfInputSamples,         // samples to be interpolated
  Array1D<float64>::Handle hfInterpolationFilter,  // polyphase filter coefficients,
  int32_t iFilterInterpolationFactor,              // # of "rows" in polyphase filter
  int32_t iFilterLength,                           // Length of each row in filter
  float64 fInterpolationFactor,                    // Factor to interpolate the
                                                   // signal by
  float64 fTimingOffset,                           // Offset into the signal (units   
                                                   // of samples)
  Array1D<float64>::Handle hfOutputSamples         // left as an exercise for the reader
);

#!/usr/bin/sh
#       Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T
#         All Rights Reserved

#       THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T
#       The copyright notice above does not evidence any
#       actual or intended publication of such source code.

#ident  "@(#)false.sh   1.6     93/01/11 SMI"   /* SVr4.0 1.3   */
exit 255

Taken from SunOS 5.9 aka Solaris 9 (/usr/bin/false)


/* logic */
#ifndef TRUE
# define TRUE 1
#endif /* TRUE */
#ifndef FALSE
# define FALSE 0
#endif /* FALSE */
#define EOF_OK TRUE
#define EOF_NOT_OK FALSE

and the rest of the glorious mkentry.c at the IOCCC page. I can't keep laughing every time I read through this source.


I don't have the exact code package anymore, but I remember the comment vividly.

// The code below needs to be changed immediately.
// I wish I was a little bit taller
// I wish I was a baller
// I wish I had a girl who looked good, I would call her.

/* You are not meant to understand this */ 

// no comment


This is my favourite comment ever.

/// I intend to do this as shittily as possible because there are many better products that will totally blow this out of the water
/// and we don't have them so whatever

Later on in the file we have more fun like

/// sidestep a bug in WCF (that we can't send types across)
/// or, depending on how you look at, this issue is a Feature

And again later

if( where == null)//be nice

That one is well-known but I like it (in sys/ufs/ufs_vnops.c):

/*
 * A virgin directory (no blushing please).
 */

in the FreeBSD kernel source tree (and even before, back into 4.xBSD)


'Major changes: Everthing! - Removed all Cornoud's code !

//Do not continue reading if you dont want to die.

This one almost killed me.


//MailBody builders for two outgoing messages
StringBuilder hanz = new StringBuilder();
StringBuilder franz = new StringBuilder();

I still chuckle a little when I read that one...


While working on some websites I found this at the start of the embedded JS:

I feel so dirty doing this but the guy wanted it in .NET


Quite a while ago I came across some connection script and while I don't remember the syntax I do recall the comments as I'm a Pink Floyd fan.

//Attempt Handshake: Hello? This is London calling. Are we reaching you?


//Handshake Failed: I don't understand...he just hung up.

// All this code is yours, except gedit()...attempt no modifications there.

//Dear future me. Please forgive me. 
//I can't even begin to express how sorry I am.  

And I just found this one today:

//private instance variable for storing age
public static int age;

// This is a walkaround for bug #7812

Written by one of our Chinese programmers, for whom English was not his first language.

I really liked this one. I happen to think "walkaround" is almost a better term than "workaround."


Found this in makefile

# ===== Never edit below this line. Ever. Or I'll kick your ass. ====

I just ran across this one in a really simple test C++ program for a class in college.

I was commenting a class.

In the destructor...

// Choose! Choose the form of the Destructor!
// The choice is made! The Traveler has come!

Production source code:

// Remove this if you wanna be fired

I believe in JBoss somewhere there was a line that read

return null; //Not really null

I always liked that line.


While working on some websites I found this at the start of the embedded JS:

I feel so dirty doing this but the guy wanted it in .NET


else
{
    // rien, c'est parfait.
}

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

That one is by Donald Knuth.


A modification log I noticed in a legacy code

05/17/99 D JONES COMMENT OUT THE BLOODY AUZIES CODE (02/19/99)

05/17/99 K ROBINSON BLOODY TEXAN CAN'T SPELL AUSSIE CORRECTLY (NO CODE CHANGE - JUST A COMMENT)


While working on some websites I found this at the start of the embedded JS:

I feel so dirty doing this but the guy wanted it in .NET


BerkeleyDB

/*
 * Chaos reigns within.
 * Reflect, repent, and reboot.
 * Order shall return.
 */
return (DB_RUNRECOVERY);

A large project I worked on used StyleCop and FXCop in the automated build with rules to prevent people checking in code with uncommented fields, methods, properties etc., etc.

Someone got so pissed off with having to add comments like "Gets or sets the full name." to self-documenting properties like FullName, that they went to the effort of writing a macro to get around the rules.

The macro inserted XML summary tags for methods, properties etc. with a single non-displaying Unicode character as the tag content which would fool the build rules whilst simultaneously striking his minor blow against mindless insistence on commenting stuff for the sake of it...

...at least until they introduced another rule to check for Unicode characters in comments.


"This will never happen".

Famous last words my friend...


private int mousycounter = 0; //Not really a counter

try {
  dataSource.close();
}
catch (SQLException ex) {
  // Do nothing, since we're going to trash this anyway
}

Of course, this sort of thing is actually a wtf in JDBC (or at least Oracle's JDBC driver) as it can throw SQLExceptions when closing a connection...


From Python/ceval.c:

/* This is gonna seem *real weird*, but if you put some other code between
   PyEval_EvalFrame() and PyEval_EvalCodeEx() you will need to adjust
   the test in the if statements in Misc/gdbinit (pystack and pystackv). */

//BELOW IS THE REAL CODE...JABRONI
        //
        // Yeah, but can you play the outtro to Bark At The Moon?
        //

        //|--------------------------------------------------|------------------------------------------------|
        //|--------------------------------------------------|------------------------------------------------|
        //|--17^16-16-16-17^16-17^16-16-16-17^16-17^16----16-|-19^16----16-19^16-19^16---16-19^16-19^16----17-|
        //|--------------------------------------------19----|-------17----------------17---------------17----|
        //|--------------------------------------------------|----------------------------------------------

// I have to find a better job

(A bunch of code that's really weird looking)  //Kludge.

// I'm sorry.

//this is a crap way to do this but I ran out of patience

DelButton.click(); 

//The following code is commented out
//(a load of commented out code followed)

// Singleton object. Leave $me alone.
private static $me;

From an absolutely lovely project I worked on up until recently (yes, I admit, some of those are mine, but I won't tell you which):

if(FAILED(hr))
{
    char fuck[256];
    sprintf(fuck, "GetBuffer() fucking fucked the fuck: %d", hr);
    MessageBoxA(0, fuck, fuck, MB_OK | MB_ICONERROR);
    return;
}


// This is for Chris, since he gets all hot and horny over "uint" instead of "unsigned int"
// ... or maybe he's just a lazy fuck. Who knows!?
using Ogre::uint; 
// movable texts, fucktory
MovableObjectTextFactory* m_pMovableObjectTextFactory;


// diarrhea... shitting CR from the string. complete run...

What he meant was that he's splitting the string by carriage returns to render separately.

// unlock shit (duh, this comment is useless)
pixelBuffer->unlock();


// :HACK: remove me after demo is shipped
Of course, it's still in there ;)


// it's 4am and I can't think of a decent error message.
// my lead just fell asleep at his desk, so I can't ask him.
// [name] went home because he didn't want to get divorced.
// and so it's little ol' me, sitting here, comin up with an
// error message for something that should never ever happen.
ASSERT0(in_len == max_in, "http://www.youtube.com/watch?v=oHg5SJYRHA0"); 


// you want hungarian, you GET hungarian!
for(int fcknglpidxcntvrI = 0; fcknglpidxcntvrI &lt; len; fcknglpidxcntvrI++)


bool bKillSomethingAlive = false; // beating the dead horse instead

Of course, we also have a nice collection of interesting ways to say "Hack":

// HACKOMATIC 
// HMM... HACKXOR?
// HACK'O'ROONY
// AR; yeah I know it's HACKsoup
// HACK SHOT! DOMINATING!
// HACK'KIDO
// HACKku. sepukku. harakiri. kamikaze. ninja.
// HACK'o'NEIL
// HACKsaw

// Bad Christian, No cookie

Cookie in this context does not refer to a browser cookie


# There is a bug in the next line.  $searchParameters != {} will always return true, because {} is creating
# a new hash reference on the fly, and the inequality operater is comparing the memory location of it
# to the memory location of $searchParameters, and they will always be different. 
# This means that the following code will always get executed as long as $nodes is defined.
# I'm leaving it there because it has always been there, and although I'm sure it was originally meant to
# mean %$searchParameters (essentially "is this hash not empty"), I'm afraid to change it.
if ( $nodes && $searchParameters != {} )
{

Classic ASP:

'Is it worth it, let me work it'
'I put my thing down, flip it and reverse it'
'Ti esrever dna ti pilf, nwod gniht ym tup I'

NextIP = StrReverse(UserRecordset.Fields.Item(0))

Just found this one in some of our PHP code

$s=2; // chicken and bacon wrap for lunch

How useful, luckily $s was self explanatory


/* Here I sit, Joe broken hearted, came to do some sh*t, but only just started. */

In regards to some heavy regular expression input validation.


#ifdef TRACE
#undef TRACE     /* All your trace are belong to us. */
#endif
#define TRACE ....

using namespace std;            // So sue me

I do not have a copy of the source but I have always remembered it:

// If you cannot figure it out, you should not be reading this


// somedev1 -  6/7/02 Adding temporary tracking of Login screen
// somedev2 -  5/22/07 Temporary my ass

 // WARNING!!!
 // Very perversive code ahead!

... about a 20 lines of "very perversive" code ...

// Now you can call your grandmother back. ;)

I once worked on a project where I found this comment:

// Cabbage fart?

I have no idea what it was supposed to mean. Just glad my cube wasn't next to whoever wrote it.


Top of sqlite source files:

/*

** The author disclaims copyright to this source code.  In place of             
** a legal notice, here is a blessing:                                          
**                                                                              
**    May you do good and not evil.                                             
**    May you find forgiveness for yourself and forgive others.                 
**    May you share freely, never taking more than you give.

*/

'NO COMMENT

/**---------START-----------**/

  //  IMPLEMENTATION GOES HERE

/**---------END-----------**/

But No Code ;)


It's not strictly speaking a comment, but...

It was the mid-1990s and I was working on a big migration: small software vendor, big client, lots of pressure. We had a lot of shifting-goalpost stuff; the project was very hard to control. I was the key developer, but new to the system, and the other developer was the vendor's owner/founder.

After a few months of not quite making deadlines and not quite satisfying the client, the owner/founder brought on another developer, who was working remotely. (I'm gonna go out on a limb and say the new developer had lesser skills and experience than me.)

Well, the new guy made some changes in code that I'd already worked on, and then a month or two later I was back in the same area of the code, and there were variables I hadn't seen before. With names like StupidMark.

Dude, that's just not right. I mean, there's teamwork considerations, but also: in this environment, variable names can show up in runtime error messages. I'm just saying.

In my opinion at the time, the new guy's code wasn't getting us much closer to a deliverable product anyway, which made the insult sting a little more.


On the linux 1.0 kernel scheduler (sched.c):

Dijkstra probably hates me.

/*
 *  'schedule()' is the scheduler function. It's a very simple and nice
 * scheduler: it's not perfect, but certainly works for most things.
 * The one thing you might take a look at is the signal-handler code here.
 *
 *   NOTE!!  Task 0 is the 'idle' task, which gets called when no other
 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
 * information in task[0] is never used.
 *
 * The "confuse_gcc" goto is used only to get better assembly code..
 * Dijkstra probably hates me.
 */
asmlinkage void schedule(void)

(...)


One of the most classic ones is the comment made by Pierre de Fermat about his well-known "Last theorem": "The margin of this page is a bit too small to write down the proof".

It took more than 350 years before the proof was found...

(According to wikipedia this is the original text:)

Cubum autem in duos cubos, aut quadratoquadratum in duos quadratoquadratos, et generaliter nullam in infinitum ultra quadratum potestatem in duos eiusdem nominis fas est dividere cuius rei demonstrationem mirabilem sane detexi. Hanc marginis exiguitas non caperet.

...and translated into English:

(It is impossible to separate a cube into two cubes, or a fourth power into two fourth powers, or in general, any power higher than the second into two like powers. I have discovered a truly marvellous proof of this, which this margin is too narrow to contain.)


'NO COMMENT

//Abandon all hope ye who enter beyond this point

don't know if it it's funny or sad..but one intern I had working with me had this little gem to calculate the price per unit

...

// get the units from the form 
int numUnits = Integer.parseInt(request.getParameter("num_pieces")); // this break at random times

//price 
float price = Float.parseFloat(request.getParameter("price")); // same as above

// Under certain conditions the following code blows up. I don't know those conditions.
float pricePerUnit = price / (float)numUnits;

...

// if i ever see this again i'm going to start bringing guns to work

// this comment included for the benefit of anyone grepping for swearwords: shit.

def format_ticket_content(text, recursive = true)
  if text.is_a?(TicketNote)
    note = text
    text = note.content
  else
    note = nil
  end

  ## Safety pig has arrived!
  text = h(text)
  ##                               _
  ##  _._ _..._ .-',     _.._(`))
  ## '-. `     '  /-._.-'    ',/
  ##    )         \            '.
  ##   / _    _    |             \
  ##  |  a    a    /              |
  ##  \   .-.                     ;  
  ##   '-('' ).-'       ,'       ;
  ##      '-;           |      .'
  ##         \           \    /
  ##         | 7  .__  _.-\   \
  ##         | |  |  ``/  /`  /
  ##        /,_|  |   /,_/   /
  ##           /,_/      '`-'
  ## 

We have a file and half way down it a programmer trying to make sense of the mess managed to move all the nonsense code to the bottom, and left a comment of something like:

I have no idea what this stuff does below here.

Another programmer left a series of nested namespaces that acted like a which-way-book, so that you could drill into the namespaces in the idea and choose your actions.


if(count<0) count=0;    //don't get me wrong but this has to be done :p

const int TEN=10; // As if the value of 10 will fluctuate... 

From a contractor in an application for a UK bank.

// i don't know how this works but it does so i'll leave it here anyway

He also added BNP (British very right wing party) as 1 of the dummy customers for testing... our immediate boss was of Asian ethnicity.


// some sport psychology
if (!focused)
    Focus();

// long live COM'n'Roll
public enum StatusCode
{
        //success codes
        S_OK                                            = 1,
        S_NONE                                          = 2,
        S_SQL_OPERATIONS_LISTS_EMPTY                    = 3,

        //error codes
        E_NO_MATCHING_END_FOUND                         = -1,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_BEGINNING        = -2,
        E_SEQUENCE_NUMBER_NOT_FOUND_AT_END              = -3,
        E_FORWARD_AND_BACKWARD_OPS_COUNT_DO_NOT_MATCH   = -4,
        E_FORWARD_AND_BACKWARD_IDS_DO_NOT_MATCH         = -5,
        E_IDS_DO_NOT_MATCH                              = -6
}

That one is well-known but I like it (in sys/ufs/ufs_vnops.c):

/*
 * A virgin directory (no blushing please).
 */

in the FreeBSD kernel source tree (and even before, back into 4.xBSD)


From the source code of the UNIX flavor of the Netscape web browser, circa 1997:

/* HP-UX sucks wet farts from dead pigeons' asses */

Such pearls were unfortunately removed before Moz went open-source ...


Top of sqlite source files:

/*

** The author disclaims copyright to this source code.  In place of             
** a legal notice, here is a blessing:                                          
**                                                                              
**    May you do good and not evil.                                             
**    May you find forgiveness for yourself and forgive others.                 
**    May you share freely, never taking more than you give.

*/

It speaks volumes about our profession that when asked about the "best comment", we all answer with the worst comments we can find...


//this is a crap way to do this but I ran out of patience

DelButton.click(); 

// This procedure is really good for your dorsolateral prefrontal cortex.

For those of you who are, for some peculiar reason, unaware of the DPC, it's the part of your brain that lights-up when you're deeply engaged in learning something new.


// TODO: Implement this function!

// StupidCompilerDontInline(SCDI), in the test project where
// allcode was in a single cpp the compiler had inlined nearly
// everything which lead to nice stackoverflow.
// To prevent this the metods are made virtual
#define SCDI virtual

A few from the Linux kernel:

/* Sun, you just can't beat me, you just can't.  Stop trying,
* give up.  I'm serious, I am going to kick the living shit
* out of you, game over, lights out.
*/

-

/* 2,191 lines of complete and utter shit coming up... */

-

#if 0 /* XXX No fucking way dude... */

I don't have the exact code package anymore, but I remember the comment vividly.

// The code below needs to be changed immediately.
// I wish I was a little bit taller
// I wish I was a baller
// I wish I had a girl who looked good, I would call her.

I once worked on the source code of Windows 3.0. (Not, I hasten to add, as a Microsoft employee!) There I came across a file loader that went re-entrant multiple times, and had one example of some nasty punning (just to show how clever the author was).

This mess of re-entrant code was executed with an Intel assembly jmp instruction (in the middle of C code), which went to the label "we_are_not_in_kansas_any_more_toto".


We have a file and half way down it a programmer trying to make sense of the mess managed to move all the nonsense code to the bottom, and left a comment of something like:

I have no idea what this stuff does below here.

Another programmer left a series of nested namespaces that acted like a which-way-book, so that you could drill into the namespaces in the idea and choose your actions.


// need a coffee to fix this.

This was for a custom DHCP server that we used in a university's dorms to put computers into 'clean' or 'dirty' IP address pools depending on whether or not they'd registered/installed patches and Antivirus:

public boolean getDirty (String MAC) // not as fun as it sounds

This one i found it in the package "twisted" for Python 2.5 (the file is tcp.py at line 371)

# Limit length of buffer to try to send, because some OSes are too
# stupid to do so themselves (ahem windows)
return self.socket.send(buffer(data, 0, self.SEND_LIMIT))

//        .==.        .==.          
//       //`^\\      //^`\\         
//      // ^ ^\(\__/)/^ ^^\\        
//     //^ ^^ ^/6  6\ ^^ ^ \\       
//    //^ ^^ ^/( .. )\^ ^ ^ \\      
//   // ^^ ^/\| v""v |/\^ ^ ^\\     
//  // ^^/\/ /  `~~`  \ \/\^ ^\\    
//  -----------------------------
/// HERE BE DRAGONS

I don't have access to the original file because I don't work there anymore, but it was something very similar to this picture. It was at the top of a file that always caused troubles, that we had to fix but not allowed to take the time to really fix. (University politics)


// BEGIN HACK
...
// END HACK: I feel dirty.

In a GIGANTIC 800 line 'switch' statement, somewhere in the middle:

// Joe is sorry

A few hundred lines later...

// Harry is sorry too

Best comment I ever saw was

/* 
  There is no accounting for pointers 
*/

All bugs added by David S. Miller


From a classic from usenet:

Deep inside the Teradyne hardware modeler code is a routine that feeds a whole bunch of hex numbers into a SYS$QIO call. The only comment is 'Weird magic happens here'.


In some assembler, at the end of a line that contained &h723

' RIP LVB

(get it?)


I just ran across this one in a really simple test C++ program for a class in college.

I was commenting a class.

In the destructor...

// Choose! Choose the form of the Destructor!
// The choice is made! The Traveler has come!

Actually saw this the other day, on some code that was written when there was a deadline rush.

//This was clearly written under duress

Dennis M Ritchie has a page about some of the ancient UNIX comments here


/*************************** Drag And Drop Section - Start (you should be me to mess with this section)*********************************************/

i just noticed myself writing this

// not brilliant solution, but fair enough heh.

An HORRIBLE patch for a decode (Translation by italian language):

/**
*@return the value 
*@param key: the id of the list of instruments
*@PS this function is a violation of all the laws of the 
*software engineering, 
*commons sense, highway code 
*and ONU decision about the coding.
That sh*t...
*/

Control + A, Rewrite

This was a comment added to source control on a previous project as the check in comment.


//too much log will kill you

This comment I wrote it myself, when lowering the priority of some logs which otherwise would write hundreds of MB of crap and seriously crippled an application performance.


I just ran into this in some of my own code. It was in a magento admin template for category selection:

        /*
         * OK; before you read the following code know what I am trying to do.
         * I needed to get the list of child catagories from the root node so that
         * the root node didn't appear in the selection box. But for some stupid
         * fucking reason the stupid fucking DBA wont let me access the items using
         * indicies and I instead have to use their stupid fucking Iterator
         * implementation. So there.
         */
        $firstList = $this->getRootNode()->getChildren();
        foreach ($firstList as $node)
        {
            $nodes = $node->getChildren();
            break;          // wtf?
        }

I am going to remove the language of course out of our flagship product; but I remember I was super frustrated. If I hadn't left a comment, I would try to revise it but then run into the same problems I had before.


In Latin, Abandon hope all ye who enter here from Dante's "Divine Comedy".


// TODO - Comment this function

// If you're reading this, that means you have been put in charge of my previous project.
// I am so, so sorry for you. God speed.

on js code:

// hack for ie browser (assuming that ie is a browser)

My favorite (which I must admit I've used many times):

// Yes...I know this is repulsive and stupid.
// But <%CompanyOwnerOrManagerToken%>, not knowing a thing about code,
// demanded I do it anyways. SO, go crap on their desk, not mine.
// K THX BYE 

I don't have the code to share, but imagine this scenario. About a month or two after our Linux Sys Admin left for greener pastures, I had the pleasure of opening a shell script he'd written. I can't recall why I needed to edit it, but that's not what matters. What's important is that the script was about 40 lines long. I scrolled past the commenting (of which there were 37 lines) to reach the actual working code (3 lines). The code was great, but I was curious - why 37 lines of commenting? So, I scrolled to the top and proceeded to read. To my surprise, the commenting was a rap about what the three lines of code did and how to change it. The best part - it was a partial rip off of Nothing But A G Thing by Dr. Dre and Snoop D O DOUBLE G. Thanks Brian!


Many years ago (about 1994) I was working on a Oracle PRO*C application for a large multi-national software company that you will have heard of. The app I was working on was a massive Oracle application and they had a utility that ran overnight tidying up data and doing all sorts of aggregate calculations. Every time anything needed doing as a batch job, it got shoved into this utility and as you can imagine it became an absolute monstrosity. It was also notable for the tiny number of comments that it had for such a massive program.

One of the few comments it did have remains the finest comment I have ever seen for pure WTF'ness... I was trying to find a bug in a function which was hundreds of lines long and right in the middle of it was the only comment in the function:

/* I did this the other way */

To this day it is still the finest comment I have ever seen.


Linux Comments

There are heaps of good ones here ...

These are all comments in linux

http://lwn.net/1998/1015/a/f-word.html

My Favourites:

./arch/sparc/kernel/ptrace.c
/* Fuck me gently with a chainsaw... */

./drivers/scsi/qlogicpti.h
/* Am I fucking pedantic or what? */

Q: "What is the best comment in source code you have ever encountered?"

A: Easy - the one that helped me solve whatever problem I was having at the time, and there are lots of those!

Second best are those that help guide new development from avoiding known pitfalls.


This was for a custom DHCP server that we used in a university's dorms to put computers into 'clean' or 'dirty' IP address pools depending on whether or not they'd registered/installed patches and Antivirus:

public boolean getDirty (String MAC) // not as fun as it sounds

First at the beginning of an Update to a huge object:

/*General note to all who tread in the <ObjectName>() code...
 * The SetOriginals() method from the BaseEntity class should be called (and only called) right after the Get() method
 * call as seen above.  Calling the SetOriginals method elsewhere will result in bugs and all kinds of other nasty suprises.
 */

Then after some 200 lines of logic to update the object:

//Attempt to explain this confusing mess of code:
//First time you save an actual absence this is what happens:
//0. The first save saves to the <TableName> table (among other things). (Fig. A)
//1. The <CalculationMethod> method is called next which inserts to the <OtherTableName> table. 
//(This is the table that keeps track of credits to the case.) (Fig. B)
//2. So then you have to call <UpdateCalculations> to move the <TableName> records to the <ThirdTableName> table. (Fig. C)
//3. Then you go back and run calculations since you have the debits table (<ThirdTableName>) populated. (Fig D.)
//4. Then a final save to save the calculations back to the case. (Fig. E)
//Yeah, I know what you're thinking:  this sucks. 10/01/07 XXX

And the developer was right... This sucked HARD!


var arbitraryNumber = 10;
//I don't know why. Just move on.


The favorite comment I ever wrote:

//the XML returned from this request is *mind-bogglingly* bad. Terrifyingly bad.
//a completed batch looks like this:
//<Batch>batchid=363777811 status=Done dateandtime=09/18/2007 09:53:10 PDT activateditems=335 numberofwarnings=0 itemsnotacivated=17 </Batch>
//and an incomplete batch like:
//<Batch>batchid=363778361 status=In Progress </Batch>
//so we'll just parse each item as a regex. Thanks Amazon.

And yes, Amazon actually returns XML like this.


// Keep prozac ready if things get ugly!

All bugs added by David S. Miller


// no comment


Found over a complex code -

//Jesus and this code have one thing in common: both were resurrected


From a lad that clearly had been watching Monty Python:

> // And now, for something completely
> // different:

class theLarch{


// haack, phil haack

and:

/* hack, hack, hack, hack, hack hack, hack, hack
 * hackity hack, oh wonderful hacks
 * wonderful hacks, oh wonderful hack, hack, hack
 * hack hack hack... and spam 
 */

EDIT: Just found this in some of my code (the project wishes to remain anonymous):

// yikes, we need to:
/*
 *       o
 *      -|-     < US CROSSING PLATFORM
 *       |\ 
 ************************************************
 *       |          ^ PLATFORM           |
 *       |                           T   |
 *       |                      TROLL^   |
 */
// right now:
/*
 *   o ./_  | 
 *  -|-[]\  |  (_'_) () (\) | ) \|/ (S) < WALL
 *   |\     |    ^ FRIENDLY MESSAGE FROM YOUR FRIENDS AT MICROSOFT
 *  ***********************************************
 *        | ^PLATFORM                       |
 *      ^ SPRAY CAN (IN HAND)
 */
public static class DefaultFonts
{
    public static string SansSerifPath
    {
        get { return @"C:\Windows\Fonts\arial.ttf"; }
    }
    public static string SerifPath
    {
        get { return @"C:\Windows\Fonts\times.ttf"; }
    }
    public static string MonospacePath
    {
        get { return @"C:\Windows\Fonts\courier.ttf"; }
    }
}

How I love puns.


Well, these are mine, so WTF is me, as CodingHorror said:

//#region Code for weird cases - do you really want to know?

I once left a comment like so in some ASP:

' Commented out following code, don't delete for when [CustomerName] changes his mind

As it happens, [CustomerName] didn't change his mind, but he DID have access to the web server, and he DID find that line...


class Act //That's me!!!
{

}

// if i ever see this again i'm going to start bringing guns to work

I posted this "license statement" in a WordPress template I released. I thought it was funny, anyhow.

/* The License:
You (from this point on referred to as The You) are hereby 
granted by me (from this point on referred to as The Me) 
license to knock yourself silly with this template. 
By using this template The You implicitly accepts this 
license and pledges solemnly to never claim creative 
ownership of any graphics, code, concepts, eggs, bacon, ideas, 
colors, shapes, hypertext-transfer protocols or other conduits 
of the visual splendor thatis this template. 

The Me, in turn, pledges equally solemnly to be far too 
lazy to ever check up on you, so if you do manage to pull 
some chicks The Me won't have a cow. 
However The Me would be sorely disappointed if The You 
were to try and sell or distribute this work without 
acknowledging The Me. Seriously. The Me will come down on 
The You like a large quantitiy of hard and heavy objects 
that in large quantities may be harmful and possibly even 
lethal to The You; So don't even think about it, The Buster.
*/

Seen in some COBOL back in 1983:

   C   I don't know what this next bit does so I'll jump around it
       GOTO DONE.

This is one from my own code, but it's still really funny, and I figure I might as well put it up because it's in public SVN.

// These were orginally up and down. When it was clear the names were
// inapplicable, they were renamed to retain the joke.
// Sorry if you were hoping for useful variable names.
quantum strange, charm;

In a class named "Bar" (which was a UI Control with a less than descriptive name), the class header:

/// <summary>I pity the "foo".</summary>

And the Remove() method:

/// <summary>A "foo" and his money are soon parted.</summary>

Even worse, it was a business partner that pointed it out from the generated documentation. Even worse than that, is those are probably the closest things to useful documentation we ever got out of the guy.


Well, here's one I just committed:

/* Every time I re-visit this function, I feel like
 * I need to take a shower.
 *
 * Don't get too used to this function, its days are
 * numbered.
 */

Someone could start something like greatcodecomments.com and make some cash. That person, however, is not me.


I just found this one in a custom Linq provider for .net:

//select is a royal pain in the ass where 
//the parameter passed to CreateQuery isn't actually the one that goes in the call
//requiring this workaround.  Not sure how straight Linq to Objects does it.

And this one

//expressions have to be compiled in order to work with the method call on 
//straight Enumerable somehow, LINQ to objects itself magically does this.  
//Reflector shows a mess, so I (Aaron) invented my own way.  God love unit tests!

And i just found this one as well... it just gets better

  //ok, this is a hairy, dirty, and nasty piece of code
  //the alternatives are substantially worse than this though
  //i.e. when you do your own provider, LINQ assumes that
  //you are going to implement your own expression tree visitor and
  //do it all yourself.  Frankly, I still have xmas shopping to do
  //and I really don't want us to be foobared when we get
  //even more extension methods added to LINQ
  //therefore, we are pulling execute based on taking the calling the 
  //standard execute on enumerable, but using our own class
  //
  //optimization can occur from here on an as needed basis, that is
  //check for the value of mex.Method.Name, and write a handler for
  //that method
  //
  //also, it may not be a bad idea to rather than do this reflection 
  //each and every time somehow cache the reflected methodinfos and do 
  //lookups that way that said, we need a complete red/green/refactor 
  //cycle here before I am touching that one

And this one

//Compile that mutherf-ker, invoke it, and get the resulting hash

options.BatchSize = 300; //Madness? THIS IS SPARTA!

int Q13Factor = 8125; // 2^13 for Q13 

I don't remember exactly, but the idea was something like this:

Person p = new Person("John", "Doe", "male");
Collection women = new ArrayList();
women.insert(p.getTail());

It's dirty code ;)


My personal favorite is documentation in limerick form:

        Subclassing made Zope and TR
        much harder to work with by far.
            So before you inherit,
            be sure to declare it
        Adapter, not PyObject*

This probably spoils the joke a bit, but since it's a bit obscure I'll explain:

"TR" here refers to "Twisted Reality". Zope 2 and the original twisted.reality package made extensive and unfortunate use of multiple inheritance, which could make it difficult to understand what was going on when you saw a method call. Zope 3, Twisted itself, and twisted.reality's successors (including the most recent, Imaginary) instead generally favor component composition.


Another classic, by Donald Knuth no less:

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


//I am not sure why this works but it fixes the problem. 

This was before a set of code that technically did fix the problem it was meant to but broke 3 other things....


A few hours after showing a friend this post from Coding Horror, I saw this comment on his code:

// MrValdez is a violent Psychopath. Don't piss him off.


Just found this in some Actionscript I have to update...

/*
* spaghetty code in this module.
* hardcoded variables for load paths for the content window.
* Needs (vast) improvement.
*/

..great :(


struct core_unlocker
{
    core_unlocker(lock)
    {
        m_lock = lock
        unlock(lock)  //Abandon All Locks, Ye Who Enter Core!
    }
    ~core_unlocker()
    {
        lock(m_lock)
    }  
    private:
    Corelock m_lock;
}

%%return_median
hit_the_sweet_spot(Arg)->
.
.

  rescue
    # silently, we fail
    # many validations fade
    # like tear drops in rain
  end

This is just one of many...


This is my favourite comment ever.

/// I intend to do this as shittily as possible because there are many better products that will totally blow this out of the water
/// and we don't have them so whatever

Later on in the file we have more fun like

/// sidestep a bug in WCF (that we can't send types across)
/// or, depending on how you look at, this issue is a Feature

And again later

if( where == null)//be nice

Once I found this:

// I wish (boss name) could do this by him self.

// THE LOOP THAT DO EVERYTHING!!!!!!!

$this->getSelect()->where ('main_table.product_id = -1'); // Mom, Dad... sorry

//  Hey, your shoe's untied!

Followed by some dubious code, and within that code,

//  Keep looking!  I think it was the other shoe!

Finally,

//  How strange -- I must be seeing things.  Anyhow, I'm going to go take a shower, now...

// I love the smell of dirty XML in the morning
xml = xml.Replace("xmlns=\"urn:bsd.orion/inventory\"", "");

Dennis M Ritchie has a page about some of the ancient UNIX comments here


// I'm sorry.

// This procedure is really good for your dorsolateral prefrontal cortex.

For those of you who are, for some peculiar reason, unaware of the DPC, it's the part of your brain that lights-up when you're deeply engaged in learning something new.


// I dedicate all this code, all my work, to my wife, Darlene, who will 
// have to support me and our three children and the dog once it gets 
// released into the public.

//too much log will kill you

This comment I wrote it myself, when lowering the priority of some logs which otherwise would write hundreds of MB of crap and seriously crippled an application performance.


In the header of an XSLT file:

DON'T TOUCH THIS SCRIPT -> XSLT is like arcane, black magic

Some time ago I came across:

raise InvalidChild() # e.g. no legs

This is grotesque since "inwalida" in polish, means person with disability. silly me :)


Well, these are mine, so WTF is me, as CodingHorror said:

//#region Code for weird cases - do you really want to know?

I once left a comment like so in some ASP:

' Commented out following code, don't delete for when [CustomerName] changes his mind

As it happens, [CustomerName] didn't change his mind, but he DID have access to the web server, and he DID find that line...


//  Hey, your shoe's untied!

Followed by some dubious code, and within that code,

//  Keep looking!  I think it was the other shoe!

Finally,

//  How strange -- I must be seeing things.  Anyhow, I'm going to go take a shower, now...

//  If you delete the credits, I will fucking kill you.

found in a joomla module.


That one is well-known but I like it (in sys/ufs/ufs_vnops.c):

/*
 * A virgin directory (no blushing please).
 */

in the FreeBSD kernel source tree (and even before, back into 4.xBSD)


It speaks volumes about our profession that when asked about the "best comment", we all answer with the worst comments we can find...


// GK Experimental

(GK being the initials of the coder)

Used to indicate parts of code which are, indeed, kind of experimental. :)

A great flag to know that when you hit it during debugging you're probably busy for the upcoming few hours fixing the hack.. ;)


// Magic. Do not touch.

// barcore.cpp - MFC

//.....
HBRUSH CControlBar::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    LRESULT lResult;
    if (pWnd->SendChildNotifyLastMsg(&lResult))
        return (HBRUSH)lResult;     // eat it

//......

// Eat it - just like eat this.

when :orientation
## Avoid matching gay people with straight people - they hate it, they do, they really do.
query_parameter = "(users.orientation = 'Bi' OR (users.orientation = 'Straight' AND users.gender IN ('#{user.opposite_genders.join('\',\'')}')) OR (users.orientation = 'Gay' AND users.gender IN ('#{user.same_genders.join('\',\'')}')))"

From a dating website...


This is my favourite comment ever.

/// I intend to do this as shittily as possible because there are many better products that will totally blow this out of the water
/// and we don't have them so whatever

Later on in the file we have more fun like

/// sidestep a bug in WCF (that we can't send types across)
/// or, depending on how you look at, this issue is a Feature

And again later

if( where == null)//be nice

While debugging someone else JavaScript I've seen the following comment:

// Notice: I feel so dirty doing this, but it's the only way to make it cross browser.

But while reading one post of Scott Hanselmen I came across the following quote that goes very well with the comments I found inside the code:

Every line of code you write that you feel gross about will ultimately come back to haunt you. Therefore, avoid writing code that makes you feel dirty.

That's funny :)


Found in the JUnit API:

/**
 * ...as the moon sets over the early morning Merlin, Oregon
 * mountains, our intrepid adventurers type...
 */
public Test createTest(Class theClass, String name) {
    ...
}

// human madable inconvenient. Way too sucks.

I still don't fully understand what it means, but I have found it to be very true about a lot of code.


// This code was written by a genius so don't try to understand it with
// your tiny little brain.

Once, I asked a coworker how to do something (forgot exactly what, some obscure technical calls) with our in-house framework. He said "easy, look HERE", then opens a .java file in his editor and shows me this comment in the middle of several pages of code:

// HERE

I just checked, the comment is still there in this file :)


Back in the early eighties, I came across this in assembler (quoting from dim memory):

I don't understand how the following bit works, but it worked in the program I stole it from.

return 1; # returns 1

I cried when I read this one on a project I was given to maintain.

//Write Code Here

I still cringe :)


In a class named "Bar" (which was a UI Control with a less than descriptive name), the class header:

/// <summary>I pity the "foo".</summary>

And the Remove() method:

/// <summary>A "foo" and his money are soon parted.</summary>

Even worse, it was a business partner that pointed it out from the generated documentation. Even worse than that, is those are probably the closest things to useful documentation we ever got out of the guy.


Not really a comment:

DvLog::Log("This silly log message fixes a PSCRIPT5.DLL gpf when printing to Adobe.");

Sad thing is that without the comment, PSCRIPT5.DLL really did blow up ...


Sometime in the early 1980's we were writing financial modeling code for utilities in PL/I. Got a call from a client with code blowing up right after a comment

/* Honest this works */

The guy had taken our standard set of financial equations and done about 15 pages of algebra to combine a bunch of code into one equation. After Three Mile Island when utilities had to write off their nuclear plants at huge costs the equation failed because of a FIXED BIN 15 (integer) overflow that would not have happened if the algebra hadn't happened.


# absolutely foul heuristic code.
# ..it's dirty, but you want it.

and:

# VERY USEFUL DEBUGGING AID, for when the above all goes pearshaped:

Back in college:

//why the f*** we have to move this here to make it work

It was highlighted in a printed source when we went to review with the professor.

The reason: some really nasty bug related to a buffer overflow, that affected an unrelated variable with a file handler in other place of the code. Moving the variable would make it work again.


The favorite comment I ever wrote:

//the XML returned from this request is *mind-bogglingly* bad. Terrifyingly bad.
//a completed batch looks like this:
//<Batch>batchid=363777811 status=Done dateandtime=09/18/2007 09:53:10 PDT activateditems=335 numberofwarnings=0 itemsnotacivated=17 </Batch>
//and an incomplete batch like:
//<Batch>batchid=363778361 status=In Progress </Batch>
//so we'll just parse each item as a regex. Thanks Amazon.

And yes, Amazon actually returns XML like this.


Sometime in the early 1980's we were writing financial modeling code for utilities in PL/I. Got a call from a client with code blowing up right after a comment

/* Honest this works */

The guy had taken our standard set of financial equations and done about 15 pages of algebra to combine a bunch of code into one equation. After Three Mile Island when utilities had to write off their nuclear plants at huge costs the equation failed because of a FIXED BIN 15 (integer) overflow that would not have happened if the algebra hadn't happened.


// good luck!

   // Some wanker in ISO got rid of ifstream(int), ofstream(int), and
   // fstream(int).  Twit.

Upon being forced to write unit tests for anemic domain objects that are nothing but bags of getters and setters (which I was forced to write as well):

// zzzzZZZZzzzz....

Many years ago (about 1994) I was working on a Oracle PRO*C application for a large multi-national software company that you will have heard of. The app I was working on was a massive Oracle application and they had a utility that ran overnight tidying up data and doing all sorts of aggregate calculations. Every time anything needed doing as a batch job, it got shoved into this utility and as you can imagine it became an absolute monstrosity. It was also notable for the tiny number of comments that it had for such a massive program.

One of the few comments it did have remains the finest comment I have ever seen for pure WTF'ness... I was trying to find a bug in a function which was hundreds of lines long and right in the middle of it was the only comment in the function:

/* I did this the other way */

To this day it is still the finest comment I have ever seen.


//open lid


//take sh!t


//close lid

Comments for a File open, data dump, file close...


My personal favorite is documentation in limerick form:

        Subclassing made Zope and TR
        much harder to work with by far.
            So before you inherit,
            be sure to declare it
        Adapter, not PyObject*

This probably spoils the joke a bit, but since it's a bit obscure I'll explain:

"TR" here refers to "Twisted Reality". Zope 2 and the original twisted.reality package made extensive and unfortunate use of multiple inheritance, which could make it difficult to understand what was going on when you saw a method call. Zope 3, Twisted itself, and twisted.reality's successors (including the most recent, Imaginary) instead generally favor component composition.


don't know if it it's funny or sad..but one intern I had working with me had this little gem to calculate the price per unit

...

// get the units from the form 
int numUnits = Integer.parseInt(request.getParameter("num_pieces")); // this break at random times

//price 
float price = Float.parseFloat(request.getParameter("price")); // same as above

// Under certain conditions the following code blows up. I don't know those conditions.
float pricePerUnit = price / (float)numUnits;

...

Technically not a comment, but from coding on something at 2 am or so:

consent = False

... that variable is never used again EVER and appears in the beginning of a listen loop for a socket.


options.BatchSize = 300; //Madness? THIS IS SPARTA!

It speaks volumes about our profession that when asked about the "best comment", we all answer with the worst comments we can find...


""".........................:~+?7$$$ZZZZZZZ$$$7I+=:,............................
........................~+7ZZZZZOZZOOZOZZOZOZOOZZZZZ7?~:........................
......................,~7$ZZOOOOOZOZOZOZZOOZZOZOOOOOZ$$I,.......................
...................,=I$OOZOZOZZOOOZZOZOOOOZOZZZOOZZZOZZOZI=:....................
.................:?$ZZOOZZOZOZZOOOZZZOOZOZOZZZZZZZOZZOZOOOZ$I~..................
................IZOOOZOOOZZZOZZZZOZZOZOOOOZOZZZOOZZZZOOZOZZZOZ7=................
...............~ZZOZZOZOOZOOZOZOZZOZOZOZZZZZOZOZZOZOOZOZZOOOOZZ7................
.............:IZOOZOZZZZOZOZZOZOOZOZOZOZZOZOOZOOOOZOZZZZZOZOZZOOI~..............
...........,+$ZOOZZOZOZOZOZOZZOZOZOOZZOZZOZZOZOOOOZOZZOZZOOZOOOOO$?:............
..........:IZZOOOZOZZZZOOZOOZOZOZZOZOZZZZOZOOZOZZOZOZOZOOOOOOOZZZOZ7~...........
..........+$OOZZZOZZOOZOOZZZZOZZOZOZZOZOOOZOZOZZOZOZOZOOOOOZ$$77I77$+:..........
........,?$OOZZZZZZZOZOOOZOZZOZZZOOZOZOOOOZOZZZOOZOOZOOO7?~:,.......,...........
........+ZOOZZZZZOZOOZOOZZZZOZZOOOZZZOZOZOOZZOZOZZZOOO$?........................
........$ZOZZZOZZZZOZOOZZZOZOZZOOOOOOOOOOOZOZOZZOZOO$?,.........................
.......:ZOOZOZOZZOOZZOZOZOZOOOZOOOOOOOOOOOOOOOZOZOOZI:..........................
.......+OOOZOOZOZOZOZZZOOZOOZOOO$I+=~:::~+I$OOOOOOZ?:........,:=,...............
......:7ZOOZOZZOOOZOZOZOOZOOZ$I=............:?$OOZ7:.......:IZOOZ?,.............
......=$OZOZOOZOOOOOZOZZOOZ7=,................:?O$+.......~7OOOOOZ+,............
.....,?$OOOOOZZZZOOOOOOZOZ?,....................ZZ=.......=$OOZOOZ+,............
.....:IZOZZ$777I7$ZOOOOOZ7~.....................$Z=.......~7OOOOO7=.............
.....:+?~:,.......,~IZOO7~........~+II?=........?$?,.......:I$ZZ?:..............
.....................+ZO=,......:IOOOOOZ:.......=7$~............................
.....................:IO~.......=OOZOZOO=,......~7O7~...........................
...........:~:.......:IO~.......+OOOOZOO=.......~78Z?,.................,:.......
..........:IZ7~......+ZO~.......:7OOOOO$,.......+$OOZ7=,.............:?$=.......
...........,,.....,=7ZOO+,.......,=II?=:........7OOOOOOZ=:,.....,:=I$ZOO=.......
....................,:+$7=.....................~OOOZZZOOOZZ$$7$$ZOOOOOOZ=.......
......................:?Z?,...................:?OZOOZOOZOOOOOOOOOOZOZOZO=.......
............,::,.......,OO7:................,+$OOZOZOOZOZZOZOZZOOZOZOZOO=.......
...........~$8OI........$OOZI~,.........,:=IZOOZOZOZOZOOOZOZOZOOOZZZOZOO=.......
...........:??=:.......:OOOOOZZ7+=~~==+?$ZOOOOZOOOZOZOZOOZOZOZZOZZOZOZZO=.......
............::,.......,+OOZOOOOO$7777$$ZOOOOOZOZZZZOZOZZZOOZOZZOOOZOOZOO=.......
.....................=7OOZOOZOOZOOOOOOOOOZZZOZOZZOZOZOZOOOZOZOZZOZOOZOOO=.......
................,:=I$OOOZZOOOZOOOOOZOZOZZZZZOOZZZOZOZZZOOZOOZOZOZOZOZOOZ=.......
...........:~+?7ZOOOOOOZZZOZOOZOZOOZOZOZZOZZOZOZZZZOZOZZOZOZOZZOZOOZOOOZ=.......
........$$ZOOOOOOOOZOZOZZZZOZOZOOOZZZOZZZOZOOZOZZZZZZZZOOOZOOZZZOZOOZOOZ=.......
.......~OOZOOZZOOZZZZZZOOZOZOZOZZOOZOOZZZOZZOZOZZOZZZOZOOOOOZOZOZOOZOOOZ=.......
.......~OOZOOZZOZZOZOZZOZZOZOOZOZOOZOZOZZOZOOZOZZOZOZOZOZOOZOZOOOZOOZOZO=.......
.......~OOZZZOZOOOZOZOZZOZOZOZOZOOZOOZOOOOZOZOOZOOOZOOOZOZZOZOZOOZZOOOOZ=.......
.......~OOZZOZOZZZOOZOOZOZOZOZZOZZZZOZZZZOZOZZOOOOZ$ZZZZZZOZZZOZZOZOZZZO=.......
.......~OOZZOO$??$OOZOOZZOOZOZOZ+~IZOOOZOZOOZZOOZI==IZOZZOZOOZOZZOZI~=7O=.......
.......~OOZO$I:..~IZZZOZOZOZOZ$+...=7ZOOZOOZZOZZ=,..,=$ZZOZZZZZOZI~...,?=.......
.......~OOOZI:....:IZOOOZZOOO$+:....~7ZOZOZOZOZ$,....,=$OOZOOOZOI~.....:~.......
.......~OZI~........~IZZZOZ$?:........=IOOZZZ$+,.......,$ZOOOZZ7................
.......=7~............~IOZI:............7ZO$+:..........,=7ZZ7=,................
.......,,...............=~...............~=:..............,~=...................
                                                               GlassGiant.com""" 
print "Hello World!"

<!-- THIS IS THE MAIN CONFIGURATION FILE FOR THE ENTIRE BLOODY DIRECTORY    -->
<!--    WHATEVER YOU DO, DO NOT EDIT THIS FILE WITHOUT TALKING TO ME FIRST  -->
<!--                                I'M SERIOUS                             -->
<!-- (scroll down) -->

From the 2004 Windows leak,

__inline BOOL
SearchOneDirectory(
                  IN  LPSTR Directory,
                  IN  LPSTR FileToFind,
                  IN  LPSTR SourceFullName,
                  IN  LPSTR SourceFilePart,
                  OUT PBOOL FoundInTree
                  )
{
    //
    // This was way too slow. Just say we didn't find the file.
    //
    *FoundInTree = FALSE;
    return(TRUE);
}

var something TBoolean; //Pickins

-- Beyond this point, there'll be dragons

I find it more pleasingly illustrative with the longer saying ^^


I found this

// This is a kind of magic...

I just finished a logging framework (that uses Trace, why nothing like this exists I don't know). I made a convenience base class that inherits from TraceListener. It overrides all of the TraceListener methods and routes them into one method - so that is a lot of doc commenting:

// TODO: Need some codemonkey to doc comment this class.

this has turned up in my own code a few times. obviously I touched it more than once:

// TODO: Fix this.  Fix what?

v.bpc     := v.pc;  -- Remember to jump back
v.baccu   := accu;  -- Yo dawg, heard you like runing instructions
                    -- so I took backup of your accu so you can run
                    -- instructions while you run instructions.
v.flags.i := false; -- No more interupts

In the header of a code file heavily edited by everyone on the dev team:

'Avert your eyes, it may take on other forms!

Good ol' Flanders.


on js code:

// hack for ie browser (assuming that ie is a browser)

/*
* After 36 hours, 2 holes in my wall and writing my code right beside the API
* this still doesn't work.
* function getMap():void takes in an event object @param: evt:mouseEvent
* I will now retire for the day with a bottle of rum and 2 hours of crying
*/

# Don use this. Never!

Looking back at old code from classes is fun...

    cardDeck.push_back(*(new card((rank)r, (suit)s)));  // Push each card onto the deck
                                                        // Temp. objects are overrated

While going through some things, it makes me wish I left more comments at 4 AM when I was hacking together random code...


BEGIN.
// Here might be dragons
.
.
 IF...
 // Beware of the Jabberwocky
 .//user the force, luke
 .
 .
 ENDIF.
.
END.

long long ago; /* in a galaxy far far away */ 

Case 1:
   ...
   break;
   ...
//I don't want do do this but [my coworker] says it's part of the code standard
default:
   break;

/* Halley's comment */

This one i found it in the package "twisted" for Python 2.5 (the file is tcp.py at line 371)

# Limit length of buffer to try to send, because some OSes are too
# stupid to do so themselves (ahem windows)
return self.socket.send(buffer(data, 0, self.SEND_LIMIT))

//Woulda
if(x) {}
//Shoulda
else if(y) {}
//Coulda
else {}

/*

 ____________________
/                    \
| Jean-Michel Bechet |
| 2002-2009          |
\___  _______________/
    |/
 (o_
 //\
 V_/_


*/

try {
  dataSource.close();
}
catch (SQLException ex) {
  // Do nothing, since we're going to trash this anyway
}

Of course, this sort of thing is actually a wtf in JDBC (or at least Oracle's JDBC driver) as it can throw SQLExceptions when closing a connection...


I am particularly guilty of this, embedding non-constructive comments, code poetry and little jokes into most of my projects (although I usually have enough sense to remove anything directly offensive before releasing the code). Here's one I'm particulary fond of, placed far, far down a poorly-designed 'God Object':

/**
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
*/

I'M SORRY!!!! I just couldn't help myself.....!

And another, which I'll admit I haven't actually released into the wild, even though I am very tempted to do so in one of my less intuitive classes:

// 
// Dear maintainer:
// 
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
// 
// total_hours_wasted_here = 42
// 

//Not a bug, parameter position can change..., if you think this is wrong, you are in fact wrong.

From Joomla! source:

// fudge the group stuff

// this is really complicated

with no other comments


-- Beyond this point, there'll be dragons

I find it more pleasingly illustrative with the longer saying ^^


<!-- THIS IS THE MAIN CONFIGURATION FILE FOR THE ENTIRE BLOODY DIRECTORY    -->
<!--    WHATEVER YOU DO, DO NOT EDIT THIS FILE WITHOUT TALKING TO ME FIRST  -->
<!--                                I'M SERIOUS                             -->
<!-- (scroll down) -->

// Houston, we have a problem


'NO COMMENT

From a battery monitor module in an embedded system:

// batmon.c drives the rastamobile

I inherited a project that haad been delivered to the customer without any UAT. It was dropkicked over the fence and the money requested.

First time they used it, it naturally blew up. It was an interposing library that overrode any system calls that took a file name as a parameter rather than a file descriptor.

Many system calls had been forgotten.

When I got onboard the code was laced with such gems as:

/* core dumps around here but this is hardly ever called */

and

/* don't know why this works but it seeems to be ok */

Oh, and there were no unit tests. A colleague had started to add the missing system calls and unit tests.

And the bastards who'd written the code were still in the team and didn't care at all about the garbage that had been delivered!


This comment is from an old project that i had to debug:

//Haleluya i can go home!

I think I had something of this sort:


if (case1) { // trivial
...
}
else { // we are screwed
 /* fill in later */
}

ok, so I might have used a stronger word than screwed


#define FUCK_VS6_CANT_COMPILE_TEMPLATES_WITHOUT_HANDHOLDING ((float*)0)

... 

SetPinsFromChannels`<float`>(&pinbuf, streambuf, &inmapper, FUCK_VS6_CANT_COMPILE_TEMPLATES_WITHOUT_HANDHOLDING);

Production source code:

// Remove this if you wanna be fired

//If only humans could leave things be.

//Please do not edit this code, 
//if you do you wont go to jail, you wont go directly to jail, 
//you wont pass go, you wont collect 200 dollars

try {
   doSomething();
} catch(err) {
   // Die quietly
   alert(err);
}

I've just placed this comment:

// this control (Resistance) is FUTILE! 

From the leaked Win2K source code:

// The magnitude of this hack compares favorably with that of the national debt.


I just checked this in the other day...

/// <STERNLY-WORDED-WARNING>
/// Pay attention to this or I will hunt you down.
/// ...
/// </STERNLY-WORDED-WARNING>

Where ("..." == "proprietary stuff that I can't post"). I just liked my STERNLY-WORDED-WARNING element.


In an art asset export tool, I stumble upon a complete translator from digits (arabic) numbers to roman numbers. It looked like this:

/*
//You can tell I was bored
//I wanted to do this for a long time
char* ConvertToRoman(int number, int base)
{
... whole code here
}
*/

The team of the person that wrote this code had been crunching for a long time, I guess it affected their sanity.


//ALL YOUR BASE ARE BELONG TO US

...it made my boss think someone had hacked in. He didn't know the joke.


Best one so far:

"This code makes baby Jesus very sad!". 

It was refering an String iniciatilization like this:

String blankSpaces="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //100 whitespaces
                   "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //200 Whitespaces
                   ...
                   "                                        " //100 whitespaces

Well you get the idea.


const int TEN=10; // As if the value of 10 will fluctuate... 

From C#

#region Hack - Shield Eyes Before Expanding

/// <summary>
/// A single uint with all of the bits set to represent the different tracing
/// </summary>
/// <remarks>
/// Ugly I know, so if you can think of a better way, feel free to rewrite.
/// </remarks>
[Browsable(false)]
public uint TraceBitfield
{
    // Snip
}

#endregion

// Jay knows what's going on here, but will he remember in a year? Not very likely, this code sucks, but it works so do not change it.

This comment was posted above a huge while-if-for block... Oh, and it manipulated an object array of object arrays of object arrays of strings that could be strings or numbers, depending on at least 3 factors... (yes, I had to debug this code and change it and I wrote the comment, however I did not write the original code). ;)


//Iterate by one
$i++;

Unfortunately it was mine, during my "Must comment everything phase".


This one was a living proof, in production code, of micro-management effects in our team:

// I am not responsible of this code.
// They made me write it, against my will.

... followed by less than optimal code, conceived by our beloved technical director, who was quite fond of forcing down both code and coding guidelines into developers' throats (*).

Of course, when the project leader searched for the cause of a bug, and found it was inside the "less than optimal code", he was less than amused...

(*) I am, of course, mentioning the Mighty VB King... If you want to assess the full magnitude of the power of the Mighty VB King, you can read the following SO post: What was the strangest coding standard rule that you were forced to follow? ...


// Replaces with spaces the braces in cases where braces in places cause stasis 
   $str = str_replace(array("\{","\}")," ",$str);

A German comment in some source-code, translated by machine or very tired human + Google

; Rechnen ja ; have faith in yes

I guess the original meant "assume true here" ... but ever since I've taken it as a mantra for my life.


// drunk, fix later

Wish I were kidding. And knowing the developer who wrote the code, I think he meant it literally.


# as you can see: I comment the code!


//There can Only Be one HIGHLAN....err..Singleton
public class SomeSingleton
{
...
}

// Added because boss changed his mind : 20020111,20020501,20020820, ...
// Commented out because boss changed his mind : 20020201,20020614,20020908, ...

In an ETL script between a mostly hacked RPG database and an SQL Server one. I had something like 10 or 20 occurences of this comment...


I inherited a project that haad been delivered to the customer without any UAT. It was dropkicked over the fence and the money requested.

First time they used it, it naturally blew up. It was an interposing library that overrode any system calls that took a file name as a parameter rather than a file descriptor.

Many system calls had been forgotten.

When I got onboard the code was laced with such gems as:

/* core dumps around here but this is hardly ever called */

and

/* don't know why this works but it seeems to be ok */

Oh, and there were no unit tests. A colleague had started to add the missing system calls and unit tests.

And the bastards who'd written the code were still in the team and didn't care at all about the garbage that had been delivered!


// this comment included for the benefit of anyone grepping for swearwords: shit.

// nobody read comments!

//Abandon all hope ye who enter beyond this point

From a battery monitor module in an embedded system:

// batmon.c drives the rastamobile

THIS PROGRAM HAS CODE THAT DOES NOT MEET STANDARDS      

That comment is in nearly every program we have here....


  rescue
    # silently, we fail
    # many validations fade
    # like tear drops in rain
  end

This is just one of many...


// Added because boss changed his mind : 20020111,20020501,20020820, ...
// Commented out because boss changed his mind : 20020201,20020614,20020908, ...

In an ETL script between a mostly hacked RPG database and an SQL Server one. I had something like 10 or 20 occurences of this comment...


I really almost like the oh_my_gawd tag better than the comment...

    /*
     * IOC3 is fucked fucked beyond believe ...  Don't even give the
     * generic PCI code a chance to look at it for real ...
     */
    if (cf == (PCI_VENDOR_ID_SGI | (PCI_DEVICE_ID_SGI_IOC3 b_type0_cfg_dev[slot].f[fn].c[where ^ (4 - size)];

    if (size == 1)
        res = get_dbe(*value, (u8 *) addr);
    else if (size == 2)
        res = get_dbe(*value, (u16 *) addr);
    else
        res = get_dbe(*value, (u32 *) addr);

    return res ? PCIBIOS_DEVICE_NOT_FOUND : PCIBIOS_SUCCESSFUL;

oh_my_gawd:

    /*
     * IOC3 is fucked fucked beyond believe ...  Don't even give the
     * generic PCI code a chance to look at the wrong register.
     */
    if ((where >= 0x14 && where = 0x48)) {
        *value = 0;
        return PCIBIOS_SUCCESSFUL;
    }

public function get state( /* of Palestine back */ ):Boolean

A comment I added to a PHP CMS I was working on a while back.

if (/*you*/ $_GET['action']) { //celebrate

Seen in some COBOL back in 1983:

   C   I don't know what this next bit does so I'll jump around it
       GOTO DONE.

// Bad Christian, No cookie

Cookie in this context does not refer to a browser cookie


//open lid


//take sh!t


//close lid

Comments for a File open, data dump, file close...


/* This is O(scary), but seems quick enough in practice. */ 

followed by four nested for-loops


//The below code needs to be commented out.


// John! If you'll svn remove this once more,
// I'll shut you, for God's sake!
// That piece of code is not “something strange”!
// That is THE AUTH VALIDATION.

And what do you think? The code below was safely ‘svn removed’.


/* This is a replica of a horrible hack - many moons ago, the legacy PortfolioServer was modified to return cash trades in an "optionTrade" block, because the client side developer was too lazy to get their XPaths right. Their laziness echoes through the ages, and means we need a similar hack here...*/


// Fuck.

That, and...

// This code worked before, but my cat decided to take a trip across my keyboard...

This is from an old IOCCC winning entry, I had to download the whole archive of winners -- a humongous 1.4 M -- and grep for several phrases I remembered wrong before finding it.

Syntactically this is probably not a comment. Or may be it is. I haven't figured it out. It definitely does not have comment delimiters, but it doesn't have String delimiters either.

C="Lint says "argument Manual isn't used."  What's that
mean?";

No prices for guessing the output from lint.

And for the curious, that entry is here.


This was actually made by me when I was implementing a prototype turned into real code:

// Abandon all hope you who needs to debug this

Yes, someone smarter than me actually refactored the code afterwards (it had to have a good ending).


Comment in our Enterprise Class system used for Government purposes

'RH 5/24/06 burn me if this dosn't work.. :)

Good ole RH.....company Prez/Lead Developer


[vrk:Cloud ID="cTags" runat="server" DataTextField="Tag" DataWeightField="Total"
    Width="100%" DataHrefField="Tag" DataHrefFormatString="~/tags.aspx?tag={0}"]
[/vrk:Cloud]

[!--if anybody would like to change the control's color contact with FLORJON--]

Repeat
    ...
Until (JesusChristsReturn) ' Not sure

""".........................:~+?7$$$ZZZZZZZ$$$7I+=:,............................
........................~+7ZZZZZOZZOOZOZZOZOZOOZZZZZ7?~:........................
......................,~7$ZZOOOOOZOZOZOZZOOZZOZOOOOOZ$$I,.......................
...................,=I$OOZOZOZZOOOZZOZOOOOZOZZZOOZZZOZZOZI=:....................
.................:?$ZZOOZZOZOZZOOOZZZOOZOZOZZZZZZZOZZOZOOOZ$I~..................
................IZOOOZOOOZZZOZZZZOZZOZOOOOZOZZZOOZZZZOOZOZZZOZ7=................
...............~ZZOZZOZOOZOOZOZOZZOZOZOZZZZZOZOZZOZOOZOZZOOOOZZ7................
.............:IZOOZOZZZZOZOZZOZOOZOZOZOZZOZOOZOOOOZOZZZZZOZOZZOOI~..............
...........,+$ZOOZZOZOZOZOZOZZOZOZOOZZOZZOZZOZOOOOZOZZOZZOOZOOOOO$?:............
..........:IZZOOOZOZZZZOOZOOZOZOZZOZOZZZZOZOOZOZZOZOZOZOOOOOOOZZZOZ7~...........
..........+$OOZZZOZZOOZOOZZZZOZZOZOZZOZOOOZOZOZZOZOZOZOOOOOZ$$77I77$+:..........
........,?$OOZZZZZZZOZOOOZOZZOZZZOOZOZOOOOZOZZZOOZOOZOOO7?~:,.......,...........
........+ZOOZZZZZOZOOZOOZZZZOZZOOOZZZOZOZOOZZOZOZZZOOO$?........................
........$ZOZZZOZZZZOZOOZZZOZOZZOOOOOOOOOOOZOZOZZOZOO$?,.........................
.......:ZOOZOZOZZOOZZOZOZOZOOOZOOOOOOOOOOOOOOOZOZOOZI:..........................
.......+OOOZOOZOZOZOZZZOOZOOZOOO$I+=~:::~+I$OOOOOOZ?:........,:=,...............
......:7ZOOZOZZOOOZOZOZOOZOOZ$I=............:?$OOZ7:.......:IZOOZ?,.............
......=$OZOZOOZOOOOOZOZZOOZ7=,................:?O$+.......~7OOOOOZ+,............
.....,?$OOOOOZZZZOOOOOOZOZ?,....................ZZ=.......=$OOZOOZ+,............
.....:IZOZZ$777I7$ZOOOOOZ7~.....................$Z=.......~7OOOOO7=.............
.....:+?~:,.......,~IZOO7~........~+II?=........?$?,.......:I$ZZ?:..............
.....................+ZO=,......:IOOOOOZ:.......=7$~............................
.....................:IO~.......=OOZOZOO=,......~7O7~...........................
...........:~:.......:IO~.......+OOOOZOO=.......~78Z?,.................,:.......
..........:IZ7~......+ZO~.......:7OOOOO$,.......+$OOZ7=,.............:?$=.......
...........,,.....,=7ZOO+,.......,=II?=:........7OOOOOOZ=:,.....,:=I$ZOO=.......
....................,:+$7=.....................~OOOZZZOOOZZ$$7$$ZOOOOOOZ=.......
......................:?Z?,...................:?OZOOZOOZOOOOOOOOOOZOZOZO=.......
............,::,.......,OO7:................,+$OOZOZOOZOZZOZOZZOOZOZOZOO=.......
...........~$8OI........$OOZI~,.........,:=IZOOZOZOZOZOOOZOZOZOOOZZZOZOO=.......
...........:??=:.......:OOOOOZZ7+=~~==+?$ZOOOOZOOOZOZOZOOZOZOZZOZZOZOZZO=.......
............::,.......,+OOZOOOOO$7777$$ZOOOOOZOZZZZOZOZZZOOZOZZOOOZOOZOO=.......
.....................=7OOZOOZOOZOOOOOOOOOZZZOZOZZOZOZOZOOOZOZOZZOZOOZOOO=.......
................,:=I$OOOZZOOOZOOOOOZOZOZZZZZOOZZZOZOZZZOOZOOZOZOZOZOZOOZ=.......
...........:~+?7ZOOOOOOZZZOZOOZOZOOZOZOZZOZZOZOZZZZOZOZZOZOZOZZOZOOZOOOZ=.......
........$$ZOOOOOOOOZOZOZZZZOZOZOOOZZZOZZZOZOOZOZZZZZZZZOOOZOOZZZOZOOZOOZ=.......
.......~OOZOOZZOOZZZZZZOOZOZOZOZZOOZOOZZZOZZOZOZZOZZZOZOOOOOZOZOZOOZOOOZ=.......
.......~OOZOOZZOZZOZOZZOZZOZOOZOZOOZOZOZZOZOOZOZZOZOZOZOZOOZOZOOOZOOZOZO=.......
.......~OOZZZOZOOOZOZOZZOZOZOZOZOOZOOZOOOOZOZOOZOOOZOOOZOZZOZOZOOZZOOOOZ=.......
.......~OOZZOZOZZZOOZOOZOZOZOZZOZZZZOZZZZOZOZZOOOOZ$ZZZZZZOZZZOZZOZOZZZO=.......
.......~OOZZOO$??$OOZOOZZOOZOZOZ+~IZOOOZOZOOZZOOZI==IZOZZOZOOZOZZOZI~=7O=.......
.......~OOZO$I:..~IZZZOZOZOZOZ$+...=7ZOOZOOZZOZZ=,..,=$ZZOZZZZZOZI~...,?=.......
.......~OOOZI:....:IZOOOZZOOO$+:....~7ZOZOZOZOZ$,....,=$OOZOOOZOI~.....:~.......
.......~OZI~........~IZZZOZ$?:........=IOOZZZ$+,.......,$ZOOOZZ7................
.......=7~............~IOZI:............7ZO$+:..........,=7ZZ7=,................
.......,,...............=~...............~=:..............,~=...................
                                                               GlassGiant.com""" 
print "Hello World!"

// This should fix something that should never happen

Upon being forced to write unit tests for anemic domain objects that are nothing but bags of getters and setters (which I was forced to write as well):

// zzzzZZZZzzzz....

long john; // silver

At the top of a header file:

/* Project : XYZ (Please somebody shoot me!)
 *
 * File : $Id: defs.h,v 1.1 $
 *
 * Purpose : Create havoc rather than peace among many nations
 *
 * History : Back-ported changes that were not in CVS.  Please somebody,
 *  shoot us and put us all out of our misery.
 */

The "XYZ project" (name changed) was a seven-year ordeal. That last comment was written by the one stalwart soul who was involved from the very beginning through to the end.


[onload_1;block=begin;when 1=0]

Some of the techinques in this template are rather obscure, just trust me, they need to be there.
OTOH a better sollution would be to create a few seperate templates and pick one in the php-script...

[onload_1;block=end]

i just noticed myself writing this

// not brilliant solution, but fair enough heh.

I once implemented some document workflow using MS SQL Server Developer 2000 (the human workflow stuff).

It consisted of a bunch of triggers that would be added to the database to make it follow workflow rules.

In one of the triggers, someone at Microsoft had written something along the lines of:

//Determine if the database has been "Grizzlified"

(The internal name of the product was "Grizzly", so I thought that was funny).


// but the "real" solution is much more complicated

from jpgraph


/**
 * Not even your mum thinks you're special if you call this method
 */    
onlyYourMumThinksYoureSpecialIfYouCallThisMethod() {...}

/* My lawyer told me not to reveal */

/**
 * Happy Javadoc haiku:
 *
 * Without Javadoc
 * Builds break in Maven site stage
 * This fixes the build.
 */

From Joomla! source:

// this is daggy??

If you have reached this part in the code, then this program sucks.

//Iterate by one
$i++;

Unfortunately it was mine, during my "Must comment everything phase".


// human madable inconvenient. Way too sucks.

I still don't fully understand what it means, but I have found it to be very true about a lot of code.


Re eating one's own dogfood: We have the same term in our workplace (granted, only because I introduced it). My code is peppered with comments that say "TODO" and indicate something that ought to be done eventually, but a comment saying "DOGFOOD" (both keywords are always at the beginning of the comment, in all caps) means something that must be done before this program can be used even internally. It's a handy thing to search for, as the word "dogfood" is never going to appear in a quoted string - if it does, I can always just say "dog-food" or something - so even a case-insensitive search will come up with the right results.

Regarding zeroing the accumulator: I've done exactly the same thing when programming an Intel 80x86 (I started on the 8086 and moved up from there into the modern Pentiums). XORing a register with itself is the quickest and tightest way to clear it. Using "MOV AX,0" requires three bytes (opcode and two bytes of literal 16-bit zero), whereas "XOR AX,AX" is only two; it's even more noticeable with the 386-and-higher extended registers, where "MOV EAX,0" requires five bytes (four bytes of 32-bit zero). My C/C++ compiler always zeroes registers this way, so I'd assume it's still the best way (although I haven't studied opcode timing tables in ages, and probably both XOR reg,reg and MOV reg,imm take one clock).


Simple but effective comment, before a less than safe hack in some C++ code

// yikes

When I was taking a CS class in Highschool, we were being taught in a regular classroom - no computers. All our tests were done on paper that we handed in - one class per sheet of paper. Our teacher was teaching the class in C++ for the first time and would occasionally switch into Pascal mode on the chalkboard. This was awkward, as few of us had interest in learning Pascal.

For larger than in class work, we would do them at home and hand in code + output printouts to be graded. After submitting a few code + output printouts, we collectively realized that the teacher wasn't actually reading the code - just the printouts. To test our theory, I put in a comment on the 3rd page of my code - right between some class declarations:

// If you are reading this, please place a checkmark here [  ]

Of course, I got it back with a big blue "A" on the front and no checkmark to be found.


In a class named "Bar" (which was a UI Control with a less than descriptive name), the class header:

/// <summary>I pity the "foo".</summary>

And the Remove() method:

/// <summary>A "foo" and his money are soon parted.</summary>

Even worse, it was a business partner that pointed it out from the generated documentation. Even worse than that, is those are probably the closest things to useful documentation we ever got out of the guy.


Recompiling FreeTextBox3 for the first time in our application because we need IE8 support... And look what I've found:

// IE7 update. this is still bad code, but IE8 is probably a long way off :)

I don't have the code to share, but imagine this scenario. About a month or two after our Linux Sys Admin left for greener pastures, I had the pleasure of opening a shell script he'd written. I can't recall why I needed to edit it, but that's not what matters. What's important is that the script was about 40 lines long. I scrolled past the commenting (of which there were 37 lines) to reach the actual working code (3 lines). The code was great, but I was curious - why 37 lines of commenting? So, I scrolled to the top and proceeded to read. To my surprise, the commenting was a rap about what the three lines of code did and how to change it. The best part - it was a partial rip off of Nothing But A G Thing by Dr. Dre and Snoop D O DOUBLE G. Thanks Brian!


// for 8 or 12 threads this does not affect much.
// Strange are the situations if not understood properly.
// Yoda strikes again

In a mutli-threading module! :)


public int hashCode() {
//sucks, but what're you gonna do

/*
int hash = 7;
for (int i = 0; i < array.length; i++)
    hash = hash * 31 * (null == array[i] ? 0 : array[i].hashCode());
return hash;
*/

return 0;
}

// *** drunk -- fix later ***

direct link

More fun with google code search...


// TODO: not this

Written by a colleague above a query in desperate need of optimization. In his defense, we'd all been working 70-hour weeks for a few months at that point...


When I'm commenting out chunks of code that I THINK are no longer useful, but I might be wrong about (hence not deleting them) I will sometimes preface them with

// Wilted celery?

The idea being that this is like celery that is wilted, but you put it back in the fridge anyway. I just know that 10 years from now someone else will find these comments and say WTF?


I was doing a database in Access, very simple thing - at least it was supposed to be at the start or I would have done it in Delphi. The client wanted to be able to get the customer info out of the database but they would not enter enough information to reliably identify the customer. I told them to use the phone number as the key as each customer (the way they worked, not for everyone) would have a different number. After a few frantic calls from them, (It's not working we can't enter the customer) I discovered that they were too lazy to look up the phone numbers from their old system and were trying to enter all the numbers they did not know as "n/a". In trying to sort this out for them I ended up with a lot of checking loops in the code and had the comment beside one outcome "This should never be reached if they do what they are supposed to do!!!!!!!!!"

They also asked me once "How can we find the right customer even if we put in the wrong address?" And all for peanuts.


Found in the main trigger code for transactions in an OLTP database:

-- This line negates the @inverseqty, which is the
-- negative of the @insertedquantity.  This works through the
-- magic of the trigger.  In fact, this code is a lot like
-- the bermuda triangle!
@negquantity = -1 * @inverseqty

From a classic from usenet:

Deep inside the Teradyne hardware modeler code is a routine that feeds a whole bunch of hex numbers into a SYS$QIO call. The only comment is 'Weird magic happens here'.


In an LKM:

/*
* Dear Richard Stallman,
*
* This one's for you.
*
* Sincerely,
* Me
*
*/
MODULE_LICENSE( "GPL" );

I just ran into this in some of my own code. It was in a magento admin template for category selection:

        /*
         * OK; before you read the following code know what I am trying to do.
         * I needed to get the list of child catagories from the root node so that
         * the root node didn't appear in the selection box. But for some stupid
         * fucking reason the stupid fucking DBA wont let me access the items using
         * indicies and I instead have to use their stupid fucking Iterator
         * implementation. So there.
         */
        $firstList = $this->getRootNode()->getChildren();
        foreach ($firstList as $node)
        {
            $nodes = $node->getChildren();
            break;          // wtf?
        }

I am going to remove the language of course out of our flagship product; but I remember I was super frustrated. If I hadn't left a comment, I would try to revise it but then run into the same problems I had before.


/* Emits a 7-Hz tone for 10 seconds.
  True story: 7 Hz is the resonant frequency of a
  chicken's skull cavity. This was determined
  empirically in Australia, where a new factory
  generating 7-Hz tones was located too close to a
  chicken ranch: When the factory started up, all the
  chickens died.
  Your PC may not be able to emit a 7-Hz tone. */

main()
{
    sound(7);
    delay(10000);
    nosound();
}

(the sound function in the Turbo C version 2.0 Reference Guide)


# Don use this. Never!

Repeat
    ...
Until (JesusChristsReturn) ' Not sure

I just found this one in a custom Linq provider for .net:

//select is a royal pain in the ass where 
//the parameter passed to CreateQuery isn't actually the one that goes in the call
//requiring this workaround.  Not sure how straight Linq to Objects does it.

And this one

//expressions have to be compiled in order to work with the method call on 
//straight Enumerable somehow, LINQ to objects itself magically does this.  
//Reflector shows a mess, so I (Aaron) invented my own way.  God love unit tests!

And i just found this one as well... it just gets better

  //ok, this is a hairy, dirty, and nasty piece of code
  //the alternatives are substantially worse than this though
  //i.e. when you do your own provider, LINQ assumes that
  //you are going to implement your own expression tree visitor and
  //do it all yourself.  Frankly, I still have xmas shopping to do
  //and I really don't want us to be foobared when we get
  //even more extension methods added to LINQ
  //therefore, we are pulling execute based on taking the calling the 
  //standard execute on enumerable, but using our own class
  //
  //optimization can occur from here on an as needed basis, that is
  //check for the value of mex.Method.Name, and write a handler for
  //that method
  //
  //also, it may not be a bad idea to rather than do this reflection 
  //each and every time somehow cache the reflected methodinfos and do 
  //lookups that way that said, we need a complete red/green/refactor 
  //cycle here before I am touching that one

And this one

//Compile that mutherf-ker, invoke it, and get the resulting hash

I didn't encounter this firsthand, but it makes for a good story (see explanation in my comment):

#define MSGTAG_B33R     0x723 /* RIPLVB */

I found this:

I'm not sure what I did

There was some old javascript code, quite well written tho. Then was a comment line

// and there is where the dragon lives

followed by a function 4 people spent a day to understand what it's doing. Finally we realised it's not even used and does nothing.


Seen in some COBOL back in 1983:

   C   I don't know what this next bit does so I'll jump around it
       GOTO DONE.

Spelunking through the Hardware Abstraction Layer while working for a certain Finnish Mobile Network Equipment Manufacturer I found 100+ occurrences of the Finnish word "puukko".

A 'puukko' is an all purpose knife that every Finn has in their toolbox or around the house. It is used for everything from pealing potatoes to performing computer repairs (my observations). I believe in this context it is the Finnish equivalent of the word 'Hack'.

My Finnish colleagues denied this and said it meant something more like 'surgical procedure/intervention'... and I almost believed them until I found the comment:

/* Perkele ISO Puukko! */ -> Fucking Big Hack!

In SJ CA back during the early days of the auction business I worked with a guy named Rick Dorin. He wrote compilers back when you had to poke at cards all day long. One of his error messages was

Too Many Errors... Make fewer!


Once I saw in another discussion something like this:

// I can't divide with zero, so I have to divide with something very similar
result = number / 0.00000000000001;

Clever solution, isn't it :) ? (It's a joke if someone's not sure)


Taken from the Quake III source, I stumbled across this in some random slashdot posting. Full source of the file can be found here. It's a particularly fast method of calculating an inverse square root. As for the best comment? It's a common one to be sure, but given that it's attached to the line that does the magic is what makes it great.

float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the fuck?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}

Near the top of a unit:

// Oh what a tangled web we weave
// When first we practice to deceive
// ASTA

// HACK ! COPY/PASTE this and look for another job

// This code was written by a genius so don't try to understand it with
// your tiny little brain.

Best one so far:

"This code makes baby Jesus very sad!". 

It was refering an String iniciatilization like this:

String blankSpaces="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //100 whitespaces
                   "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "+ //200 Whitespaces
                   ...
                   "                                        " //100 whitespaces

Well you get the idea.


// THE LOOP THAT DO EVERYTHING!!!!!!!

// Houston, we have a problem


// TODO: what the hell is this all about?

And then some commented out code.

This was found in our code in work earlier today. I'm not sure if I should laugh or cry...


// This condition can't happen. Call the police or something.

Honest to God:

// This is crap code but it's 3 a.m. and I need to get this working.

//Visual Studio Bug Workaround:
//http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101677

//To fix 'CJumpToHelper::GetInstance()' : undeclared identifier compiler errors, change the number lines below
//until the file compiles correctly. (This needs to be done anytime a change is made to this file)

    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines
    //////////////////////////////////////: There should be 1-10 of these lines

//Woulda
if(x) {}
//Shoulda
else if(y) {}
//Coulda
else {}

I once came up with what I thought was an elegant solution to a particularly sticky problem, in retrospect it was a bit of a mind-bender and made some heavy use of macro programmimg. Years later I found this comment from a maintenance programmer

/*
    Description: The Total Perspective Vortex derives its picture of the
                 whole Universe  on the principle of extrapolated matter
                 analyses.

                 To  explain  -  since every piece of matter in the Universe
                 is in some way affected by every other piece of matter in
                 the  Universe,  it  is  in  theory possible to extrapolate
                 the whole of creation - every sun, every planet, their
                 orbits, their composition and their economic and social
                 history from, say, one small Macro.

                 The man who invented the Total Perspective Vortex did so
                 basically in order to annoy the IT department.

                 Steve Weet - for that was his name - was a dreamer, a
                 thinker, a speculative philosopher or, as some would have
                 it, a slacker.

                 And they would nag him incessantly about the utterly
                 inordinate amount of time he spent staring out into space,
                 or mulling over the mechanics of Chelsea FC, or doing
                 spectrographic analyses of macros.

                 "Have  some  sense  of  proportion!"  they would say,
                 sometimes as often as thirty-eight times in a single day.

                 And so he built the Total Perspective Vortex - just to show
                 them.

                 And into one end he plugged the whole of reality as
                 extrapolated  from one  macro, and into the other
                 end he plugged the IT department: so that when he turned it
                 on they saw in one instant the whole infinity of creation 
                 and theirselves in relation to it.

                 To  Steve Weet's horror, the shock completely annihilated '
                 their brains; but to his satisfaction he realized that he
                 had proved conclusively that if life is going to exist in a
                 Universe of this size, then the one thing it cannot afford
                 to have is a sense of proportion.

*/

Case 1:
   ...
   break;
   ...
//I don't want do do this but [my coworker] says it's part of the code standard
default:
   break;

In some assembler, at the end of a line that contained &h723

' RIP LVB

(get it?)


// TODO: Delete

Not a comment but an attribute

[ThereBeDragons]

And one I have seen in an implementation of IHttpHandler

//What is this?
public bool IsReusable
{
    get{return false;}
}

From Joomla! source:

// fudge the group stuff

/* Please work */

From /System/Library/Frameworks/AppKit.framework/Versions/C/Headers/NSTextView.h:

- (void)smartInsertForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace beforeString:(NSString **)beforeString afterString:(NSString **)afterString;
- (NSString *)smartInsertBeforeStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;
- (NSString *)smartInsertAfterStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;

/* Java note: The second and third methods are the primitives and are the 
methods exposed in Java.  The first method calls the other two.  All 
Objective-C code calls the first method.  In either Objective-C or Java any 
overriding should be done for the second and third methods, not the first 
method.  This will all work out correctly with the exception of existing code 
that overrides the first method.  Existing subclasses that do this will not 
have their implementations available to Java developers. Isn't Java wonderful? */

//Do not continue reading if you dont want to die.

This one almost killed me.


Some years ago I was working in a large code base that had no unit-testing to speak of.

There was a method buried deep within the code that performed some calendar calculations. It was somewhat broken, had to deal with daylight savings in a very clumsy way due to some unfortunate circumstances.

We had to fix it a couple of times, and every time, we would find something broken some months after.

After spending a whole day fixing it and analyzing it, I put the code in source control, along with a comment that said something like this:

// this code was written after a version trying to do {this} failed because of {reason},
// previously we were doing {this} which failed because of {reason}. This is 
// now written {this} way so that {lots of reasons here}. If you want to touch
// this code, please make sure that it produces the right answers when tested with:
//
// {some sort of unit test}

Ultimately, my team was outsourced. Some days I wonder what happened to this code :)


I found this:

I'm not sure what I did

if(count<0) count=0;    //don't get me wrong but this has to be done :p

Sanitized:

//Forward declarations:

class X {}; // TODO: Remove {}  ! When we get X defined....

//I am not sure why this works but it fixes the problem. 

This was before a set of code that technically did fix the problem it was meant to but broke 3 other things....


Classics from the old netscape mozilla code. Personally I like

just can't fuck around. Oh, also moving memory would doom us anyway, and it'll all just be too damn hard to figure out. So, I give up, the Mac just completely utterly sucks complete rocks

but there are a lot of other fun ones.


// TODO: not this

Written by a colleague above a query in desperate need of optimization. In his defense, we'd all been working 70-hour weeks for a few months at that point...


//If you're reading this, then my program is probably a success

// A Gorgon class - For the love of Zeus don't look directly at it!

This one was a living proof, in production code, of micro-management effects in our team:

// I am not responsible of this code.
// They made me write it, against my will.

... followed by less than optimal code, conceived by our beloved technical director, who was quite fond of forcing down both code and coding guidelines into developers' throats (*).

Of course, when the project leader searched for the cause of a bug, and found it was inside the "less than optimal code", he was less than amused...

(*) I am, of course, mentioning the Mighty VB King... If you want to assess the full magnitude of the power of the Mighty VB King, you can read the following SO post: What was the strangest coding standard rule that you were forced to follow? ...


// Hard to explain

It ended up being broken, too. No wonder it was hard to explain


int Q13Factor = 8125; // 2^13 for Q13 

In Latin, Abandon hope all ye who enter here from Dante's "Divine Comedy".


def leppard
# what, i cant have my own convention?
end

// HACK ! COPY/PASTE this and look for another job

// TODO: Delete

options.BatchSize = 300; //Madness? THIS IS SPARTA!

# dont question, i just felt like throwing some globals in
# this is actually quite pointless as youll soon see

later in the code

#draw the circles (complicated)...dont question

even later...

# complicated process of drawing the circles in a
# somewhat symmetrical, 3-d pattern
# dont question again

and even later...

# will determine if user clicks on die
# i determined these values...dont worry about them

I've seen this code in a function FULL of Explicit weird casts:

// Since today's CPUs are really fast, this is dedicated to those who said:
// " You can't use Moore's Law as an excuse to write bad software. "

The code was horrendous :)


#define FUCK_VS6_CANT_COMPILE_TEMPLATES_WITHOUT_HANDHOLDING ((float*)0)

... 

SetPinsFromChannels`<float`>(&pinbuf, streambuf, &inmapper, FUCK_VS6_CANT_COMPILE_TEMPLATES_WITHOUT_HANDHOLDING);

Fix problem where Nulls don't work properly.  Stupid Microsoft!

Code converted Nulls to zero-length strings line by line in roundabout way because the stupid programmer did not understand what Nulls are and had never heard of the Nz() function.


From http://www.madore.org/~david/computers/callcc.html:

/* Yow!  DEMONS are flying through my NOSE! */

-- Change Log:  Not needed. The code is perfect 'cause I wrote it.
-- If you change it, it will break.

I'm in the middle of reviewing some code comments to check they make sense, and saw the modest line above.


at the end of a rather long and convoluted set of while loops and if blocks, the developer in question inserted this final comment:

else
{
    // wobbly wilson said this would *never* happen!!
}

a laconic mixture of wit and sarcasm :)


This one i found it in the package "twisted" for Python 2.5 (the file is tcp.py at line 371)

# Limit length of buffer to try to send, because some OSes are too
# stupid to do so themselves (ahem windows)
return self.socket.send(buffer(data, 0, self.SEND_LIMIT))

Exception up = new Exception("Something is really wrong.");
throw up;  //ha ha

// GK Experimental

(GK being the initials of the coder)

Used to indicate parts of code which are, indeed, kind of experimental. :)

A great flag to know that when you hit it during debugging you're probably busy for the upcoming few hours fixing the hack.. ;)


int main(void)
/* Program starts here */

if(count<0) count=0;    //don't get me wrong but this has to be done :p

On initialization of a linked list:

last = first; /* Biblical reference */

Succint and hilarious.


// *** drunk -- fix later ***

direct link

More fun with google code search...


// A Gorgon class - For the love of Zeus don't look directly at it!

I don't have the exact code package anymore, but I remember the comment vividly.

// The code below needs to be changed immediately.
// I wish I was a little bit taller
// I wish I was a baller
// I wish I had a girl who looked good, I would call her.

I often found this one

// fix it!

This is so much nicer than the scary legal notices and disclaimers you see in many comment headers. From SQLite.

/*
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
*/

//        .==.        .==.          
//       //`^\\      //^`\\         
//      // ^ ^\(\__/)/^ ^^\\        
//     //^ ^^ ^/6  6\ ^^ ^ \\       
//    //^ ^^ ^/( .. )\^ ^ ^ \\      
//   // ^^ ^/\| v""v |/\^ ^ ^\\     
//  // ^^/\/ /  `~~`  \ \/\^ ^\\    
//  -----------------------------
/// HERE BE DRAGONS

I don't have access to the original file because I don't work there anymore, but it was something very similar to this picture. It was at the top of a file that always caused troubles, that we had to fix but not allowed to take the time to really fix. (University politics)


This was the only comment we found in a smartcard product that a previous employer bought in. A load of embedded C and assembler written by a bunch of Dutch cryptography PhDs

// echt halmaal gek - no way!

(It means something like "really completely stupid"...which didn't help us either)


From Joomla! source:

// this is daggy??

A few from the Linux kernel:

/* Sun, you just can't beat me, you just can't.  Stop trying,
* give up.  I'm serious, I am going to kick the living shit
* out of you, game over, lights out.
*/

-

/* 2,191 lines of complete and utter shit coming up... */

-

#if 0 /* XXX No fucking way dude... */

One of the most classic ones is the comment made by Pierre de Fermat about his well-known "Last theorem": "The margin of this page is a bit too small to write down the proof".

It took more than 350 years before the proof was found...

(According to wikipedia this is the original text:)

Cubum autem in duos cubos, aut quadratoquadratum in duos quadratoquadratos, et generaliter nullam in infinitum ultra quadratum potestatem in duos eiusdem nominis fas est dividere cuius rei demonstrationem mirabilem sane detexi. Hanc marginis exiguitas non caperet.

...and translated into English:

(It is impossible to separate a cube into two cubes, or a fourth power into two fourth powers, or in general, any power higher than the second into two like powers. I have discovered a truly marvellous proof of this, which this margin is too narrow to contain.)


//Dear future me. Please forgive me. 
//I can't even begin to express how sorry I am.  

And I just found this one today:

//private instance variable for storing age
public static int age;

/* Only break the connection if it actually exists. It is important to
 * check the timeslot saved in the SOURCE of the disconnect message. */

I wrote this comment, and now I can't remember WHY it's important...


I didn't encounter this firsthand, but it makes for a good story (see explanation in my comment):

#define MSGTAG_B33R     0x723 /* RIPLVB */

// Catching exceptions is for communists

From Mike Duncan's page on SQLite.


//Iterate by one
$i++;

Unfortunately it was mine, during my "Must comment everything phase".


catch
{     
    // you’re fucked
    // write out the file somewhere and start screaming “Connection down! Connection down!”
}

/**
 * Happy Javadoc haiku:
 *
 * Without Javadoc
 * Builds break in Maven site stage
 * This fixes the build.
 */

// This is confusing, I KNOW, so let me explain it to you.


/**
 * Hexadecimal digit
 */
protected $version = -1;

// Keep prozac ready if things get ugly!

// Fuck.

That, and...

// This code worked before, but my cat decided to take a trip across my keyboard...

// some sport psychology
if (!focused)
    Focus();

// No women, no children... What movie???

Found this in makefile

# ===== Never edit below this line. Ever. Or I'll kick your ass. ====

Here's a few that I've put in my code at various times. Some aren't technically comments, but they're the same sort of concept.

In a cross-platform project that needs some special code on one platform only:

//If defined, will include all the Windows-specific code.
#define LOSE

#ifdef LOSE
#include <windows.h> //WIN32. Duh.
#endif


---------------------------------------------------


//Stolen from other_project_name.cpp


---------------------------------------------------


/*
 * These comments have been lifted from propagate() and, though they no longer apply to the code, they may still be of value somewhere. Original tabbing and structural elements have been preserved.
 */
    //CAUTION: This has a major Bobby Tables risk. Even if a rulebuilder is used, there's still the risk of something getting corrupted in the database itself.
    //Reading text from anywhere and simply slotting it into an SQL statement is a major security risk. (With thanks to xkcd for the name "Bobby Tables".)
    //Requirement: Eliminate one Bobby Tables by changing [redacted] to be not just straight SQL.
[lots more comments that are not as funny]
/*
 * End of lifted comments. There should not be any executable code between these markers.
 */


---------------------------------------------------


        /*
        Okay. It's unrecognized. Why is this a fatal error? It's actually very closely akin to the miswart of botched #includes being a fatal. When writing a C/C++
        program, you need your headers, and if you don't have one, chances are there'll be a million cascaded errors; so by making "unable to open asdf.h" a fatal,
        the compiler suppresses all those errors about undefined symbols and potentially misspelled type names.
        */


---------------------------------------------------


    //If someone tries to import 'id' as a field name, it won't work. (We already have our own id.) But I think the probability is so low that I can afford to be funny.
    if (!stricmp(ptr,"id")) {warn(0,"Import","","'id' is a reserved word and cannot be used as a column name. (Try 'ego' or 'superego'.)"); return;}


---------------------------------------------------


//Need a place to squirrel away SQL statements somewhere
char *uts[1024]; //Unified Temporary Storage. (Why? Because I said so.)
int nuts=0; //What is it that squirrels keep? Ha!
int utsid[sizeof uts/sizeof *uts];


---------------------------------------------------


        /**************************************\
         * NOTE: This sets tilde.action. If a *
         * tilde header does not exist in the *
         * import file (not the _content_, if *
         * the entire column isn't there), it *
         * will duplicate down through all of *
         * the rows. This is fine for ~id, as *
         * that will never be changed; and if *
         * ~Quantity is blank, that throws an *
         * error in 'Add'. With ~Action, I am *
         * not so certain. I THINK it'd be OK *
         * to dup-down most of the time... if *
         * the user only ever imports Adds or *
         * Revises, but never both at once in *
         * a single import. So for safety, to *
         * allow a blank ~Action to revise OR *
         * add, I'm breaking the check out to *
         * a new variable - the curaction. In *
         * most cases, it won't be needed, so *
         * it's a waste; but it isn't like it *
         * has to copy the entire tilde.*, so *
         * it's only a small waste. So it can *
         * waste a register... big deal. OK ! *
        \**************************************/


---------------------------------------------------


            //if (!response) // we're going to crash
            //if (!items) // we're going to crash
            //TODO: Don't crash


---------------------------------------------------

A lot of my comments contain obscure references to films or musicals, but they won't be nearly as funny if you don't know the show.


// Empty constructor to satisfy the stupid compiler
 Public ServletHandlerClass () { } 

map(TimeZoneId.Romance, "Romance Standard Time"); //LULZ.

An old boss of mine was always going on about how we had to use our own products internally i.e. "Eat our own dog food..."

Many years later I found embedded in some source that a temporary coworker had done, every function he touched is tagged with:

/* NOT FIT FOR HUMAN CONSUMPTION */

//The following 1056 lines of code in this next method 
//is a line by line port from VB.NET to C#.
//I ported this code but did not write the original code.
//It remains to me a mystery as to what
//the business logic is trying to accomplish here other than to serve as
//some sort of a compensation shell game invented by a den of thieves.
//Oh well, everyone wants this stuff to work the same as before.
//I guess the devil you know is better than the devil you don't.

    /* Mark: If there's one thing you learn from this code, it is this...
   Never, ever fly Air France.  Their customer service is absolutely
   the worst.  I've never heard the words "That's not my problem" as 
   many times as I have from their staff -- It should, without doubt
   be their corporate motto if it isn't already.  Don't bother giving 
   them business because you're just a pain in their side and they
   will be sure to let you know the first time you speak to them.

   If you ever want to make me happy just tell me that you, too, will
   never fly Air France again either (in spite of their excellent
   cuisine). 

   Update by oej: The merger with KLM has transferred this
   behaviour to KLM as well. 
   Don't bother giving them business either...

   Only if you want to travel randomly without luggage, you
   might pick either of them.
   */

#!/usr/bin/sh
#       Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T
#         All Rights Reserved

#       THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T
#       The copyright notice above does not evidence any
#       actual or intended publication of such source code.

#ident  "@(#)false.sh   1.6     93/01/11 SMI"   /* SVr4.0 1.3   */
exit 255

Taken from SunOS 5.9 aka Solaris 9 (/usr/bin/false)


Honest to God:

// This is crap code but it's 3 a.m. and I need to get this working.

-- Change Log:  Not needed. The code is perfect 'cause I wrote it.
-- If you change it, it will break.

I'm in the middle of reviewing some code comments to check they make sense, and saw the modest line above.


A few from the Linux kernel:

/* Sun, you just can't beat me, you just can't.  Stop trying,
* give up.  I'm serious, I am going to kick the living shit
* out of you, game over, lights out.
*/

-

/* 2,191 lines of complete and utter shit coming up... */

-

#if 0 /* XXX No fucking way dude... */

Not code comments, but SVN commit comments on the same file:

First commit (following of dozens of others after results coming back from testers):

Squashed some IPR mod bugs. The were big and juicy ones, too.

2nd commit:

Squashed some more mod bugs. Those are some nasty bugs, them mod bugs...

3rd:

Squashed some more mod bugs. They are like cockroaches: they'll live through a nuclear war.

4th:

Squashed some more John bugs. They too are like cockroaches: they appear anywhere John goes. Wait. That doesn't sound right.

And 5th:

Same John bug. It didn't die, just played 'possum.

Yes, I was tired of "Fixed bug".


Stating the obvious?

/** Logger */
private Logger logger = Logger.getLogger();

From a google code project:

# This job would be great if it wasn't for the fucking customers.

// *** AAAAAHAHAHAH!!  What is this??

In a game where this object can be stepped on, or:

stepOff(); //bitch

// The ratio of a circle's circumference to its diameter.  Remember to change
// this to 3.0 if you move to a site in Indiana.

#define Pi                                      3.1415927

/**---------START-----------**/

  //  IMPLEMENTATION GOES HERE

/**---------END-----------**/

But No Code ;)


    /* Mark: If there's one thing you learn from this code, it is this...
   Never, ever fly Air France.  Their customer service is absolutely
   the worst.  I've never heard the words "That's not my problem" as 
   many times as I have from their staff -- It should, without doubt
   be their corporate motto if it isn't already.  Don't bother giving 
   them business because you're just a pain in their side and they
   will be sure to let you know the first time you speak to them.

   If you ever want to make me happy just tell me that you, too, will
   never fly Air France again either (in spite of their excellent
   cuisine). 

   Update by oej: The merger with KLM has transferred this
   behaviour to KLM as well. 
   Don't bother giving them business either...

   Only if you want to travel randomly without luggage, you
   might pick either of them.
   */

//If you're reading this, then my program is probably a success

I saw this comment on someone's code:

// This comment is self explanatory.

I guess he meant to say 'variable' but the mistake made one funny comment... Think of the circular logic here, and the futility of writing it.


//Mr. Compiler, please do not read this.

Sanitized:

//Forward declarations:

class X {}; // TODO: Remove {}  ! When we get X defined....

int MyFunction()
{
    // There once was a man named Dave
    int Result = 0;

    // Whose code just wouldn't behave
    MyObject *Ptr = new MyObject();

    // He left to go to a meetin'
    Result = Ptr->DoSomething();

    // And left his memory a leakin'
    return Result;
}

C++ Comment


// Whoever put this here is an idiot...this doesn't work at all !

But the code is still there...


//If you're reading this, then my program is probably a success

' Oh man I'm pissed. I think I better go home.

where pissed = drunk


Some old fortran code I saw:

     integer *4 one,two,three;

c    asssign one to 100 before entering the loop
     one=100;

i tell a mentee to do at least SOME exception handling. This is what i get in return around every db call....

Catch (Exception e) {
    //eat it
}

I see this one a lot:

// TODO make this work

/* This is O(scary), but seems quick enough in practice. */ 

followed by four nested for-loops


From a lad that clearly had been watching Monty Python:

> // And now, for something completely
> // different:

class theLarch{


//Dave chapelle reports errors.
function reporterror() {
  davechapelle.trace("FUCK!");
}

Dennis M Ritchie has a page about some of the ancient UNIX comments here


Many years ago I picked up the job to provide support to a project that ran real time on a Z80 and was in assembly (is there any other way to do Z80??) Anyway, the original author was a Nigerian guy by the name of Moses. Maybe I should just stop there. Anyway, scattered throughout the code was this:

XRA A    ;MT

Took me awhile to figure out what this was. The instruction itself does nothing more than clear the accumulator. It's a slick way, although I'm not sure if there is an advantage or not. you can just do:

LDA 0

But maybe

XRA A

saves a byte or something. What is does is exclusive or the accumulator with itself. The result is, of course, always zero.

Back to the MT - Empty (get it?)

That's the best I've run across.


I once implemented some document workflow using MS SQL Server Developer 2000 (the human workflow stuff).

It consisted of a bunch of triggers that would be added to the database to make it follow workflow rules.

In one of the triggers, someone at Microsoft had written something along the lines of:

//Determine if the database has been "Grizzlified"

(The internal name of the product was "Grizzly", so I thought that was funny).


REM Don't delete this print statement ****** will die

The process in question was a service in some legacy code


Near the top of a unit:

// Oh what a tangled web we weave
// When first we practice to deceive
// ASTA

Technically not a comment, but from coding on something at 2 am or so:

consent = False

... that variable is never used again EVER and appears in the beginning of a listen loop for a socket.


private static final Logger lager = new Logger();

The below code was seen in a mock tutorial for Python.

# This is my rifle.
def rifle(type='hunting'):
    print('This is my (%s) rifle.' % type)

# This is my gun.
def gun(type='hand'):
    print('This is my (%s) gun.' % type)

# This is for fighting.
def fighting(type='illegal'):
    print('This is for (%s) fighting.' % type)

# This is for fun.
def fun(type='gaming'):
    print('This is for (%s) fun.' % type)

The author must have been a fan of Family Guy. ^_^


I recently saw this:

// you just lost the game

if you don't know what the game is: http://en.wikipedia.org/wiki/The_Game_(mind_game) (it's very silly, but silly in a interesting in a way)


'Do not optimize these next two lines. Compiler bugs lurk.

And they did. Compacting the variable into the expression on the second line resulted in jumping into the middle of the heap and trying to execute data.


I went through a sleep-deprived coding run and started only writing comments that were quotes from Fight Club.

Still trawling through the code years later I find a comment that makes me laugh. Most of them just random thoughts. I did however keep my comments to lines ratio pretty good!

// This shouldn't happen. The only way this can happen is if the
// <code>JFileChooser</code> has returned a <code>File</code> that doesn't exist
// on the system. If this happens we can't recover, and there is more than likely
// a rip in the space time continuum that the user is too distracted by to notice
// anything else.

 /**
   * This method leverages collective synergy to drive "outside of the box"
   * thinking and formulate key objectives into a win-win game plan with a
   * quality-driven approach that focuses on empowering key players to drive-up
   * their core competencies and increase expectations with an all-around
   * initiative to drive down the bottom-line. I really wanted to work the word
   * "mandrolic" in there, but that word always makes me want to punch myself in
   * the face.
   */
private void updateFileCountLabel() {

Taken from the Quake III source, I stumbled across this in some random slashdot posting. Full source of the file can be found here. It's a particularly fast method of calculating an inverse square root. As for the best comment? It's a common one to be sure, but given that it's attached to the line that does the magic is what makes it great.

float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the fuck?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}

REM Don't delete this print statement ****** will die

The process in question was a service in some legacy code


Catch (Exception e) {
 //who cares?
} 

// Catching exceptions is for communists

From Mike Duncan's page on SQLite.


This is actual code I once had to support. After struggling to comprehend the logic in AstaSaysGooGoo and AstaSaysGaaGaa (where many more astaTempVars were declared and used ) I was ready to give up. I finally looked up and saw the "@author" comment and the whole thing began to makes sense.

/*

* @author Andrew Asta
*/
public class AstaClass{

    private String astaVar1;    
    private String astaVar2;    
    private String astaVar3;    
    private String astaVar4;    
    private String astaVar5;    
    private String astaVar6;    
    private String astaVar7;    
    private String astaVar8;    
    private String astaVar9;    
    private String astaVar10;   

    public void AstaSaysGetData(){
        //JDBC statement to populate astavars 1 through 10
        //...
        String astaSqlStatment = "Select astaCol1, astaCol2, astaCol3... From AstaTable Where...";
        //..
        //...
    }

    //Perform data manipulation on astavars...
    public void AstaSaysGaaGaa(){
          [removed for sake of brevity]
    }


    //Perform more data manipulation on astavars...
    public void AstaSaysGooGoO(){
        [removed for sake of brevity]
    }

    public void AstaSaysPersist(){      
        //JDBC statement to save astavars to DB 
        String astaSqlStatment = "Update AstaTable set astaCol1 = @astaVar1
                                                  , set astaCol2 = @astaVar2
                                                  , set astaCol3 = astaCol3... 
                                                  Where...";
    }
}

PS I changed the actual authors real name so as to avoid me getting in any disputes etc...


I inherited a project that haad been delivered to the customer without any UAT. It was dropkicked over the fence and the money requested.

First time they used it, it naturally blew up. It was an interposing library that overrode any system calls that took a file name as a parameter rather than a file descriptor.

Many system calls had been forgotten.

When I got onboard the code was laced with such gems as:

/* core dumps around here but this is hardly ever called */

and

/* don't know why this works but it seeems to be ok */

Oh, and there were no unit tests. A colleague had started to add the missing system calls and unit tests.

And the bastards who'd written the code were still in the team and didn't care at all about the garbage that had been delivered!