Saturday, August 18, 2012

Shakespeare Programming

The following lines of code group a list of customers by city and orders the groups with more than two values by key.

var custQuery =
    from cust in customers
    group cust by cust.City into custGroup
    where custGroup.Count() > 2
    orderby custGroup.Key
    select custGroup;

I dub this style of coding... "Shakespeare Coding." Why do we write code like this? This code is taken directly from the MSDN website, which implies that this is how Microsoft expects programmers to write code.

My problem with Shakespeare Coding is that it is too close to the syntax of a language near and dear to my heart. A language with weak typing, ambiguous references, poor commenting, and a rotund standard library filled with functions that rarely anyone will ever use. That language is English.

Shakespeare Programming is coding in a style which is akin to writing prose. I attest that this style of coding is not compatible with a programming mindset. Programming syntax should be readable, obvious, and terse. Prose has many nuances and intricacies that can make it ambiguous and difficult to interpret

Let's modify the code above to be a little bit more gentle on my eyes, shall we?

var custQuery = customers
                    .GroupBy(cust => cust.City)
                    .Where(group => group.Count() > 2)
                    .OrderBy(group => group.Key);


That wasn't so hard. And now what we have are three clauses, each of which has a very obvious and meaningful purpose in the main statement.