Tuesday, February 25, 2014

A gender neutral version of the Crispin's Day speech

WESTMORELAND. O that we now had here
But one ten thousand of them in England
That do no work to-day!

What's they that wishes so?
My cousin, Westmoreland?
No, fair cousin.
If we are mark'd to die, we are enough to do our country loss,
Or if to live, the fewer of us, the greater share of honor.
God's will, I pray thee, wish not one of us more.
Rather, proclaim it, Westmoreland, through my host
That they which hath no stomach for this fight,
Let them depart.
Their passports shall be made and crowns for convoy put into their purse.
We would not die in that one's company that fears their fellowship to die with us.
Tomorrow is the feast of Crispian.
They that outlive this day and come safe home will stand a tip-toe when this day is named
And rouse them at the name of Crispian.
They that sees this day and lives t'old age shall yearly, on the vigil,
Feast their neighbors and say, "Tomorrow, is St. Crispian's"
Then will they strip their sleeves and show their scars
And say, "These wounds, I had on Crispin's Day"
The Old Ones forget, yet all shall be forgot, but they'll remember
With advantages, what feats they did that day!
Then will our names, familiar in their mouths as household words,
"Harry the King, Bedford and Exetor, Warwick and Talbott, Salsbury and Glouster"
Be in their flowing cups, freshly remembered.
This story, shall the Good One teach their child.
And Crispin Crispian shall n'er go by, from this day to the ending of the world!
But we in it shall be remembered.
We few. We happy few.
We band of comrades.
For them today that shed their blood with me shall be my comrade.
Be they ne'r so vile, this day shall gentle their condition.
And gentlefolk in England now abed
Shall think themselves accursed they were not here
And hold their values cheap
Whilst any speaks that fought with us upon St. Crispin's Day

Sunday, November 24, 2013

Øredev 2013

The trip to Øredev is a long one, but worth it. This year, the Øredev conference proposed a theme celebrating the arts and technology. I wasn't sure what to expect heading toward Sweden, but I arrived tired yet open-minded. The first activity of the week was sleep, an attempt to catch up on a few hours of shut-eye after 14 hours of travel and a 7-hour timeshift. On the night of arrival, the first conference-organized activity I participated in was a Swedish cultural event involving sauna, the cold Baltic, and Swedish hospitality. The event took place at Kallbadhuset, a sauna/restaurant situated on a pier over the Baltic sea.

It was a cold and rainy night. When we arrived at the restaurant by bus, the rain and wind made the pre-sauna beer go down very nicely. There were a men's and a women's saunas, and the size of the group that showed up for the event that night was larger than they'd anticipated. They ran out of towels and I went to the sauna armed only with two sheets of paper towel to separate me from the baked cedar inside the sauna room. And it was hot in there. I stayed until I'd worked up a massive sweat and then headed out into the cold night to race down the long pier, the end of which descended into the frigid waters of the Baltic Sea. The transition from the hot sauna to the icy waters of the Baltic was stark. The immersion into that water brought out my barbaric yawp. I stayed in the water for nearly a minute, then rushed back across the pier to jump into the hot sauna for another round. The second dip in the Baltic wasn't as satisfying as the first and I declared the experience to be over for me.

After showering and dressing, I remember the open-air walk back to the restaurant from the sauna area being much more pleasant than what I'd experienced in the long, wet walk from the bus that brought us to the restaurant. The transitions from extreme heat to extreme cold had conditioned my body to find the center and be at peace with the conditions of the night.

They served a lovely meal and the conversations at the all the tables in the restaurant were lively. The experience of sitting naked in the sauna and testing our mettle in the cold waters had exposed a bit of the shared humanity that the conference was embracing with its arts theme. That night was a celebration of the feelings and the extremes our bodies are capable of withstanding. Connecting with that and each other is what the arts often enable, and, what I suspect the conference hoped we would experience.

The first keynote of the conference was given by Anna B. Scott (@doctoradancer). Anna is a dance professor who told a very poignant story about how a brain injury changed her life and robbed her of her mobility for a while. She described how technology came to the rescue to keep her connected to humanity, how she discovered a community of people whom she connected with despite not being able to move around very much. This story she told, about interface of the physical and the technological was delivered partly as a talk and partly through interpretive dance. Anna said that the arts are expressions of our humanity; they are what lead us out of the forests that we hide in. It was a gripping performance that set the tone for the conference: how do the people we are relate to each other via ideas and technology? What changes in how we can relate when our communication shifts from face-to-face interaction to words streaming across screens in front of us? Does technology disrupt us or do we disrupt each other by our use of technology? She was a brilliant choice as the opening keynote of the conference. I got a chance to speak to her afterwards and pass on how much her talk grabbed me.

There were many other talks at the conference that I found memorable. One was given by Douglas Crockford on RQ, a library for writing functional JavaScript that includes "monads, promises, and various flavors of FRP". Crockford said that event-based systems are inside-out inversion of control models, versus procedural architectures which are systems of dominoes. He also mentioned a JavaScript port of QuickCheck that he wrote called (JSCheck). I can't help but look at Crockford's disapproving avatar from his github page and assume that I am doing it wrong.

I saw a presentation on Scala and the Play framework by James Ward. What I saw made me think that Play still had a way to go before it would as enjoyable to write web applications in compared to Rails.

There was a presentation by Thomas Q. Brady about how great design pushes developers to connect users to a moment and to each other through technology. He recommended the movie, Jiro Dreams of Sushi, as a source of inspiration for pursuing mastery in the art form that is your calling.

Angela Harms gave a very personal talk on pairing and mindfulness. About showing up with your whole self and being present with your pair while thinking through a problem. Also about being open to ideas that you may not agree with for the purposes of exploration. She told a great story about pairing with someone and agreeing to go down a path she thought was wrong only to learn that it turned out to work. That sticking with your pair and being open to an alternative approach (even one that was counter to where you should be going) could lead to learning both for you and your pair. I really liked this idea.

Steve Klabnik gave a tour of through the history of Rails. How an environment that gave @dhh the freedom to create a framework that innovated away from practices that no one else was questioning. The time was right for a new way of organizing and writing web applications. In the last few years, the landscape has changed yet again. Rails is still alive but JavaScript has seen a massive resurgence and in the client and server space. Steve acknowledged this trend and made a point of saying that Rails makes a great API server for JavaScript web applications.

The talk that generated the most notes in my notebook was given by Fred George on Implementing Micro Service Architectures. Micro service architectures are systems where requestors and responders are completely decoupled and communicate via event messaging. The services that respond to event "requests" (though the events may be requests or they may just represent data known about something) are small (hence the 'micro' component of the architecture) and are meant to be replaceable/disposable at any time by some "better" form of the same or a similar service. Fred described a rule-of-thumb of no more than 100 lines per service. He also said that one of the benefits of this architecture is that it allowed rapid deployment and feedback about the efficacy of any service. As well, in adopting this architecture, his teams had abandoned the normal TDD (or unit testing in general) of the services themselves. That instead of writing automated tests for services that may be thrown away at any time, service monitoring became the means of bug/design feedback. In the talk, he didn't go into much detail about the monitoring and what (other than that a service was up and responding to events) was being monitored. There were many interesting ideas from this talk, lots more than what I've mentioned here. I recommend watching the talk and perhaps reaching out to Fred with questions. I asked several from the audience.

The coolest talk I saw was a live-coding demonstration by Bodil Stokke, wherein she created a CRUD site in Clojure for managing MLP-related data. Aside from being fantastically impressed by the coding feat, I took from the demo that Clojure a DSL for creating MLP websites.

I had the greatest meal of my life on this trip. It was at a curiously named restaurant called Bastard. It was a 5-course meal that consisted of meats, baked vegetables, fish, pickled spicy things, and perfectly paired wines. I don't remember what the dessert was because by then I was in a food coma. At several points in the evening, I had to cover my eyes and disengage from the dinner conversation because I was utterly overwhelmed by the experience the food was creating in my mouth and I just had to focus on that. The meal was crazy expensive. And worth it. If the conference was a celebration of the arts and technology, and the arts reflect our humanity, Bastard grabbed hold of my humanity from the inside of my mouth and reminded me how good it is to be alive.

Friday, July 05, 2013

Interface Segregation Principle in Ruby

I was recently asked whether Ruby had a way of honoring the Interface Segregation Principle (ISP). ISP says that a client of an API should only depend on the methods it needs/cares about. In languages like Java, ISP is easy to manage with static typing and judicious use of Interfaces. Ruby doesn't have the same thing, though. Consider the following example:


Let's say that you want to put the controls to fly and land a drone in the hands of someone with Secret clearance, but restrict access to operations like taking pictures and launching missiles to a client with a different security clearance. The problem with the Drone class is that the methods for doing all of the operations are visible to anyone with a reference to a Drone instance. ISP says that the lower-level clearance client should only be able to see a subset of all of the methods on a Drone instance. We can't control this on the instance itself very easily because the class is defined to expose all methods to anyone with a reference to an instance of it.

What you can do in Ruby is present access to an object via a proxy to it using the Forwardable module. In the example below, the Pilotable class tells Forwardable where to send invocations of the methods "take_off", "land", and "fly_to". Any other method invocation will blow up. An object of Pilotable class doesn't expose the reference to an aircraft it is wrapping, instead it simply provides a means of invoking a subset of its methods.


This is the essence of the Interface Segregation Principle: provide a client with an interface limited only to the methods needed in the context of the client's interaction.

Saturday, June 15, 2013

Styles of handling conditional logic

TLDR: Raising & catching exceptions is a programming style. Designing functions/methods to always return a value to indicate success or error is a programming style. My preference is the latter, as I will explain below.

This post is a response to a Twitter discussion about the use of exceptions as an indicator of a condition that an API caller must either deal with or defer handling to logic at a higher level of a call stack. To read that discussion thread and all of its branches, you can start here.


In the case above, the get_user method communicates a condition where it is not able to return a user object by means of raising an error (RecordNotFoundError). Anything that calls this method can choose to call it and ignore the possible error case as is shown below:


Or it can wrap the call to get_user in a block that guards against the possibility of the call failing and handling that condition in a rescue block:


What should the code do in the rescue block? Whatever is appropriate given the requirements of the system. Frankly, it doesn't matter. The rescue block is a form of conditional logic branch. The logic of the branch above could be rewritten if, instead of blowing up, the call to get_user always returned something. But what? It could return nil (or whatever value represents "nothing" in your language of choice, if such a concept exists in the language). With this design, the calling code would have to test for whether the method returned a value or not.


Is this better? I think it is not better because the un-value value (nil) is being INTERPRETED by the calling code to mean something. The calling code must know that either a useful object will be returned, or else a reference to something that the calling code must make a decision about will be returned (nil). What is nil? In the style above, nil can mean whatever the API designer wants it to mean. At the same time, nil can mean whatever the caller to the API wants it to mean. It is a value open to interpretation, like a work of art. No right answers, and no wrong answers... And no useful information passed between caller and callee. At least with raised exceptions, the caller can have multiple rescue blocks each catching a different sort of error condition and responding in kind. In my opinion, though, it is better to be uniform and explicit about conditional behavior instead of expressing logic using a mixed set of language constructs.

So how is this accomplished? There's more than one way to do it. One approach is the Null Object pattern . This pattern introduces an object that is meant to behave like an "empty" instance of a type, one which has no real values. So given a type Product:


A variation of Product could be a PerishableProduct:


And for cases where some function or method may return a product or may fail to retrieve a product for some reason, a NullProduct may be returned instead so that calling code which wants to operate uniformly on all products to do something qualitative can get an object reference that will behave like a Product but does not actually represent one.


This approach is useful when the caller needs a usable reference to something but doesn't care what kind of thing it is. The caller relies on polymorphic behavior in whatever is returned in the call that yields either a "real" Product or a NullProduct. However, this is different from the original problem. One where calling an API either returns something useful or blows up, and this dichotomy requires the caller to use conditional logic to account for both sets of outcomes. An alternative to NullObject for more accurately representing the return of something usable or something to indicate a failure or error is the "Either" pattern.

Either is a wrapper object that can hold the "ideal" return value of a call or something that is informationally indicative of the failure to return the ideal value.


The Either is an ideal return value from an API along with whatever error indicator may have occurred in the course of creating (and therefore in lieu of) that value. Callers of a method or function that return an Either must ask the Either reference whether it has a real value or an error and behave appropriately. This turns the original example above into the following:


In this style, there is the same amount of conditional behavior as in the begin/rescue approach, but it is more explicit about handling the conditions. I prefer the clarity of this style. Languages (like Java) that distinguish between checked and unchecked exceptions (ones where the compiler either enforces explicit handling of method invocations that could result in a raised exception vs. ones where a RuntimeException may be thrown that the calling code can either handle or allow to leap up the call stack) put the responsibility of imposing the conditional logic via try/catch blocks in code that calls into an occasionally explosive method or function. For these kinds of languages, API designers have (in my opinion) too much influence over the coding style of the callers of their code with respect to handling success or error cases where their APIs are invoked.

I have been intentional in the use of the word "style" in this post. Expressing conditional logic via if/else, switch/case/when, try/catch/begin/rescue, or polymorphic semantics (depending on the language) is a matter of coding style and developer preference, that of the API designer. The outcome of each is effectively the same, a running program goes down one logical branch or another. Stylistically, I think code should be simple and prefer to use constructs like Either instead of designing APIs that may return something useful or blow-up.

I would like to thank Jessica Kerr for first introducing me to the Either style. It is not an uncommon approach for return values in the Scala world.

Sunday, March 17, 2013

Ruby Immutability

Recently, I was thinking about immutability in Ruby and how (if I was so inclined) to design classes and objects that contained immutable state.  Ruby is such a flexible language.  It's submissive; the language bends to your will with a minimum of effort, and to great enjoyment.  I wondered how to design an object that I could initialize with some state and have the object just hold onto that state and make it available to me, but not let go of it.  And not allow the values I pass into its initialization to be changed.

Any reasonably experienced Ruby developer knows that all Ruby objects have a method #freeze that lets an object's state be frozen (restricted from external change).

For example, if I have a String:

s = "Heynow"
s.freeze
s.upcase! # [Kablooee]

Freezing the s String causes its internal state to be fixed such that any calls to a method that would result in an internal state change raise an exception. That solves my problem, right?

For some class of immutability problems in Ruby, that actually does what you want. If you don't "own" the object you are freezing, though, calling #freeze on any object whose state you fancy fixing in place is like painting your favorite colors on your best friend's bicycle; it may feel right, but that don't make it right.

For the case where I wanted to preserve the state of objects handed to my classes but allow my own classes to manage objects as they pleased (IOW, borrow my neighbor's shovel and not damage it while clearing the snow off my driveway), I would need an idiom for fixing some but not all state in an object of my design.

I came up with a trick for tucking away objects handed to my initializer in a place where it would be difficult for me (or anyone else) to tamper with them. The case I am solving is one where an object of my design is handed some other object that I may initially modify or just hold onto, but want to fix its state at a specific point. In the example below, I have a class that receives an email value and I need to make sure that the email I'm handed doesn't get changed by whoever asks me for it.


In this approach, the value handed into the Profile object is tucked into a lambda and set as a method in the instance. This sets aside the email object passed into the initializer so that no other instance methods can modify the value of the email parameter (as they would be able to if email was simply referred to via an @email instance variable name).

The trouble with this approach, though, is that the email value itself is mutable by whoever passed it into the initializer of the Profile class. This is preventable (if true immutability is important).


By duplicating the parameter passed into the initializer and freezing the copy, the object can safely tuck the value away in a lambda and sleep soundly, knowing that no code (internally or externally) will tinker with a value that should not be changed.

This isn't perfect immutability, though. You could still write code to replace the method on this object instance with a new method that returns a different value for email. Any code doing this, though, isn't operating via an accidental course, changing state on objects unintentionally. The lambda, and dup/freeze combination is a reasonable tradeoff for creating a form of immutability in a language that is designed to be as mutable as you want it to be.

Sunday, December 11, 2011

New England Clam Chowder

(preparation time 40 minutes)

This is what you'll need for 4 servings (though Anna doubles the recipe):

  • 4 slices bacon or salt pork
  • 1/2 cup finely chopped onion
  • 4 medium potatoes, peeled, diced
  • 1 Tbsp. all-purpose flour
  • 2 cans (6 oz. each) minced clams with liquid
  • 1 cup bottled clam juice
  • 1 cup half-and-half
  • Salt and pepper to taste
  • 1/2 cup whipping cream (optional)
  • 2 Tbsp. finely chopped parsley (very optional)

Preparation:

  1. In a large heave saucepan, sauté bacon or pork until brown and crisp. Remove. Drain on paper towels. Dice or crumble.
  2. In same skillet, sauté chopped onion and potatoes for a couple of minutes. Sprinkle with flour.
  3. Add clam juice from cans and from bottle. Stir to combine. Bring to a boil. Simmer, stirring from time to time, until potatoes are soft (about 15 minutes).
  4. Add half-and-half and season to taste with salt and pepper.
  5. Add minced clams. Heat until simmering. Do not boil. Add whipping cream, if used. Sprinkle with parsley or diced pork or bacon. Serve immediately.

New England Clam Chowder

Good served with croutons or small crackers, hearty bread and beer, red wine or beverage of your choice.

Thursday, September 22, 2011

The Teacher

I was fortunate enough to help organize the Strange Loop 2011 conference, but this post is not specifically about that. During the conference, I had the privilege to talk to several of the speakers, and one stood out for me in a way I won't forget. Professor Gerald Sussman is the Panasonic Professor of Electrical Engineering at MIT and is perhaps best known (at least among the people that might read this blog) for inventing the Scheme programming language and co-writing Structure and Interpretation of Computer Programs (also known as "SICP" and the "Wizard Book"). Though this textbook is nearly 30 years old, it continues to be recommended reading for hackers who seek a deep understanding of computer programming.


2011-09-20 14.19.03

During the conference, I had several occasions to speak with Professor Sussman about a great range of topics. Professor Sussman is fantastically knowledgeable about many things. If you ever get a chance to have a conversation with the man, I highly recommend dropping everything to do it. At one of the session breaks, I caught the Professor at a coffee station and asked him about something I had heard, which was that in addition to being an expert in electrical engineering he was also a watchmaker. He told me that he had received a Rolex watch as a gift after earning his doctorate (in 1973) and that at some point the watch needed to be cleaned. He sent the watch (which he still wears) to Rolex and noticed upon its return that they had been careless in cleaning it and had either smudged the inside of the crystal or damaged the watch face (I unfortunately don't recall exactly the detail of the blemish). His abundant curiosity lead him to taking it apart to fix the mistake made at the factory. This was apparently Professor Sussman's introduction to the fine art of watch making.


Since that time, the Professor has been pursuing experience in the art of watch making. He told me that he travels weekly to the shop of one of the few Master Watchmakers in Massachusetts (somewhere in Stoneham) to do work in exchange for guidance in an art that only a master watchmaker can provide. I couldn't get this story out of my head. Here I was, talking to one of the most revered computer scientists of our time and listening to him recount his own journey toward mastery in a field other than what has been his life's work. It was both humbling and inspiring to hear that the man still lives the life of a learner.


Dr. Sussman doesn't have a cell phone and he doesn't watch television. Free time is too valuable to him to waste on such things. He occupies himself pursuing new understanding and sharing his panoptic knowledge with his own students. This man is a nerd. He is a nerd's nerd. I might say he wears his nerd on his sleeve, but he wore short-sleeve shirts during the conference and instead wore his nerd where it belongs: on his shirt pocket. (Below is a pocket protector generously given to me by Julie Sussman, Professor Sussman's wife and co-conspirator in the pursuit of awesome).


Nerd Pride


As we were chatting casually, I mentioned that I have trouble getting more than five hours of sleep a night. He only smiled and said I was "winning" because it gave me more hours to be alive. This perspective reflects an attitude that recognizes how many things there are in the world to learn, and more than that to relish in understanding. It was one of the most inspiring, personal experiences that I can remember.


The lecture above was taken from MITWorld.

Professor Gerald Sussman | Speakers | MIT World

Thank you Scott Bale, for capturing the shot when Professor Sussman was teaching me a great lesson.