358
votes

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

0

518 Answers 518

1
2 3 4 5
18
1453
votes

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
// 
Sign up to request clarification or add additional context in comments.

6 Comments

//Dear Programmer // //Your code now runs slower now that I fixed all the bugs you //introduced. //But your optimizations sure helped.
While True { total_hours_wasted_here += 1 }
total_hours_wasted_here=-32768, what should i do? i think something is broken.
Best one I've encountered was 2001: 250 x   //This is necessary otherwise Netscape will insert multiple linebreaks, honestly!!
Please stop "updating" the counter. It's not worth bumping this question onto the front page yet again.
|
1049
votes
Exception up = new Exception("Something is really wrong.");
throw up;  //ha ha

9 Comments

I read all comments from top to bottom, wondering what people meant, when they say the "cracked up, reading this one" or "cracked up, reading that one". Well. I just cracked up reading this one...
Literally did LOL at the combined cleverness and childishness of this one.
class MonkeyPoo extends Exception {}; ... throw new MonkeyPoo(); // because it's so much more fun to throw than an exception
When I wake up from truly deep sleep, my IQ drops to about 25, and my mind goes extremely strange places. Once, after a long stint of writing java, I woke up in the middle of the night feeling quite ill, and bolted to the bathroom. As I vomited into the toilet, the only thing I could think was "I wonder which exception I'm throwing right now..."
Would be funnier if the exception message were, "I don't feel so good."
|
1048
votes
//When I wrote this, only God and I understood what I was doing
//Now, God only knows

3 Comments

That's a phrase from Karl Weierstrass, the mathematician who gave us the wonderful epsilon and delta continuity definition.
Weierstrass the Undifferentiable?
@Augusto, do you have a source for the attribution of that phrase to Weierstrass? I'd like to know what he was referring to.
1045
votes
stop(); // Hammertime!

12 Comments

I like it. Da da da DA, da DA, da DA, It's over (David Spade, SNL, Weekend Update)
stop(); // collaborate, listen!
stop(); // what's that sound?
stop(); //! In the name of love. Before you break my heart.
|
1026
votes

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

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

1 Comment

I think they'll mess your code up anyways: it says it'll fix itself, so why not break it for kicks?
942
votes
// sometimes I believe compiler ignores all my comments

9 Comments

I hope the compiler ignores this person's comments.
// Since I never heard back from the compiler, I believe this is true.
I think it's supposed to be ironic...
laughter, that's the future, compilers reading comments just to make sure they haven't misunderstood ;-D
//#reply_from_compiler you like clippy, don't you?
|
927
votes
// 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.

7 Comments

Is this somewhere on the Duke Nukem Forever source code? ;)
I don't get it, what's so funny?
He's dedicating the code below to his wife, even though he knows it's so bad that it's going to either get him fired or make his company go out of business. :)
Why will the dog be released to the public?
@Nosredna, thank you for such a funny comment! @hasen j, the code was written so bad that the "programmer" will most likely lose his job, and therefore his wife will have to support the family.
|
907
votes
//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.

39 Comments

That's riddled with obscenities, but I literally laughed in my cube the entire time reading it.
censorship sucks. bring back the original!
Rolled back. We're all adults here. If the original code had been "sanitized", you would never have remembered it enough to post it here.
Will be even funnier if a customer sees the class name in a stack trace.
PLEASE DO NOT ROLLBACK TO NSFW VERSION - the author explicitly accepted the SFW version at revision 3 and 6.
|
825
votes
// somedev1 -  6/7/02 Adding temporary tracking of Login screen
// somedev2 -  5/22/07 Temporary my ass

2 Comments

Ah, the good permanent temporary solutions :)
There is nothing as permanent as temporary!!!
726
votes
// drunk, fix later

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

11 Comments

That is ridiculous, who writes comments when they're drunk.
@Jiminy: Seriously! When I code drunk, I wake up with magnificent code that I, unfortunately, do not understand.
Ohh... If you don't understand it, it has to be magnificent!
haha!!! I made this just for fun: grepped my local subversion repo for 'drunk', and found one commit comment I wouldn't remember: "Works again, somehow. Well... I'm drunk!"
ha ha, "..somehow a B.A.C. between 0.129% and 0.138% confers superhuman programming ability..." xkcd.com/323
|
718
votes
// Magic. Do not touch.

16 Comments

Magic = fragile, perhaps?
I've had to write that so many times - mostly to remind myself that "If you touch the following code without really knowing what you're doing, bad things will happen!"
@Simon Howard, I'd only not touch it if it said "More Magic"
I still remember being taught CS in high school, where our stupid questions were answered with "Magic!" and the most sinister smile.
|
699
votes

#define TRUE FALSE //Happy debugging suckers

7 Comments

#define NULL (::rand() % 2) // would be quite nice aswell
#define if( if(!
@Bart: You can't have half parens in your code, but you could do #define if(x) if(!(x)) (or, more sinisterly, #define if while )
As given this would actually work though: the comment-till-end-of-line characters make sure that likely lines where this macro is used will not compile. For example: a = TRUE; will translate to a = FALSE // Happy debugging suckers; which will lead to a compile error because the termating ; is now in comments. If you use the block comment /* Eat this */ it will work.
#define struct union is very helpful in memory constrained systems.
|
638
votes
// I'm sorry.

8 Comments

(The code that followed made me cry.)
man, I wanna see the code that followed...
// You are forgiven. Go in peace my son.
This should be a standard comment in the default templates generated by MSFT
really, what's the code that follows this???
|
635
votes
return 1; # returns 1

14 Comments

Classic! But i like this one even better: "i++; // increase i by 1"
Who knows if he #DEFINE 1 as something else...
I wish comments like that were unfamiliar to me.
I've seen this a lot. I know a lot of coders who stub out their functions with comments, then fill in the code below/beside each comment. Makes it very easy to write large business functions, but you end up with some rather detailed comments at times.
# returns one what? Be more specific.
|
589
votes
/* This is O(scary), but seems quick enough in practice. */ 

followed by four nested for-loops

9 Comments

pfft, that's only N^4 most likely, no where near as bad as 4^N or N!
I once hit a situation with loops nested 8 deep. The runtime was measured in hours.
I had a O(n) algorithm with a 500ms network RTT in its inner loop. n > 100k. Ouch.
There is a redeeming quality: they know what big O terminology is at least. Hopefully each loop is running over very small N :-D
I work with somebody who would say, "O(MFG), please"
|
588
votes
// Replaces with spaces the braces in cases where braces in places cause stasis 
   $str = str_replace(array("\{","\}")," ",$str);

11 Comments

+1 - Pure genius. This should go on a t-shirt or something :-)
Dr Seuss writes code? +1!
Needs two more syllables at the end...
Just opened the comments to say that it needs two more syllables, but apparently I beat myself by three months.
I disagree with the need to additional syllables, the meter is perfect as is. Five groups of three syllables each.
|
540
votes

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

17 Comments

I completely agree with your comment that comments are rarely needed.
Depends on the comments. Even "self-documenting" languages can benefit from comments, such as Python. I hate having to slog through the code to figure out what is happening, when a simple sentence can tell me.
I disagree re: comments being unnecessary. There are times when a simple "framing" comment can make sense of a whole slew of code. For example, if you are using a sophisticated algorithm to escape the time complexity of a brute force algorithm, a reference can be essential.
The code says what...the comments say why!
I couldn't agree more with "Richard E". Comments are meant to tell your future * (coworkers, reviewers, yourself) why did you chose to do things that wicked way instead of another. I'm not for littering comments all over the place, but sometimes they should be mandatory.
|
524
votes
long john; // silver

5 Comments

Pure corn. That's why I like it.
Totally cracked up as well. I think my code now is too boring.
Might be me but this cracks me up everytime double d.
Damn, I was thinking of en.wikipedia.org/wiki/Long_John_Silver's Ether way, I'm hungry.
505
votes
Catch (Exception e) {
 //who cares?
} 

13 Comments

This one had me laughing like a mental
I saw the same thing with // move along, nothing to see here.
I laughed so hard at this one.
Have to admit that I've done this on more than one occasion because sometimes it just doesn't matter.
Wow, I write that comment all the time. I never thought of it as funny, I thought it was a serious statement.
|
496
votes
/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}

Never rely on a comment...

8 Comments

I always tell my co-workers. "Comments don't run!!"
I believe you meant, "never rely on the code". I'm sure the spec, design and requirements required a return code or true :)
looks like something you'd see on the techie edition of failblog.org
Things like this actually happen, people don't bother keeping documentation up to date with changes even if it's right above the function.
... #define false true?
|
456
votes
/*
 * 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.
 */ 

8 Comments

Reminds me of a fellow who swore he could optimize a mechanical theorem-proving algorithm I wrote years ago in an AI project. He did improve performance but then the code didn't work...which he swore was my fault.
Hmm, haven't I seen this one somewhere?
@Mark He only said he'd optimize the time, he said nothing about the functionality =P
If it doesn't have to work, I can optimize any code to a runtime of zero.
That's what source control is for. Waste a few hours trying to optimize it, and then if it doesn't work out, just roll back.
|
428
votes
try {

} finally { // should never happen 

}

14 Comments

++. others in my company write this all the time!
i've seen that comment (and even written it myself) in the past, for things that relalyt shouldn't ever happen (but just in case, here's code to handle the error). The funniest part is that ti's placed in a finally block, which means it should always happen...
Yes, that was the joke. =)
If you have a System.exit() call in the try block, then YES, the finally should never happen !
Reason #984 to use Debug.Assert(). ;)
|
409
votes

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.

4 Comments

The line right after that and its comment really top the cake. Sanity? What sanity? The format ate it all...
s/PSD/Internet Explorer/g. s/file format/web browser/g. Now it matches my thoughts.
I pity that programmer for having to go through such a pain!!! But awesome piece of comment. Has poured his heart out.
This line: // PSD is not my favourite file format. makes this a classic.
387
votes
const int TEN=10; // As if the value of 10 will fluctuate... 

20 Comments

In today's market 10 now has a value of only 9.
Maybe someday we will evolve more fingers...
what about very large values of 10?
const int TEN=11; // Mine goes to eleven
Calling Fortran from C - Fortran only does call-by-reference so you need variables for all constants.
|
363
votes
    #Christmas tree initializer  
    toConnect = []  
    toRead =   [  ]  
    toWrite = [    ]   
    primes = [      ]  
    responses = {}  
    remaining = {}  

4 Comments

That's a win. A huge win...
OK I am going to use this next time I need four empty arrays and two hashes!
Urgh. A loud "FAIL!" to the author for not knowing if he's using a format-free language or not.
I doubt that he didn't know about the format-free language. That's a nice joke :-)
362
votes

About the middle of a 30 page xslt

<!-- Here be dragons  -->

14 Comments

I'm still trying to figure out how to comment an XSLT in a way that makes sense.
We really need more dragons in our code.
@annakata you think that's bad, the other day someone was asking for help dealing with a 31GB xml file. I cried out in anguish.
Did someone call for me?
|
352
votes

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)

21 Comments

tour-de-france code
this is thedailyworsethanfailure.com worthy!
Looks like Lisp!
That comment is probably there to fix a compiler bug. :|
Cyclomatic complexity level of OH SHIIIIIIIII
|
351
votes
//This code sucks, you know it and I know it.  
//Move on and call me an idiot later.

4 Comments

Honestly in comment!
I love the honesty.
The first step to improvement is to acknowledge the deficiency.
accept your mistakes before others exaggerate them :)
351
votes
long long ago; /* in a galaxy far far away */ 

4 Comments

does this actually work? in which language?
@Mauris: It was originally a C and C++ extension for 64-bit integers, which many vendors supported. Then C99 and C++0x standardized support for it: en.wikipedia.org/wiki/Long_long
Makes me think about the far vs. near pointers we used in 16-bit land. :)
It still works perfectly fine. We first put it in our compiler at Convex about 25 years ago because DMR suggested that that should be the name for our 64 bit-bit ints.
324
votes
// If this comment is removed the program will blow up 

15 Comments

A long time ago, I accidentally fixed a segfault in Java3D by adding a comment. It was 100% reproducible; if I removed the comment, it crashed. As long as the comment was there, it worked fine. I assume it was some bizarre timing issue, but I never did figure out exactly what was happening.
Magic/More Magic
This is sort of like a virus. It contains content meant to protect itself. It is like the junk DNA that is good at getting itself copied.
you should compare the bytecode generated by the 2 versions
It took me half a day once to figure out that ending a C comment with \ (used to mark which direction we are going in a 2D array) causes the compiler to skip the next line.
|
1
2 3 4 5
18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.