Wednesday, November 28, 2012

A case study in expressive (domain specific language) programming.

I was asked to write a cache for a HTTP request. My first instinct was to add a static instance variable and be done with it. Then I thought about staleness. I could've added another field for a Date, and turned my class into an unmaintainable mess in trying to manage the freshness...instead I factored out.

I noticed, as I was writing the new class, that I wasn't in a dry, soulless programming mood. I could've described everything in terms of caches, maps, requests, buffers, etc...instead, I decided to make it like telling a story: the PreviousJourneys of Corey the HttpCourier.

I noticed that by using expressive names like rememberVisit() instead of putDataInCache(), and expanding out expressions like hasVisited(location) && tripTakenRecently() into a method--visitedRecently(location)-- I'm able to write a fairly comprehensible story.

It could use some work, of course. It's not perfectly consistent in names. The logic is 3 am logic. Technically it's probably better to make a Journey that has place, experience, and date, as it makes more sense to say "If I haven't visited X in 7 days I probably wanna see what's new there" rather than "I haven't been anywhere in 7 days so I'm going to X, damn it!"

But the point of the exercise is that I think most people could follow it.

I think this was the point of the Abbot Method, CRC cards, Use Cases, and all of OOP. It's what BDD is driving at. If you're writing code powerfully, it should tell the story of the system in a way that's obvious to most people who have some idea what's going on. Knuth's Literate Programming is probably quite far along the spectrum to Codevana...maybe even farther than LISP. *gasp*