views:

211

answers:

2

I am looking for examples of reasonably short, but reasonably complicated segments of code (objects, functions, classes, a particular set of variable names, etc) that strike that perfect zen like balance of self documentation and implementation elegance.

It could either be something you are really proud of or something that you came across and experienced an "Aha!" moment of enlightenment.

Some potential criteria (not all need to be met in a single example):

  • Sparse and Focused
  • Self evident. Perhaps so clearly written that even a non programmer could understand what you are trying to do, even if they don't understand the syntax or implementation details.
  • Manifestly Useful (has multiple use cases, e.g. a sorting algorithm, handy recursive method, etc.)
  • Clever
  • Enlightening
  • Production quality and functional (e.g. not pseudo code)

I am looking for an example snippet followed by a brief commentary of what makes the code special. Of course the best examples will require minimal additional commentary because they are well documented.

Note to moderators: I am new to stackoverflow, so if this question is somehow not appropriate or must be closed, can you provide an explanation of where it runs afoul of stackoverflow's norms? I am not intending to waste people's time.

The goal of this question it to learn good commenting practices through examples provided and rated by the community.

+1  A: 

Jon Bentley's implementation of Quicksort in C, from the book Programming Pearls.

void quicksort(int l, int u) {
    int i, m;
    if (l >= u) return;
    swap(l, randint(l,u));
    m = l;
    for (i=l+1; i<=u; i++)
       if ( x[i] < x[l] )
           swap(++m, i);
    swap(l, m);
    quicksort(l, m-1);
    quicksort(m+1, u);
}

It's just incredible. Elegant, concise, minimal, and supremely efficient. In particular, I'd recommend the analysis of this algorithm in Chapter 3 of Beautiful Code. Mind-blowing!

ire_and_curses
This is certainly elegant, but how might this example be commented so that a non-programmer can understand it?Perhaps some comments or more verbose variable names.
Gordon Potter
@Gordon Potter: Sorry, I just realised I didn't read your question properly. An answer with no comments at all is probably not what you were looking for. ;) This is probably a particularly bad example from a commenting perspective - there's so much going on in every line (all interlinked) that it's a non-trivial problem to distill it into something meaningful, IMO. It is pretty though.
ire_and_curses
+1  A: 
Shane
I saw this in the bookstore will have to give it a closer look. I had this in the back of my mind when I asked this question. I posted this question on stackoverflow to get a wider swath of input on the subject.
Gordon Potter
Do buy it, you'll love it. Lots of different languages used, with brilliant code. What more could you want :)
Shane