Phil Trelford's Array
POKE 36879, 255

Progressive F# Tutorials 2011

November 8, 2011 14:55 by phil

Last week’s 2-track Progressive F# Tutorials conference seems to have gone pretty well:

Possibly the best Skills Matter event I have attended

progfsharp11

You can see pictures from the event over on the Skills Matter Flickr stream:

Don Syme, Phil Trelford, Mark SeemanChris MarinosKit Eason, Martin Trojer, Don SymeTomas Petricek

Skills Matter also have Videos Podcasts of all the sessions including Don Syme’s keynote:

This was followed by an excellent Tennis Kata in the Programming with the Stars session performed by Mark Needham and Mark Seeman, first in C# and then F#.

wimbledon

Don posted this solution on F# Snippets which is pretty close the 2 Mark's vesion:

 1: /// The two players
 2: type Player = A | B
 3: 
 4: /// The point score in for a player in a game
 5: type PlayerPoints = Zero | Fifteen | Thirty | Forty 
 6: 
 7: /// The score of a game
 8: type Score = 
 9:     | Points of PlayerPoints * PlayerPoints 
10:     | Advantage of Player 
11:     | Deuce 
12:     | Game of Player
13: 
14: /// Compute the next score in a game 
15: let nextPointScore a = 
16:     match a with 
17:     | Zero -> Fifteen
18:     | Fifteen -> Thirty
19:     | Thirty -> Forty
20:     | Forty -> failwith "what??"
21: 
22: /// Check if we've reached deuce
23: let normalize score = 
24:     match score with 
25:     | Points(Forty,Forty) -> Deuce
26:     | _ -> score
27: 
28: /// Score a point in a game
29: let scorePoint score point =
30:     match score, point with 
31:     | Advantage player1, player2 when  player1 = player2 -> Game player1
32:     | Advantage player1, player2 -> Deuce
33:     | Deuce, player -> Advantage player
34:     | Points(Forty, _), A -> Game A
35:     | Points(_, Forty), B -> Game B
36:     | Points(a, b), A -> normalize (Points (nextPointScore a, b))
37:     | Points(a, b), B -> normalize (Points (a, nextPointScore b))
38:     | Game _ , _ -> (* printfn "the game is over!"; *) score
39: 
40: /// Score a whole game, where a game is a sequence of points
41: let scoreGame (points: seq<Player>) = 
42:     Seq.scan scorePoint (Points(Zero,Zero)) points
union case Player.A: Player
union case Player.B: Player
type PlayerPoints =
  | Zero
  | Fifteen
  | Thirty
  | Forty

Full name: Snippet.PlayerPoints

  type: PlayerPoints
  implements: System.IEquatable<PlayerPoints>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<PlayerPoints>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable


The point score in for a player in a game
union case PlayerPoints.Zero: PlayerPoints
union case PlayerPoints.Fifteen: PlayerPoints
union case PlayerPoints.Thirty: PlayerPoints
union case PlayerPoints.Forty: PlayerPoints
type Score =
  | Points of PlayerPoints * PlayerPoints
  | Advantage of Player
  | Deuce
  | Game of Player

Full name: Snippet.Score

  type: Score
  implements: System.IEquatable<Score>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Score>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable


The score of a game
union case Score.Points: PlayerPoints * PlayerPoints -> Score
union case Score.Advantage: Player -> Score
type Player =
  | A
  | B

Full name: Snippet.Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable


The two players
union case Score.Deuce: Score
union case Score.Game: Player -> Score
val nextPointScore : PlayerPoints -> PlayerPoints

Full name: Snippet.nextPointScore

Compute the next score in a game
val a : PlayerPoints

  type: PlayerPoints
  implements: System.IEquatable<PlayerPoints>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<PlayerPoints>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val failwith : string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
val normalize : Score -> Score

Full name: Snippet.normalize

Check if we've reached deuce
val score : Score

  type: Score
  implements: System.IEquatable<Score>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Score>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val scorePoint : Score -> Player -> Score

Full name: Snippet.scorePoint

Score a point in a game
val point : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val player1 : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val player2 : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val player : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val b : PlayerPoints

  type: PlayerPoints
  implements: System.IEquatable<PlayerPoints>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<PlayerPoints>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val scoreGame : seq<Player> -> seq<Score>

Full name: Snippet.scoreGame

Score a whole game, where the game is represented as a sequence of points
val points : seq<Player>

  type: seq<Player>
  inherits: System.Collections.IEnumerable
Multiple items
val seq : seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------

type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>

  type: seq<'T>
  inherits: System.Collections.IEnumerable
module Seq

from Microsoft.FSharp.Collections
val scan : ('State -> 'T -> 'State) -> 'State -> seq<'T> -> seq<'State>

Full name: Microsoft.FSharp.Collections.Seq.scan
val game1 : seq<Player>

Full name: Snippet.game1

  type: seq<Player>
  inherits: System.Collections.IEnumerable


A sample game - A wins every point
val game2 : seq<Player>

Full name: Snippet.game2

  type: seq<Player>
  inherits: System.Collections.IEnumerable


A sample game - A and B swap points indefinitely
val game3 : seq<Player>

Full name: Snippet.game3

  type: seq<Player>
  inherits: System.Collections.IEnumerable


A sample game - A and B trade points but A wins more points than B
val truncate : int -> seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.truncate
val toList : seq<'T> -> 'T list

Full name: Microsoft.FSharp.Collections.Seq.toList
val randomGame : int -> seq<Player>

Full name: Snippet.randomGame

Generate a random game
val i : int

  type: int
  implements: System.IComparable
  implements: System.IFormattable
  implements: System.IConvertible
  implements: System.IComparable<int>
  implements: System.IEquatable<int>
  inherits: System.ValueType
val rnd : System.Random
namespace System
type Random =
  class
    new : unit -> System.Random
    new : int -> System.Random
    member Next : unit -> int
    member Next : int -> int
    member Next : int * int -> int
    member NextBytes : System.Byte [] -> unit
    member NextDouble : unit -> float
  end

Full name: System.Random
System.Random.NextDouble() : float
val i : int32

  type: int32
  implements: System.IComparable
  implements: System.IFormattable
  implements: System.IConvertible
  implements: System.IComparable<int>
  implements: System.IEquatable<int>
  inherits: System.ValueType
val nth : int -> seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.nth
val printfn : Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

Discriminated unions were used to describe the tennis domain and pattern matching to transition between game score states, e.g. deuce to advantage. Colin Bull came up with a Tennis Monad: http://fssnip.net/8Q.

After lunch the tutorials broke into 2 tracks:

  1. Chris Marinos introduced the F# programming language via his F# Koans
  2. Meanwhile Tomas Petricek showcased Data Access in F#, Today & Tomorrow

 

If you were in the Data Access session you may well have created your own Point of sale application using the Tesco API:

TescoAPI

By the end of the session we’d created our own custom F# 3 Type Provider for .INI files:

IniFileTypeProvider

You can download the source code here.

On the second day in the morning Robert Pickering ran a hands-on session on Building Applications in F# using a WPF Twitter client as the sample. Meanwhile Tomas Petricek and Simon Cousins presented on Asynchronous Programming in F#.

In the afternoon George Stavroulakis & Gian Ntzik ran a very well received session on F# in the cloud, the slides and code for which are available on the M-Brace site.

Unfortunately I couldn’t make their session as I was presenting on TDD & BDD with F#:

The first part of the talk introduced the REPL (F# Interactive) using the code from the Functional Cells: A Spreadsheet in F# article over on the DeveloperFusion site. The tasks for this session are available at: http://trelford.com/progfsharp.zip

Thanks again to all the speakers, attendees, sponsors and Skills Matter for putting on the event.

Please support next year’s Progressive F# Tutorials:

progfsharp2012


Tags:
Categories: F# | C# | .Net | BDD
Actions: E-mail | Permalink | Comments (0) | 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

What makes a good step definition

September 5, 2011 03:51 by phil

Following on from last week’s What makes a good feature file article, this week it’s time to tackle what makes a good step definition. To automatically test that an application’s behaviour matches that defined by the scenarios in a feature file, a mapping is required. Step definitions provide that mapping from the lines in a feature file to the code that implements the feature.

Starting with a Given:

Given I have entered 0.1134 into the calculator

Implementations

Ruby step definition for use with Cucumber::

Given /I have entered (.*) into the calculator/ do |n|
  # Some Ruby code here
end

The code above specifies a regular expression used to match lines in the feature file and an anonymous function to execute.

C# attributed step definition compatible with both SpecFlow and TickSpec:

[Given(@"I have entered (.*) into the calculator")]
public void GivenIHaveEnteredNIntoTheCalculator(int n)
{
  // C# code here
}

Again a regular expression is specified, however this time the function is public and reflection is used for invocation.

F# attributed step definition compatible with TickSpec:

let [<Given>] ``I have entered (.*) into the calculator``(n:int) =
  // F# code here
}

F# allows white space and special charecters in method names enclosed with backticks. This removes the need for both an attribute and a function name.

TickSpec also supports anonymous functions as Ruby with Cucumber, i.e.:

Given "I have entered (.*) into the calculator" (fun [Int n] –>
  // F# code here
)

From a terseness point of view it looks like Ruby and F# the advantage for writing step definitions. But that’s only part of the story…

Scope 

By default in frameworks like Cucumber and SpecFlow step definitions are defined globally, so that they can be shared or reused. Global functions are usually fine for small programs, but for larger programs we usually group them into classes or modules for maintainability.

With SpecFlow and TickSpec it is possible to constrain the scope of a step definition or set of step definitions via a StepScope attribute:

[StepScope(Feature="Addition")]
public class AdditionSteps
{
  [Given(@"I have entered (.*) into the calculator")]
  public void GivenIHaveEnteredNIntoTheCalculator(int n)
  {
    // C# code here
  }
}

Here the step definition methods in the AdditionSteps class are only matched against the Addition feature. This allows the wording in the feature file to evolve without affecting other feature files, and it allows the actions in the methods to vary too. It also means that it is easy to find the step definitions that map to a feature file in one place.

Using a class level step definition scope is quite similar conceptually to using a View Model within the MVVM pattern, where the View Model is responsible for mapping from view to model. It adds a layer of indirection over binding directly to the model, but allows the application to evolve more easily over time.

Note: TickSpec can apply scope to both Step bindings and Event bindings like BeforeScenario and AfterScenario. There is currently was an open bug on this in SpecFlow (since fixed).

Fluent interfaces

So far the step definition examples have included a “code here” comment. This is where we arrange, act and assert. In the Given steps the preconditions are arranged. The When steps execute the actions. Finally the Then steps assert the outcome. This is almost identical to the steps you’d take in TDD for a unit test, except the parts are spread across multiple methods.

Note: The state for a scenario can also be initialized in a method marked with BeforeScenario attribute

For the arrange and act steps, DSL approaches like fluent interfaces can be useful for making step definitions more readable and maintainable.

In the arrange steps using the builder pattern is useful to build up the initial state:

public void constructPizza()
{
  pizzaBuilder.createNewPizzaProduct();
  pizzaBuilder.buildDough();
  pizzaBuilder.buildSauce();
  pizzaBuilder.buildTopping();
}

In the act steps a fluent assertion API is useful, for example the FsUnit F# library:

1 |> should equal 1
anArray |> should haveLength 4
anObj |> should not (be Null)

Summary

Using fluent interfaces inside the step definition functions can make them more readable and maintainable. For larger projects constraining the scope of step definitions helps make them more maintainable. Finally step definitions can sometimes be written more concisely in languages like Ruby and F#.


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