Saturday, March 12, 2016

How I Learned to Love Loosely Coupled Test Data

"Play fast and loose with faith? So jest with heaven,
Make such unconstant children of ourselves"
-- Shakespeare, King John
Act III, Scene I, Lines 242-243

For C# development, I love to use AutoFac!  I find that AutoFac allows me to change the design of my code without having to worry about decencies.  The last thing I want to have to do while refactoring my design is fix a bunch of broken unit tests.  Typically if find that I have to support hard coded test setup for the system under test, when I change the signature of the constructor I'll also need to change all the test setups related to the class (this is often the case in code in which I was not the original author).  This can become very annoying, since the test cases often do not really care about the setup of the system under test.

If you are using a decency injection framework like AutoFac you really need to pair the loose coupling of your production code decencies with loose coupling of the setup of your system under test.  Loose coupling of the setup of your system under test is exactly what a test fixture is for.

Personally I love AutoFixture for C# development!  AutoFixture does all the hard work of creating a test fixture for you, all you have to do is walk up to it and ask it for what you want.

If you are using AutoFac or some other IoC framework in your system under test, more likely than not, you are using a mocking framework like Moq or Rhino Mocks.  Well, AutoFixture has you covered by allowing you to use an auto mocking plugin for Moq, Rhino Mocks, or whatever.  By using auto mocking along with AutoFixture you are able to create a system under test with all the decencies already mocked out.

With AutoFixture creating the system under test for you, you can freely change the signature of your constructor for your system under test without the need to change any of the setup for the test cases!

Say we have the following:

The above is a fairly common example of C# application that I work with.

We see that we are testing using two different test classes, one using AutoFixture and one not.  If we uncomment out the ILog decency in the System class we would break the test setup in the test class ProgramTestsWithoutAutoFixture, but the test class SystemTestsWithAutoFixture would continue to work!  For such a simple example this might not matter, but with larger code bases this can become an issue.

By using AutoFixture with Moq we are pairing the same loosely coupling of the creation of our system under test with the loosely coupling we get for our decencies in our production code using AutoFac.  Truly one can say, AutoFac iff AutoFixture with Moq.

Sunday, February 21, 2016

Unquote, App.config, and You

"What curious eye doth quote deformities?"
-- Shakespeare, Romeo and Juliet
Act I, Scene IV, Line 31

I've started using Unquote for my assertions with F# xUnit tests.  I find that its step-by-step failure messages really help in figuring out what is going on.

One thing that really throw me when I first used it was the System.MissingMethodException exception that Unquote was throwing at runtime.  Luckily I was able to find this StackOverflow answer.  It seems that you need to do a binding redirect for FSharp.Core, so you'll need to set up an App.config file in your test project like this example of the Coin Changer kata (using MapFold).

Happy coding.

Monday, February 15, 2016

Behold the Power of Mutation!

"And – ere a man hath power to say ‘ Behold!’ –"
-- Shakespeare, A Midsummer Night's Dream
Act I, Scene I, Line 147

One of the things I found very interesting in the Pluralsight class "Exploring C# 6 with Jon Skeet" was that the new interpolated strings works with expressions.  Since C# is a mutable language we can easily abuse this!

In the above C# REPL we see that we can we can have all kinds of fun as long as we have an expression in our interpolated string.


var intValue = 0;
var stringValue = $"{((Func)(() => { intValue++; return intValue; }))()}"

As long as the expression has a ToString value it will work.  Note, stringValue will only increment intValue once and after that it will always give the same result, but it is fun nonetheless.

Remember, never under estimate the power to abuse mutable languages!

Saturday, February 6, 2016

Item and Slice F#

"Slice, I say. Pauca, pauca. Slice! That's my humour."
-- Shakespeare, The Merry Wives of Windsor
Act I, Scene I, Line 125

I've been working my way through Dave Fancher's excellent Book of F# and found an interesting example of indexing and slicing arrays in F#.  Since programming is a full contact sport, here is my take on indexing and slicing in F#.

We have a constructor for a type called Word which takes a string and separates it into words.

type Words(sentence : string)

We implement an index with the Item member.

member x.Item(i) = words.[i]

This allows us to access the words of the string given.


We also implement an array slice with the GetSlice member.

member x.GetSlice(s : int option, e : int option)

This allows us to slice the array (substring it) of words in the string given.


We can go one better than built in slice by allow for range in the slice to be bigger than the number of words.

let longer = 100

In order to allow for this we have to check to see if the end is greater than the number of words.

if e > words.Length then words.[s..] else words.[s..e]


if e > words.Length then words else words.[..e]

I hope I have shown that F# has some very nice support for objects.

Sunday, January 24, 2016

FizzBuzz and the Roman Numeral Kata are the Same Thing!

"The same, sir."
-- Shakespeare, Coriolanus
Act IV, Scene III, Line 7

As Homer Simpson pointed out, "Coke and Pepsi are the same thing!"

Similarly I plan to show that the FizzBuzz and Roman Numeral katas are the same thing! 

First let's look at the rules of FizzBuzz.

f(x : int) : string
  if 3 | x and 5 | x then "FizzBuzz"
  if 3 | x then "Fizz"
  if 5 | x then "Buzz"
  default string x

*note, 3 | x reads 3 divides x, in other words x / 3 does not have a remainder

 In general we see that we have two (or three) rules and a default value, we are translating from the domain into the codomain following a set of rules, in other words we have a function.

How about the Roman Numeral kata?

f(x : int) : string
    roman-numerals : (int, string)
    lambda((x : int, m : string),
           (k : int, v : string)) : (int, string)
      while k | x then (x / k, concat m v)
    (x, default string) : (int, string)

Again we see a list of rules for translation.

The only real difference to FizzBuzz is the fold across the rules, but we've hinted at this in the FizzBuzz description above.  We stated that FizzBuzz has two (or three) rules, we can rewrite it using a fold with just the two rules using the fold to cover the "and" case.

We see the FizzBuzz and Roman Numeral as having the same shape which we use in the generalization in the "2 version".  Thus using the same function with a set of rules, a defaulting function, and a seed we create both the FizzBuzz and Roman Numeral kata from the same general function!

Monday, January 18, 2016

MapFold OR Set Phasers to Fun

"Back to our brother of England."
-- Shakespeare, Henry V
Act II, Scene IV, Line 115.1

One of the things I love about functional programming is you can tell a lot about how a function works by just looking at its type signature.  In F# 4.0 there is a new function to work with collections, here is it type signature:

('State -> 'T -> 'U * 'State) -> 'State -> C<'T> -> C<'U> * 'State

What do you think it does?

That's right this is a MapFold.  Looking at its full definition we see the following:

let mapFold<'T,'State,'Result> 
  (f:'State -> 'T -> 'Result * 'State) acc list =

How does this work?

Looking at F#'s unit tests we see the following test name:

let ``mapFold works like map + fold`` () =

MapFold works like a map with a fold to maintain state.  I know what you are thinking maintaining state is bad, that's why functional programming is easier to reason about.  This is very true, but this is not a mutable state, this is an evolving state.

Let us look at an example, the Coin Changer kata:

The Coin Changer kata simulates one of those machines which give you back coins at a store.  It takes a list of coin values and the amount of change to be given.

The Coin Changer kata is interesting since it has two things going on at the same time: 1) state and 2) list processing.  In the Coin Changer kata you must maintain the amount of change you have left to give along with the amount of each coin to be given back.  An example would be 99 cents with an US register, you would get back 3 quarters, 2 dimes, 0 nickels, and 4 pennies.

How would this example of 99 cents with an US register work with MapFold?

changeFor [25; 10; 5; 1] 99

We'll use s to hold the state, r to hold the result, and x to hold the current coin value we are looking at .

Processing the first value: x = 25, s = 99, r = [] resulting in s = 24, r = [3]
Second value: x = 10, s = 24, r = [3] resulting in s = 4, r = [3; 2]
Third: x = 5, s = 4, r = [3; 2] resulting in s = 4, r = [3; 2; 0]
Last: x = 1, s = 4, r = [3; 2; 0] resulting in s = 0, r = [3; 2; 0; 4]

There you have it, step-by-step through the Coin Changer kata using MapFold.

Guess what the source code to MapFold looks for the most part like what we just experienced.  Here it is:

We see that it loops through each member of the collection, applying the function given against the state and current member.  Once there are no more members it returns a tuple of the result along with the state.  For the Coin Changer kata we do not care about the state (maybe we could use it verify that we have 0 cents) so we just drop it and get the result using fst.

There you have it the Coin Changer kata and MapFold seem to be made for each other.

Sunday, January 10, 2016

Data Structures Matters

"I see thee yet, in form as palpable"
-- Shakespeare, Macbeth
Act II, Scene I, Line 31 

One of the katas we like to use at work while interviewing candidates is the Roman Numeral kata.  It is a simple kata in which you create a function which takes an integer and gives you back a string representing the roman numeral representation of the number.  It is fairly simple to explain but is deep enough to get a good idea of how the person works.

Here is a possible solution to the Roman Numeral kata in C#.

Looking at this solution we see a few things.  The solution is using C# 6.0 syntax but beyond that we see three major things.

  1. translation are being applied using the higher order function Fold (in C# Aggregate)
  2. mutation of the input value is used to maintain state through iterations
  3. translations are held in a Dictionary
Let us look at the Dictionary data structure which is the main focus of this post.  In general a Dictionary is not ordered, now some implementations are ordered in the order in which the key value pairs are inserted (this is the case with the C# implementation), but this is not a property of the Dictionary data structure (see also the NIST entry).

Here is a possible solution to the Roman Numeral kata in Clojure.

Looking at this solution we see a few things.
  1. translations are being applied using the higher order function Fold (in Clojure reduce
  2. hash maps are used to maintain state through iterations
  3. translations are held in a vector of vectors
We see that we cannot use a Dictionary (called maps in Clojure) to hold the translation.  Clojure's HashMap uses Phil Bagwell's Hash Array Mapped Trie which makes no claim about order, in fact we see that maps (and sets) are unordered while vectors (lists and seq) are ordered.  Since our algorithm requires that the translations be in the order we insert them we must use a data structure which preserves this order.  Thus we must used something that is ordered like a vector.

How about F#?  Here is a possible solution to the Roman Numeral kata in F#.

Looking at this solution we see a few things.
  1. translations are being applied using the higher order function Fold (using F#'s List.fold)
  2. tuples are used to maintain state through iterations
  3. translations are held in a List
For the same reasons that we found in the Clojure solution we cannot use a Dictionary (called a Map in F#) since they are ordered by F#'s generic comparison and not in the ordered in which they were inserted.  Luckily we can use a List which is ordered.

There you have it, the Roman Numeral kata in three different languages.  Despite being a simple kata we have learned something about the Dictionary data structure, mainly that it does not have an order and thus should not be used in cases in which order matters.

Saturday, January 2, 2016

Discoveries in 2015

"So Jove, the Olympian Lord of Thunder, hied him to the bed in which he always slept; and when he had got on to it he went to sleep, with Juno of the golden throne by his side."
-- The Iliad, Homer
Book 1

My discoveries in 2015 of things that I've enjoyed (idea from Michael Fogus' Best Things and Stuff of 2015).   Order is just ordered of discovery.

Programming Languages

Non-Fiction Books

Fiction Books

White Papers


My Top 5 Most Popular Blog Posts of 2015

Most Enjoyable Conferences

Presented at:
Attended: Strange Loop
Location (Portland): Clojure/West