Phillip Trelford's Array

POKE 36879,255

Life in a tweet

This week I had pleasure of meeting Vagif Abilov on Tomas Petricek and I’s Advanced F# course at Skills Matter. Vagif mentioned a Ruby implementation of Conway’s Game of Life being squeezed into 140 characters for tweeting and how that might look in F#.

Here’s the 140 characters of Ruby:

life=->g,s{(0..s*s-1).map{|i|->n{n==3||(g[i]&&n==2)||nil}
[[g[i-s-1],g[i-s],g[i-s+1],g[i-1],g[i+1],g[i+s-1],g[i+s],g[i+s+1]]
.compact.count]}}

And 127 characters of F#:

let f s g = g|>List.mapi(fun i x->match Seq.sumBy(fun o->
g.[abs((i+o)%(s*s))])[-1-s;-s;1-s;-1;1;-1+s;s;1+s]with 3->1|2->x|_->0)

Like the Ruby version, the F# implementation above takes a shortcut when computing points outside of the grid.

This is what the function looks like with added white space, variable names and comments:

let generate size grid =
    grid |> List.mapi (fun i value->
        /// Neighbours count
        let count =
            let s = size
            [-1-s;-s;1-s;
             -1;     1;
             -1+s;s; 1+s]
            |> Seq.sumBy (fun o ->
                let offset = abs((i + o) % grid.Length)
                grid.[offset]
            )
        // Evaluate life
        match value, count with 
        | _, 3 -> 1
        | n, 2 -> n
        | _, _ -> 0 
    )

The  game grid can is expressed as a list:

let grid = [
    0;0;0;0;0
    0;0;1;0;0
    0;0;1;1;0
    0;0;1;0;0
    0;0;0;0;0
    ]

Visualizing the grid on the console:

let show (size:int) (grid:int list) =
    for y=0 to (grid.Length/size)-1 do
       [0..size-1] 
       |> List.map (fun x -> grid.[y * size + x].ToString())
       |> String.concat "" 
       |> printfn "%s"

Or watch it running in your browser: http://trelford.com/Life/Life.htm

(I used Pit to compile the F# code to JavaScript)

Life.fs (1.77 kb)

What makes a good step definition

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#.