Phil Trelford's Array
POKE 36879, 255

Method Stubs

November 25, 2011 00:34 by phil

I’ve spent the last 2-days of this week on a hands on TDD & Refactoring workshop ran by Jason Gorman. The course comprises of short exercises that you tackle in pairs. The provided machines came with Visual Studio 2010 installed so for most of the exercises my programming pair, Martin Trojer and I, used Visual F#.

One of the exercises was to implement a fictional holiday booking system that would connect to an external flight booking system and an external villa booking system. Holidays for a particular week of the year may only be booked if flights are available and one or more villas. The idea for the exercise was to test the holiday booking system using stubs for the flight and villa booking systems.

Being a Test Driven Development (TDD) course we Test First and Assert First, i.e. we write the test and the assertion before the code to implement the test:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    // ...
    Assert.AreEqual(holidays, [])

Another practice in XP/TDD is to write the simplest code that will make the test pass. In this case the simplest thing seemed to be to implement a function that gets the available holidays for a specific week given functions that determine flight and villa availability:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    let holidays = 
        getAvailableHolidays (isFlightAvailable, getAvailableVillas) (2,2013)
    Assert.AreEqual(holidays, [])

Now we implement the functions isFlightAvailable and getAvailableVillas as stubs:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    let isFlightAvailable _ = false
    let getAvailableVillas _ = ["Mountain Dew"]
    let holidays = 
        getAvailableHolidays (isFlightAvailable, getAvailableVillas) (2,2013)
    Assert.AreEqual(holidays, [])

With the stubs in place we can make the test fail:

let getAvailableHolidays (isFlightAvailable, getAvailableVillas) (week,year) = 
   getAvailableVillas (week,year)

The test fails because we are not checking flight availability. To make the test pass:

let getAvailableHolidays (isFlightAvailable, getAvailableVillas) (week,year) = 
   if isFlightAvailable (week,year) then getAvailableVillas (week,year)
   else []

Our first test passed. Time to refactor. In our test there is some code duplication, the stub functions isFlightAvaialble and getAvailableVillas always return the same value. We can create a method to encapsulate this:

let inline always value _ = value

Then we can use partial application to define a function getHolidaysWhenNoFlights:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    let getHolidaysWhenNoFlights = 
        getAvailableHolidays (always false, always ["Mountain Dew"])
    let holidays = getHolidaysWhenNoFlights (10,2012)
    Assert.AreEqual(holidays, [])

On to the next test case (which unfortunately passes immediately as the system has now been implemented):

[<Test>]
let ``when flights are available but no villas then no holidays`` () =
    let getHolidaysWhenNoVillas = 
        getAvailableHolidays (always true, always [])
    let holidays = getHolidaysWhenNoVillas (10,2012)
    Assert.AreEqual(holidays, [])

And so on:

[<Test>]
let ``flights and a villa are available then a holiday is available`` () =
    let getHolidays = 
        getAvailableHolidays (always true, always ["Mountain Dew"])
    let holidays = getHolidays (10,2012)
    Assert.AreEqual(holidays.[0], "Mountain Dew")

In F# I find myself starting with functions and then moving to classes if necessary. In C# and Java it seems people tend to start with classes, perhaps because refactoring from a static method to a class is felt to be hard. In F# it’s almost as easy as changing the let keyword to type, and declaring a member. So starting with our function to get available holidays:

let getAvailableHolidays (isFlightAvailable, getAvailableVillas) (week,year) = 
   if isFlightAvailable (week,year) then getAvailableVillas (week,year)
   else []

Refactored to a class:

type AvailableHolidays (isFlightAvailable, getAvailableVillas) = 
    member this.Get(week,year) =
        if isFlightAvailable (week,year) then getAvailableVillas (week,year)
        else []

Just before we ran out of time for this exercise we came up with a simple implementation for spying on method calls:

type Recorder () =
    let mutable xs = []
    member recorder.Record(x) = xs <- box x :: xs
    member recorder.Values = xs

let inline spy (recorder:Recorder) f = fun ps -> recorder.Record(ps); f ps

Which allowed us to check if a the flight booking system is being called with the correct values:

[<Test>]
let ``the flight availability system is passed the correct date`` () =
    let recorder = Recorder ()
    let isFlightAvailableSpy = spy recorder (always true)
    let getHolidays = 
        getAvailableHolidays (isFlightAvailableSpy, always [])
    let holidays = getHolidays (12,2012)
    Assert.AreEqual(recorder.Values,[12,2012])

So no frameworks required for either stubs or spies! .

Overall I felt a function based approach to TDD using F# worked very well, and resulted in a very simple solution.


Tags:
Categories: F# | .Net | Software Craftsmanship
Actions: E-mail | Permalink | Comments (4) | Comment RSSRSS comment feed

DDD Belfast 2011

October 2, 2011 23:56 by phil

This weekend I flew into Belfast for their Developer Developer Developer (DDD)  conference. The DDD conferences are run by the developer community for the developer community, where sessions are voted on prior to the conference. I highly recommend these free events, there always seems to be a great range of interesting talks, not to mention plenty of lively discussion between sessions. The next event is DDD North next weekend, Saturday 8th October, in Sunderland.

Interestingly there were enough F# sessions at DDD Belfast to have a dedicated track (3), which is where I spent most of the day.

My first talk of the morning was F# Eye 4 the C# Guy (a title I ahem, recycled, from an excellent talk by Leon Bambrick given 3 years ago):

Next up was Tomas Petricek on Asynchronous Programming in F# and C#. If you’re in London, Tomas is repeating this talk at Skills Matter this Wednesday (5th October), register free here: http://www.meetup.com/fsharpLondon/

Shipping in VS11, C# 5’s Async (await) support will be very similar in implementation to C# 2’s Iterators (yield). They are both basically implementations of coroutines.

F#’s Async Workflows are available now in VS2010.

Before lunch I was up again to talk about Behavioural Driven Development (BDD) with F#:

After lunch Adam Granicz presented Developing F# Applications with WebSharper on track 3. I popped over to see Richard Dalton’s great information packed session Aha! Unit Testing.

Slides and samples: http://www.devjoy.com/2011/10/aha-unit-tests-dddbelfast/

Richard gave some really interesting observations, for example unit tests are “An Extra Client” (slide 5), and therefore it is OK to add artefacts in your code to support them. The talk presented a number of Aha! moments:

Unit Testing - Excutes Unit Testing - Real Reason

 

There were also some good tips on Mocks and Stubs (Stubs are Stooges, Mocks are Spies), including some code examples using TypeMock and references to Microsoft Research’s Moles project and Martin Fowler’s Mocks Aren’t Stubs article.

Track 3 ended with a lively Panel Discussion, which covered a variety of subjects from BDD, Concurrent programming with Agents, Parsers, Units of Measure through to games development.

Thanks again to all the attendees, sponsors, speakers and particularly Jackie Pollock for organizing the event.


Tags:
Categories: .Net | F# | C# | BDD | Software Craftsmanship
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Progressive F# Tutorials November 2011

July 3, 2011 22:46 by phil

At first glance it sounds a little like a set of rock music tutorials, based on a genre from the late 60s and early 70s performed and in a specific key. However on closer inspection the Progressive F# Tutorials seem to have a lot more to do with learning F#, an exciting new multi-paradigm programming language that’s part of Visual Studio 2010.

progfsharpbanner

Could there still be a tenuous link with Progressive Rock?

Jon Covach, once described in Contemporary Music Review, Progressive Rock as:

"a mostly British attempt to elevate rock music to new levels of artistic credibility."

Phil Trelford described in this very article, the Progressive F# Tutorials as:

“a mostly British attempt to elevate F# to new levels of developer understanding.”

Here’s How!

First, assemble of some of the big names in the F# world:

Second, mix in 2 tracks of F# goodness:

  • Track 1: Practical F# from the beginning
    suitable for programmers with C# or VB.Net experience
  • Track 2: F# in the Enterprise
    suitable those with F# experience or advanced C# and VB.Net developers
  • Each tutorial will be approximately 3 hours long and will have a very practical focus (i.e. bring your laptop or netbook). The aim of the conference is to have you programming F# confidently by the time you leave.

Third, help you shift into a Functional mind set with a Programming with the Stars session, where developers explain how they solve problems, featuring:

Finally, kick the whole event of with a look at what’s new in F# vNext!

Hope to see you on November 3rd..4th.


Tags:
Categories: F# | C# | .Net | Software Craftsmanship
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed