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.