Saturday, May 30, 2015

Destructuring in Clojure and ES6

"I do not like ‘ But yet;’ it does allay
The good precedence. Fie upon ‘ But yet!’

‘But yet' is as a gaoler to bring forth
Some monstrous malefactor.
"
-- Shakespeare, Antony and Cleopatra
Act II, Scene V, Lines 50 - 53

Intro


Sometimes your cup is over flowing and all you want is a sip.  This is where destructuring comes into play.

Say you have the following data structure.


If you only needed the Hobbit's name and family you could either drill into the data structure to obtain them or you could communicate to future readers of your code (which most likely will be you) that you only need name and family from hobbit by destructuring hobbit in the function which consume it.

JavaScript


In ECMAScript 6 we could do the following:



In the JavaScript above we see that we can destructure Bilbo to get just the name and family (which is renamed to parents) using: let {name, family:parents} = bilbo;

We see also that we can set up a function which will expect data mapping which include a name and family and then use those in its code.

let hobbies = ({name, pastTime:hobbies}) => name + ' enjoys ' + hobbies.join(', ');

The nice thing about using a data map is that we can reuse the method above with different data mappings and as long as they have a mapping for a name and family we are good.  This is what Rich Hickey was talking about in Simple Made Easy.  By using data mappings as our data transfer objects we uncomplect our code and allow for more flexibility.

Clojure


In Clojure destructuring would look like this:



Like the JavaScript code above we see we can rename while destructuring.

(let [{name :name
parents :family} bilbo]
(is (= "Bilbo" name))
(is (= ["Baggins" "Took"] parents)))

We see also that we can define a function which takes a data map in which we expect a keyword of name and another of past-time.

(defn hobbies [{name :name hobbies :past-time}]
(str name " enjoys "
(clojure.string/join ", " hobbies)))

Again we see from the created of Clojure, Rich Hickey, how using a data map in our interface allows us to reuse this function on a differently structured data map as long as it has the keywords of name and past-time.

Extro


There we have it, the ability to sip with destructuring.