Beautiful Code


[Beautiful Code cover]

Greg Wilson

University of Toronto

gvwilson@cs.utoronto.ca

http://www.cs.utoronto.ca/~gvwilson

June 19, 2008

Once Upon a Time...

[ultrasound] [Frank Willison]
  • My wife and I decided to start a family
  • Plus, I had a promise to keep...

Plan A

  • Write some rilly cool software
  • But I'm getting old...
  • ...and I've always been better at Version 2
[Rube Goldberg]

Plan B

  • I was about to start teaching software architecture
    • I wasn't satisfied with any of the books I could find
  • I'd dabbled enough in open source to know that people will thank you for scratching your itches in public
    • They might even help you
  • Maybe I could just organize something?
    • "Just"...

Everyone Else Uses Examples

[examples]

Ours Are Few and Far Between

[Lions Book] [Software Tools in Pascal] [Programming Pearls]

May I Have Your Attention Please?

    From: Greg Wilson
    Subject: Beautiful Code
    Date: May 17, 2006

    I hope you don't mind mail out of the blue, but I'm working on a
    new book project with O'Reilly called "Beautiful Code" and would
    like to ask you to contribute an article-length section. Profits
    from the book will be donated to Amnesty International.

    The book will be a collection of master classes in software design.
    In each chapter, a well-known software developer will present one
    of his or her favorite pieces of code, then explain what makes it
    particularly appealing.  The aim is to "think aloud" while walking
    through its design and implementation, so that junior developers
    can learn to see through more experienced developers’ eyes.

    Thanks,
    Greg
      

Surprises (Many Pleasant)

What I Expected:

    From: [name withheld]
    Subject: re: Beautiful Code

    Sorry, I'm too busy.  Good luck.
      

What Most People Said:

    From: [name withheld]
    Subject: re: Beautiful Code

    I don't think I've ever written any code I'd call beautiful,
    but I'd really like to read the book when it's done.
      

But Quite A Few Responded With:

    From: [name withheld]
    Subject: re: Beautiful Code

    Sure, count me in!
      

Contributors

Tim Bray Jim Kent TV Raman
Karl Fogel Ronald Mak Arun Mehta
Jon Bentley Adam Kolawa Kent Dybvig
Brian Hayes Lincoln Stein Andrew Patzer
Alberto Savoia Ashish Gulhati Bryan Cantrill
Andreas Zeller Brian Kernighan Charles Petzold
Henry S. Warren Andrew Kuchling Michael Feathers
Douglas Crockford Greg Kroah-Hartman Diomidis Spinellis
Travis E. Oliphant Simon Peyton Jones Yukihiro Matsumoto
Elliotte Rusty Harold     Jeff Dean & Sanjay Ghemawat     Jack Dongarra & Piotr Luszczek
William Otte &
Douglas C. Schmidt
Laura Wingerd &
Christopher Seiwald
Rogerio de Carvalho &
Rafael Monnerat

Beauty Takes Many Forms


    int j=0;
    for (int i=0; i < a.length; ++i) {
        j++;
    }        
    System.out.println("array size=" + j);
      

Beauty in the Small (Hayes)

[Hayes figure 2] [Hayes figure 3]
[Hayes figure 4] [Hayes figure 5]

Beauty in the Medium (Fogel)

[Subversion Delta Editor]

...Beauty in the Medium (Spinellis)

[Spinellis]

Beauty In The Large (Dean & Ghemawat)

[MapReduce]

Beauty In The Even Larger (Mak)

[Mak figure 1] [Mak figure 2]
What do you do when a day is 24 hr 39 min long?

The Beauty of the Classics (Kernighan)

    int match(char *regexp, char *text)
    {
        if (regexp[0] == '^')
            return matchhere(regexp+1, text);
        do {
            if (matchhere(regexp, text))
                return 1;
        } while (*text++ != '\0');
        return 0;
    }
            
    int matchstar(int c, char *regexp, char *text)
    {
        do {
            if (matchhere(regexp, text))
                return 1;
        } while (*text != '\0' && (*text++ == c || c == '.'));
        return 0;
    }
	    
cany literal character
.any character
^matches the beginning of the input string
$matches the end of the input string
ccc  any sequence of characters or .'s
*closure: zero or more of the previous character
    int matchhere(char *regexp, char *text)
    {
        if (regexp[0] == '\0')
            return 1;
        if (regexp[1] == '*')
            return matchstar(regexp[0], regexp+2, text);
        if (regexp[0] == '$' && regexp[1] == '\0')
            return *text == '\0';
        if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text))
            return matchhere(regexp+1, text+1);
        return 0;
    }
            

The Beauty of Utility (Kolawa)

      SUBROUTINE SGBSV( N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, INFO )
*
*  -- LAPACK driver routine (version 2.0) --
*     ..
*     .. Scalar Arguments ..
      INTEGER            INFO, KL, KU, LDAB, LDB, N, NRHS
*     ..
*     .. Array Arguments ..
      INTEGER            IPIV( * )
      REAL               AB( LDAB, * ), B( LDB, * )
      

Utility Takes Many Forms (Mehta)

[Hawking's hardware] [Hawking's interface]

The Beauty of Compromise (Crockford)

     The turnstile hash table is partitioned into two halves: the lower half
     is used for upimutextab[] locks, the upper half for everything else.
     The reason for the distinction is that SOBJ_USER_PI locks present a
     unique problem: the upimutextab[] lock passed to turnstile_block()
     cannot be dropped until the calling thread has blocked on its
     SOBJ_USER_PI lock and willed its priority down the blocking chain.
     At that point, the caller's t_lockp will be one of the turnstile locks.
     If mutex_exit() discovers that the upimutextab[] lock has waiters, it
     must wake them, which forces a lock ordering on us: the turnstile lock
     for the upimutextab[] lock will be acquired in mutex_vector_exit(),
     which will eventually call into turnstile_pi_waive(), which will then
     acquire the caller's thread lock, which in this case is the turnstile
     lock for the SOBJ_USER_PI lock.  In general, when two turnstile locks
     must be held at the same time, the lock order must be the address order.
     Therefore, to prevent deadlock in turnstile_pi_waive(), we must ensure
     that upimutextab[] locks *always* hash to lower addresses than any
     other locks.  You think this is cheesy?  Let's see you do better.
      

Theory Made Practice


    Simplicity is one of the most misunderstood
    concepts in programming.  People who design
    languages frequently want to keep those
    languages simple and clean.  While the
    sentiment is noble, doing this can make
    programs written in that language more complex.
      

Beauty As A Process


[Perforce branching history]

Reactions

Why Should We Care?

[Steam Engine] [Quilt]
"Beauty is truth, truth beauty." Pride

Where Next?

Thank You

[Greg Wilson]
I'm Greg Wilson, and I approve this talk.