Fluent language in FsStory

A nice feature for a story runner is to be able to provide arguments in a story sentence, like this:

ATableWithNumberOfLegs 4

This example is not hard to understand, but there’s some mental translation going on, since the order of the words is all screwed up. Let’s try another one:

TheNumberOfLegsOfATableIs 4

Better, but still not good. First, it’s longer than the previous example. Second, even if the grammar is correct, the word order is, well, unusual.. ­čśë

What about this?

ATableWith 4 Legs

Now we’re talking!

Here’s a bigger and more complete example:

[<Fact>]
let tableLegsScenario =
given (ATableWith 4 Legs)
|> whens (ICutOf 1 Leg)
|> thens (ItHasOnly 3 LegsLeft)

Note: As far as I know, RSpec/Cucumber is the only story runner(s) that is able to use variables inside a story sentence.

The nice thing about this is that I didn’t have to change FsStory itself to make it work. Not a single line. So, what’s the trick?

If you split up a story sentence like this, you have to prepare the step definition code (the behind-the-scenes code) in a certain way:

let ATableWith = fun n _ -> … do something here …

..or if you prefer, without a lambda:

let ATableWith n _ = … do something here …

Then you have to define Legs:

let Legs = id

As you see, in this case, it was just a matter of discovering the usage, rather than implementing it in the language. Honestly, I had no idea of this usage when I started to write on FsStory. This is clearly one of the reasons why I like internal DSLs!

Exercise: How would you implement the step definition for the following story sentence?

given (ATableWith 4 LegsAnd 2 Chairs)

Cheers!

Posted in bdd, F#, FsStory | Leave a comment

ImpossibleEstimation and Pomodoro Technique

Sometimes when using Pomodoro Technique I find it real difficult to estimate how long a particular activity will take, i.e., when locating a bug or find out why the webserver won’t read my files.

In Pomodoro Technique, every activity should have a time estimate – how many Pomodori I think it will take. Though, this is sometimes impossible! “The problem is solved when I find the bug and since I don’t know what the bug is related to, it’s impossible to say how much time it will take to find it.”

The solution: instead of just writing a number besides the activity, I use the less-than sign (<) before the number, indicating that I have a time-box for the activity, but that it might take less time. If I'm not done when the time-box is over, I have to ask a colleague to help me or ask my boss for extra resources – thus, escalating my problem. Then, I'm forced to have collected some data of the problem to help them to help me. The nice thing is that I still can have most of the benefits Pomodoro Technique gives me, i.e., increased focus when in a Pomodoro and possibility to get "the whole picture" during my breaks. The latter have proved to be an extra nice thing to have during hard problem-solving.

And, if a colleague comes to the rescue, we can construct another time-box, to know when to escalate it further, or at least to notify the team or the boss that we have some nasty problems at hand.

Yet, if I’m collecting metrics of my estimation skills, it is not a very good idea to track data for these bug-fixing Pomodori estimates. Put a “N/A” or a “-” in your records sheet and think for yourself: “Today was an exception, tomorrow will be a bug-free day.” And don’t forget to do your daily mind-map before you leave for home.

Posted in Uncategorized | 1 Comment

[Announce] FsStory, executable stories in F#

Since Claudio Perrone’s talk on ├średev, I have been thinking about what his MisBehave would look like in F#. In his talk, Claudio also mentioned Cucumber, a story runner written in Ruby. My plan was to make a lightweight DSL for writing stories in F# code, with the story parts separated from the implementation parts.

Currently, FsStory enables the developer to write user story scenarios (in Given/When/Then form) in F# code, like this:

#light

open FsStoryRunner
open MutatedTurtleMovesImpl
open Xunit

(*
In order to impress my friends
As a .NET programmer
I want to draw funny fractal pictures
*)

[<fact>]
let MoveTurtleToPosition() =
given ATurtle
|> andGiven IsRotated90DegreesToTheRight
|> whens (TurtleWalksSteps 9)
|> thens (TurtleIsLocatedAt (0,9))
|> endStory

Did you notice [<fact>] attribute just before the function definition? It is a xUnit.net specific attribute, telling xUnit.net that the function is a runnable test. So, why xUnit.net? Answer: xUnit.net is the currently the only test framework that runs static test methods, which is what F# functions compiles to.

Note: If you think that the story above is too low level to be a “good” user story, you’re right, but it’s just an example..

The “ATurtle”, “IsRotated90DegreesToTheRight”, “TurtleWalksSteps”, etc, are functions that you have to implement yourself. What these functions do is not FsStory’s business, except that they have the same type. It’s a good thing to think about this in advance.

If you’re testing something object oriented, i.e. a C# project, then you’re probably have to let the functions have the type () -> (). That is, they take no argument and return void, in C# lingo. You’d also need a mutable variable to accomplish this.

#light

open Turtle
open FsxUnit.Syntax

let mutable turtle = new Turtle() // turtle must have type Turtle

let ATurtle () = turtle <- new Turtle() // For reuse in same story let MovesOneStepForward () = turtle.Go() let IsMovedOneStepForward () = turtle.Position.X |> should equal 1 let RotationIs angle () = turtle.Direction |> should equal 0.0

It’s up to the developer what library she wants to use for her assertions. In this example, FsTest was used, but she could go for NUnit or NBehave or something else. I hadn’t actually tried this and do not longer think this will work. Either use xUnit.net or FsTest (which is based on xUnit.net).

Another style is to work with immutable objects. One example of immutable objects are value objects, in DDD. Immutable objects correspond well to functional programming principles. Here is an example of an implementation of a scenario when an immutable object is used in the SUT (System Under Test).

let ATurtle () = new TurtleImmutable()
let IsRotated90DegreesToTheRight = fun (turtle : TurtleImmutable) -> turtle.Left()
let TurtleWalksSteps steps = fun (turtle : TurtleImmutable) -> turtle.GoSteps(steps)
let TurtleIsLocatedAt (x,y) = fun (turtle : TurtleImmutable) -> turtle.Position |>
should equal (new Position(x,y)) ; turtle

To clarify, all methods on the (immutable) turtle return a new turtle and that turtle is returned and then passed in as an argument to the next test function (by FsStory). As you might have spotted, the example uses a lambda, an anonymous functions (the “fun”) instead of specifying an argument explicitly. It’s a good thing to get a running story before actually implementing the logic and assertions. Using the function “id” (just returning the argument) on the right-hand side is very helpful for getting everything to run.

You can find FsStory at http://www.codeplex.com/fsstory.

Posted in bdd, F#, FsStory | Leave a comment

BDD using NBehave + Rhino Mocks AMC

Update: I found an old blog post by Aslak Helles├Şy┬á(the main developer behind Cucumber) that touches on this subject.

Some time ago, I investigated what BDD is all about. In essence, it’s TDD with a twist. For example, the word “test” implies that we’re testing what someone (we?) already made, but TDD says we’re going to write the tests before the actual implementation of the unit of code. Somewhat, the word “test” has a direction backwards, while “should” has a direction forward. Hence, “should” is more comprehensive to use when describing and specifying the future. Makes sense?

What I’d like to show you is a piece of code I wrote to see how NBehave‘s story runner could work with Rhino Mocks‘ Auto Mocking Container[1, 2].

[Story, Test]
public void GetMoneyWhenPassGO()
{
// Set up and initialize
var mocks = new MockRepository();
var container = new Rhino.Testing.AutoMocking.AutoMockingContainer(mocks);
container.Initialize();

// Resolve and obtain references
IPlayerTurn turn = container.Create<PlayerTurn>();
IBoard board = container.Resolve<IBoard>();
IPlayer player = container.Resolve<IPlayer>();
turn.AddPlayers(new List<Player>() {player});

// Story begins here
var story = new Story("Player recieves money when passes 'GO'");

story
.AsA("Player")
.IWant("to recieve money when I pass 'GO'")
.SoThat("I can buy things that generate money");

story
.WithScenario("Normal play scenario")
.Given("A board with 4 squares", () => Expect.Call(board.NumberOfSquares).Return(4))
.And("a player near 'GO'", () => Expect.Call(board.GetIndexForPlayer(player)).Return(2))
.And("mockery has started", () => mocks.ReplayAll())
.When("player passes 'GO'",() => turn.PlayerSequence(player, 3))
.Then("the player earns $4000", () => player.AssertWasCalled(x => x.Credit(4000)));

}

When this test is run with ReSharper, the test passes and outputs the story with indentation. Nice! (Except the “mockery has started” part of the story..)

Now a question pops up: since we have only specified and tested the first (top-level) interaction, what about the rest of the interactions? I think this is a good question that leads us further down the rabbit hole.

A written user story comes from a dialogue with a person with domain knowledge. Hopefully, after some discussion, we have understood some of the moving parts of the domain problem the customer wants us to solve. Let’s assume that we want to implement a single feature at a time, a couple of questions arise: should we start top-down or bottom-up? And how far “up” should we go, i.e. should we start with the UI or the domain model, if we choose a top-down approach?

If we choose to start with the domain model, then I think the above way of specifying the behavior looks nice. The key question is where the classes in the story come from originally. I have no easy answer for that. Of course they should originate from the domain problem, but how? “The model is the code – the code is the model”, but it probably takes a while to “get it right”. Maybe code like the above could help us to see if we have understood the problem in the first place?

Now back to the question: “what about the rest of the interactions”? We have ensured that the class which is in “the center” of the particular interaction chain (the player turn) lives in a faked world (a small board and a player near go) and we finally assert that when something happens (player passes ‘GO’) then some state has changed (the player gets money). The nice thing is that we now know more about what functionality the dependent classes should provide. For example, IBoard needs to have a method GetIndexForPlayer and if there is a class implementing that interface, then a NotImplementedException is probably thrown from that method, in order to compile. Next step could be to start thinking on that particular method and choose to either write a mocked unit test or an “ordinary” unit test.

Of course, real acceptance tests are also needed, but the purpose and scope of those tests are quite different. At least that’s what I think.

What do you think?

Posted in Uncategorized | 2 Comments

The small things: Fisher Space Pen

I got this pen from my girlfriend as a christmas gift. It’s a Fisher Space Pen and I’m very happy for it!

I believe that it’s really worth investing in the cheap stuff you use daily, like pen and paper (though, in this case my girlfriend did the investment, but that’s another story). Of course, that’s assuming that you use pen and paper. You really should – pen and paper are great tools!

Posted in Uncategorized | 1 Comment

PomodoroButtButtButt

├średev was a fantastic conference! I can’t stress that enough! So why haven’t I blogged about it? Well, there’s so many blogs already about it (google on “├Şredev” and “blog”) so I don’t really know how to contribute more content, just repeat what’s already been said. That’s why.

Instead, I’m going to write a note on one thing that I’ve taken with me from a talk at ├średev: the Pomodoro Technique. It’s essentially a technique that takes agile to the personal productivity level: working in small and timeboxed iterations (25 minutes), with short breaks (3-5 minutes) between each iteration and longer breaks (15-30 minutes) between 4 iterations in a row. Oh, by the way, an iteration is called a pomodoro, italian for tomato. Why tomato? Because the inventor of the Pomodoro Technique, Francesco Cirillo, used an egg timer formed as a tomato during the early phase developing the technique. Further, each day starts with planning and ends with collecting and visualizing the data collected, ready to be analysed and retrospected.

So, the idea is very simple, but of course there a lot more to it. What you should start with is to read Staffan N├Âteberg‘s Pomodoro Technique in 5 minutes. Actually, when the videos from ├średev get published, you should start there: Staffan N├Âteberg did an excellent talk on the Pomodoro Technique, sometimes using hats and dolls to illustrate his points.

There’s also a quite large pdf by Francesco Cirillo available, but I haven’t had time to read that one yet.

I’ve just tried out the Pomodoro Technique myself for a couple of days now and some days have contained more pomodoros than others. Basically, I bought an egg timer for 25 SEK (around $3) and started with the fixed timebox part of the technique and logged the results. The second day I started to do some na├»ve estimation for each task. I also started with post-it notes for tasks, my personal pull system.

If you follow and read the links in this post, you’ll see that I don’t really do that much of the Pomodoro Technique! That’s ok with me, I’m aware of that and that’s why the title of this post is “PomodoroButtButtButt” (paraphrasing Jeff Sutherland’s ScrumButt). I’m just getting used to the habit though, and making the human beings around me used to it as well. No need to be extreme here..

By the way, I’m still recording my workday in TimeSnapper, now TimeSnapper Professional. But that’s a future blog post.

Posted in Uncategorized | 6 Comments

TimeSnapper against MultiTasking

I have been working at Dotway now, for almost two weeks. When your environment change, there’s a good opportunity for changing habits as well. So, I started with the habit of using TimeSnapper every morning. TimeSnapper is a tool that takes a screenshot every 5 seconds or so, and has the ability to “play” the images, as a movie. The movie obviously has a higher image frequency than 5 seconds, so a whole day takes approximately 5-10 minutes to play.

Essentially, you gain the ability to self-monitor – seeing yourself in third person. Early and frequent feedback is a really good thing to have in most areas, like TDD for development or Scrum for projects. In my opinion, TimeSnapper gives the same kind of early and frequent feedback. So, every morning I play the movie of yesterday, write down the activities in time intervals, analyse my behavior, and ask myself the question “What should I do today that make my morning analysis more joyful tomorrow?”. Let me explain..

I don’t like when I’m forced to write: “08:00-11:00, XX:ed, YY:ed and ZZ:ed” – that’s not really informative, i.e., how much time did I spent on XX, compared to YY? But it’s not the logging problem in itself that I have problems with, it’s that I know that it’s bad for productivity to multitask, but still I do it. Without knowing it as well, it seems. Constantly context switching is bad for productivity. So, I should only focus on one task simultaneously to make tomorrow morning a good start at the day.

Look, if you’re using GTD (a nice time management methodology), but instead of doing something useful instead read LifeHacker (a nice site/blog) every 10th minute, something is utterly wrong! Not really getting things done, are you? Though, it can be hard to see for yourself. TimeSnapper lets you visualize your behaviour at the computer, putting your (potentially) multi-tasking in an embarrasingly bright light to yourself.

Thanks to Scott Hanselman for making the tools list where I found TimeSnapper.

As a side note, I really like 43folders‘ new direction. Or, at least, this particular post.

Posted in Uncategorized | 1 Comment