Showing posts with label FsUnit. Show all posts
Showing posts with label FsUnit. Show all posts

Saturday, June 7, 2014

Leap Year in the Key of C#, F#, Haskell, and Scala

"Shall be their father's bail, and bane to those"
-- Shakespeare, Henry VI Part 2
Act V, Scene I, Line 120

Leap Year


Leap year, one of the time based banes of a programmers' existence.

The rules around if a year is a leap year are simple enough.

if year is divisible by 400 then
   is_leap_year
else if year is divisible by 100 then
   not_leap_year
else if year is divisible by 4 then
   is_leap_year
else
   not_leap_year

Most languages do have a built in check for Leap Years, but the point of the kata is to implement your own in order to learn something.  With that in mind let's look at few ways to solve this problem and see what we can learn.

C#


Note, if we want to do it the most efficient way possible we could just use the built in DateTime.IsLeapYear, but the point of the kata is to implement the algorithm yourself in order to learn something.



Here is an example using C# with NUnit for the testing.

We see that we can just implement the algorithm as a series of conditional statements.  We also see that with NUnit we can use the TestCase attribute which allows us to just give the input along with the expected result.  This kind of testing I feel leads to more readable test cases which focus on the data and not the steps needed.  Having a test case which focuses on the data is the right approach in my opinion for testing a pure calculation based function like this.

Haskell


Note, this looks a lot like the code on Rosetta Code for the TDD Haskell implementation of Leap Year, because it is the same code that I contributed there for that entry.



This Haskell solution uses pattern matching.  If you are new to pattern matching you can think of it as a switch statement.

With this style of pattern matching in Haskell we would get an error message if we call the function without a value which was covered, but the otherwise keyword at the end covers everything else so getting an exception would not happen.  Comparing this to the C# solution with a series of conditional statements the Haskell caller knows that every input is covered by the function whilst the C# call will have to hope that all input cases are covered.

Scala


Note, this is my third Scala kata ever, as such I need to look at this gist form Kingsley Davies in order to do the kata.



With the Scala solution we are again using pattern matching, but this time we are doing all of the testing in a tuple which we are matching against (note, we could have done this in the Haskell and below in the F# solution).  Using this style of pattern matching we are matching against a pattern but in this case I feel that the algorithm is hidden, as such for this function I do not think this is an improvement over the Haskell solution above (note, I did this on purpose to try out this approach with this solution to see what it would look like).

F#




This last solution using F# uses Active Pattern Matching.  Personally I find the Active Pattern Matching with a Maybe Monad very readable.  We can see that the algorithm states if the year is divisible by 400 we have leap year, but if it is divisible by 100 we do not.

Note, you can do this pattern in Scala and Haskell.

Conclusion


We see above 4 somewhat different ways to find if a year is a Leap Year.  All these approaches used unit testing frameworks along with TDD.  None of the solutions are the way to do it, but each look at the problem from a different point-of-view.

Sunday, December 15, 2013

Living with Function Programming OR Unit Testing F# with FsUnit

"Let there be some more test made of my metal
Before so noble and so great a figure
"
-- Shakespeare, Measure for Measure
Act I, Scene I, Lines 48-49

The Quest


One of the first things I asked myself while learning F# was, "This is great, how do I test this stuff?"  I did what any programmer would do and asked the Google, which pointed me to a question on Stackoverflow and a slide deck on slideshare.  Between the the top answer on Stackoverflow and the 5th slide in the deck.  I was off and running doing TDD in F# with FsUnit and NCrunch!

Intro to FsUnit


FsUnit uses the BDD should style of testing, which I personally am starting to prefer.  I hear, an example would be nice right about now; in the back of my head, here you go (these examples are taken from the FsUnit README.md):

1 |> should equal 1
1 |> should not' (equal 2)

"ships" |> should startWith "sh"
"ships" |> should not' (startWith "ss")
"ships" |> should endWith "ps"
"ships" |> should not' (endWith "ss")

[1] |> should contain 1
[] |> should not' (contain 1)


The pattern which FsUnit follows is:

{actual-result} |> should {statement-to-test} {expected-result}

Looking at the first line in the example (1 |> should equal 1) we have:

1 as the actual-result
equal as the statement-to-test
1 as the expected-result

F# is a functional language, so we should think of everything in the FsUnit test as a function.  Given that, we see that the should is looking for: an actual-result, a statement-to-test (equalnot'endWithcontain, ...), and the expected-result.  Using the |> pipe we get a readable form like, 1 should equal 1 (1 |> should equal ).

FsUnit with the Even or Odd example


Let us look at MSDN's favorite F# example, even or odd; using FsUnit?

Say we have the following:

let isOdd x =
  if x % 2 = 0 then false
  else true
  
let isEven x = isOdd x |> not

We can use the following to test these two functions using FsUnit and NUnit.

[<Test>]
let ``Given 2 isOdd is false`` () =
  isOdd 2 |> should be False

[<Test>]
let ``Given 2 isEven is true`` () =
   isEven 2 |> should be True

[<Test>]
let given_3_isOdd_is_true () =
  isOdd 3 |> should equal true

[<Test>]
let given_3_isEven_is_false () =
  isEven 3 |> should equal false

Looking at the tests we see that we can use backticks to allow for more readable names to our tests.  For boolean results we can also choose between should be False and should equal false, the first using FsUnit's keyword be with its False and the other using equal and F#'s false.  Both from my experience work the same, so it is more a question around readability and maintainability.

FsUnit FizzBuzz example


Using NUnit we can uses attributes like TestCase to pass in values to our FsUnit tests.  Again the voice in the back of my head is saying, "How about an example?", so here it is for FizzBuzz:

open NUnit.Framework
open FsUnit

 let (|DivisibleBy|_|) divisor n =
  if n % divisor = 0 then Some() else None

let fizzbuzz n =
  match n with
  | DivisibleBy 3 & DivisibleBy 5 -> "FizzBuzz"
  | DivisibleBy 3 -> "Fizz"
  | DivisibleBy 5 -> "Buzz"
  | _ -> string n

[<TestCase(2,"2")>]
[<TestCase(4,"4")>]
[<TestCase(3,"Fizz")>]
[<TestCase(9,"Fizz")>]
[<TestCase(5,"Buzz")>]
[<TestCase(25,"Buzz")>]
[<TestCase(15,"FizzBuzz")>]
[<TestCase(30,"FizzBuzz")>]
let ``Given this value the result is this`` (value, result) =
  fizzbuzz value |> should equal result

Using a parameterized active pattern (based on yet another Stackoverflow response from Tomas Petricek!) we are able to have a FizzBuzz solution which does not test the mod 15 directly and is very expandable (in case the business wants a Woof for 7!).

We see that using the NUnit TestCase attribute we can simply have one FsUnit test which is passed in different input for the argument to fizzbuzz and the expected result!