Sunday, June 28, 2015

Leap Year kata OR How TDD Does Not Mean No Forethought

"Hence! home, you idle creatures, get you home:
Is this a holiday? What, know you not,
Being mechanical, you ought not walk

Upon a labouring day without the sign
Of your profession? Speak, what trade art thou?
-- Shakespeare, Julius Caesar
Act I, Scene I, Lines 1-5

The Leap Year kata is interesting.  The real trick to the kata is not the leap year algorithm.  No, it is picking the test cases in such a way as to not cause you to have to write the whole thing at once.

Let us look at an implementation in Clojure.

We see that the key to picking test cases is to have an idea of the order in which you plan on writing your code.  How so?  In the first test case we pick leap years divisible by 400, then we pick non-leap years divisible by 100, then leap years divisible by 4, and then years which are not leap years.

Does setting up your test case with the algorithm in mind violate TDD?  I say no.  In fact I think Uncle Bob would say no.

TDD does not mean no architecture.  TDD does not mean no forethought.  No, TDD means no production code is written without a test and that only as much production code is written as what is needed to pass the current failing test.

In other words, TDD would want you to think about the leap year algorithm a head of time and pick test cases which will move along the algorithm.

Sunday, June 14, 2015

Combining Maps in JavaScript and Clojure

"Thy knotted and combined locks to part,
And each particular hair to stand an end
Like quills upon the fretful porpentine.
"-- Shakespeare, Hamlet
Act I, Scene V, Lines 18-20


Sometimes in life you want to combine different things together to make something that is even better than the things by themselves.

"Within the same school, the idea was that
We'd later combine both styles, unify the techniques
But still, we were too young
Too full of ignorant pride in our own succulent sorrow
-- Rancid, Crane Fist


In Lodash we can use the Merge and Assign functions to combine Map Data Structures.

In the code above we see the big difference, based on the examples given, between Merge and Assign is around combining the internal Map Data Structures.  We see that the result from Merge will combine them together whereas Assign will just overwrite them.


Clojure also has a Merge function.

In the code above we see that merge in Clojure works like Assign in Lodash but we can use merge-wtih along with conj to get the similar results to Merge in Lodash.


"As all things come to an end, even this story."
-- J. R. R. Tolkien, The Hobbit

Sunday, June 7, 2015

One Data Structure to Rule Them All

"Mark Antony, shall we give sign of battle?"
-- Shakespeare, Julius Caesar
Act V, Scene I, Line 23


For decades the battle cry of the LISP family of languages has been:

"It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures."
-- Alan J. Perlis
Epigrams on Programming, #9

What is this one data structure to rule them all?  The list?  Well yes and no.  In practice I would say, at least in Clojure, it would be the Map data structure (not to be confused with the Higher Order Function called Map).

Say we have the following data structure:

We can say that a Hobbit is made up of a mappings of name, age, family, and past time to values.


With ECMAScript 6 using Lodash we can use the pick and get functions to work with objects like they were Maps.

In the example above we see that with the pick we can obtain a new Map by selecting the attributes that we want.  If it is not found then it simply want be placed in the resulting Map.

If all that is wanted is one value from the Map then we can use the get function to obtain the value. 

The get function let's us provide default values.

_.get(bilbo, 'none', 'not found')
.should.equal('not found');

_.pick(bilbo, 'none')
This helps in being able to tell if the value of the attribute is null or if the attribute does not exist.


With Clojure we can use the keyword, get, and select-keys functions (to name a few) to work with Map data structures.

In the example above we see that we can use keywords as functions and that the Map data structure its self can be used as a function.

(is (= "Bilbo" (:name bilbo)))
(is (= "Bilbo" (bilbo :name)))

Like the Lodash get function, the get function let's us provide default values.

(is (= nil (get bilbo :none)))
(is (= :not-found (get bilbo :none :not-found)))

This again helps us in being able to tell if the keyword is not found or if the value of associated with the keyword is nil.

(is (= nil (bilbo :none)))
(is (= nil (:none bilbo)))

While using the keyword as a function for an association that does not exist will return nil.

We see also that select-keys acts much like Lodash's pick, in that it returns a new Map with the keyword associations selected.

Clojure's select-keys

(is (= {:name "Bilbo"}
(select-keys bilbo [:name])))
(is (= {:name "Bilbo" :family ["Baggins" "Took"]}
(select-keys bilbo [:name :family])))

Lodash's pick

_.pick(bilbo, 'name')
.should.eql({name: 'Bilbo'});
_.pick(bilbo, ['name', 'family'])
.should.eql({name: 'Bilbo', family: ['Baggins', 'Took']});


There you have it, Map,  the one data structure to rule them all.

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


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.


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.


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.


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

Monday, May 25, 2015

Living with Variadic Functions in Clojure and JavaScript

"No wonder, my lord – one lion may, when many asses do."
-- Shakespeare, A Midsummer Night's Dream
Act V, Scene I, Line 152


Often in programming (and life) you do not get exactly what you want.  Say we have a simple function which adds numbers together.  How should the input be structure?  Should we require the caller to place all the values into some type of collection?  Why can't the caller pass in the values one at a time into the function?

Splatting in JavaScript allows a function to accept a variable number of arguments, this is called a variadic function.  A variadic function allows for a variable arity, which is a fancy term for what is often called arguments.

Say we want the following:

We would like to be able to call our summer function with a variable number of arguments but we want to be able to work with the arguments like they were in a collection.  This is were splatting comes into play.

In the plain old JavaScript example we see the following:, summer.length)

This is how to do a splat in plain old JavaScript.  We are taking the argument object then we slice off the number of arguments which the function normally takes using Function.lenght, in the case of summer the Function.length value is 0.  By doing all of this we now have an array with all of the arguments passed into the summer function.  We can now call Lodash's reduce with the arguments to obtain the sum.

In the ES6 example we see we can use the new splat operation ... (also called spread) to get an array of the arguments passed in.  This is a lot easier than using the slice, arguments, and Function.length pattern that we see in the plain old JavaScript code.


How would we do something like this in Clojure?

We see in Clojure we can destruct the parameters using the & to obtain the rest of the parameters, in the case of summer & values will give us everything the function is called with.  We can then apply this collection against the + function using apply.  Apply allows use to pass in a collection as the last argument to a function which does not take collections.

In Clojure we do not need a summer function since that is exactly how the + function works.