Sunday, October 19, 2008

Code Kata : Monopoly

Yesterday evening, me and two other friends arranged a highly spontaneus and inofficial code kata, at my friend's apartment. The task was to develop a Monopoly game, using TDD. It was sort of an experiment as well, we wanted to see how TDD could help us discovering design, rather than inventing it.

We started by talking about the domain, listing some words that we thought were important to the game. Then we made a small domain model diagram, just with boxes and lines (the relations had no directions or multiplicities). This was fun! It felt like we were back in school again.. :)

After that, we started to make some user stories, each on a small piece of paper. Here are the stories we came up with (in prioritized order):
  • A player walks the number of steps the dices show.
  • In the beginning of the game, the ordering of player moves is determined.
  • Players act in the predetermined order (was later removed, redundant with previous).
  • A player hits or passes "Go" and earn 4000.
  • A player buys the street he/she is on.
Now, we could start to implement the game! :) But, as we realized, the first story was very hard, since we had no code to start with. Actually, starting to write the first test was probably the hardest. I think we made the conclusion that the first test we tried to write was to big, so we divided the test into smaller parts, and BOOM, it went much more smoother. Also, we tried to follow YAGNI, as much as possible.

An interesting detail is that we kind of get stuck on the "the dices show" part of the first story. It's obviously something that has to do with random number(s), but how should we test that? I.e., we thought that only players would need dices, but if a player use the Random() system method, then we must capture it in a public state in order to know if the player actually walked the number of steps that the dices show. Not nice! We felt the urge to really talk about this, to see if logical arguments could lead us into a good, and hopefully pragmatic, solution to this problem. We ended up with dependency injecting an "IDice" - something that could give us a random number between two and twelwe, and mocking the IDice in the test. Nice! Now we could manipulate the player through fake dices, without having code smells all over the place!

Though, in retrospective, it would have been nice with an expert on TDD in the room. In the end, you would like yourself (or the group) to ask good questions and answer them logically, but without experience, asking the right questions in the right time is hard. A teacher behind the back, mentoring and supporting would be nice to have. Reminds me a little about Polya, "How to Solve It". Though, doing the excercise without a "master" was probably a good idea, in some way: it made us (more) convinced about what we were doing, and if we weren't convinced, we had to talk about it.

We did the excercise for about six hours, but we had dinner and wine during that time as well, and perhaps we weren't that effective all the time :) Anyway, we implemented all the stories, except the last one (a half-baked story).

Thank you for a very nice evening!

Thursday, October 16, 2008

Turtle Graphics :: Changing Interface

Recalling, my first idea of the Turtle Graphics posts was to see if it was likely that a beginner in functional programming would have invented monads by himself/herself.

Let's change the interface a bit, such that a command is a function from log to log.

(I will reuse definitions from the original post, i.e. turtle definition and step)

> type Command = [Turtle] -> [Turtle]

> start = Turtle { x=0, y=0, alpha=0 }

> go, left, right :: Command
> go [] = []
> go (t:ts) = t {x = x t + step * cos (alpha t),
>   y = y t + step * sin (alpha t),

>   alpha = alpha t} : t : ts

> rotate :: Double -> Command

> rotate v [] = []

> rotate v (t:ts) = t {alpha = alpha t + v} : t : ts

> left = rotate (pi/2)
> right = rotate (-pi/2)

> execute :: [Command] -> Turtle -> [Turtle]
> execute cs l = (foldr (.) id cs) [l]

Basically, the primitive commands have to work on the whole list and consider the case of an empty list, whereas commands defined in terms of other commands don't have that restriction. It's also easy to define new commands:

> go3 = go . go . go

But the primitive commands don't look good at all! But, it's an easy fix..

The problem is of course with the type of Command. A primitive command only cares about the first turtle in the list (the newest one), so why should a command take a whole list as parameter?

> type Command = Turtle -> [Turtle]


> go, left, right :: Command

> go t = return $ t {x = x t + step * cos (alpha t),

>
  y = y t + step * sin (alpha t),
>   alpha = alpha t}

> rotate :: Double -> Command

> rotate v t = return $ t {alpha = alpha t + v}

> left = rotate (pi/2)
> right = rotate (-pi/2)


> -- [Turtle] -> (Turtle -> [Turtle]) -> [Turtle]

> |>| :: [Turtle] -> Command -> [Turtle]
> [] |>| f = []

> (l:ls) |>| f = (f l) ++ (l:ls)


So, for go and rotate, we use a little trick, using return instead of putting the result in a list. What is much more interesting is that we now have a little asymmetry in the type of a command. It is not possible anylonger to use (.) for combining commands, so we define |>| to do that for us.

We must use a little lambda to define new commands..

> go3 = \t -> t |>| go |>| go |>| go

..but that shouldn't be too much of a problem.

We're not done yet, but at least we took care about our little logging problem we had the previous post.

The ForEach extension method (C#)

Everyone knows about the foreach keyword, but have you ever noticed there are no equivalent extension method for IEnumerables? I.e. execute "this action" on each element. Perhaps the most simple extension method of them all, which is the reason I'll share it with you :)

public static class MyExtensionMethods
{
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
foreach(var item in list) action(item);
}
}

For you who aren't familiar with extension methods, what it really says is that, ForEach is a member method of IEnumerable<T>, and can be called by simply writing
myList.ForEach(myAction)

For example, to output each item of a list to the console, you could write:
myList.ForEach(x => Console.Write(x));

instead of
foreach(var x in in myList) Console.Write(x);

In this case you might not gain so much in terms of code size, but I think it makes the code more readable. You are reading text from left to right, so it makes sense having the for each statement to the right, right? :)
myList.WhereThis().SelectThat().DoThis();

(There is probably some kind of cool name for this pattern, like "The opposite of law of demeter"... Gustaf probably has more knowledge in this!)

Here is a more complex example of a combination of extension methods:
myList.Where(x => x.IsValid()).Select(x => x.ComputeValue()).Where(x => x > 0).ForEach(x => Console.Write(x));

Where and Select are also extension methods of IEnumerable. Without these you would have to write:

foreach(var x in myList)
{
if (x.IsValid())
{
var value = x.ComputeValue();
if (value > 0) Console.Write(value);
}
}

8 lines instead of 1! Impressed? :)

So, extension methods! Learn them, use them, and write your own!

Wednesday, October 15, 2008

Some thoughts on Turtle Graphics Basics

In the comments of last turtle post, Joel pointed out a way to get commands composable. I didn't quite get it to work, probably because of that Command is a type synonym and not a concrete type. The first time I saw the proposed solution, to combine commands with <|>, I got a little afraid. I'll explain why..

<Update>

Joel pointed out (in a mail) that Haskell98 doesn't permit instances of type synonyms or lists of types. If the flag "fglasgow-exts" is used, then the problem is solved.

</Update>

The biggest reason I got afraid was that it is still up to the consumer of the code to combine commands in a "good" way, i.e., to log intermediate positions. But, It would be perfectly legal to combine commands with (.) instead of (<|>), making the API quite risky. I now think a bit different..

It would be possible to kind of wrap the commands into a data structure of their own (as the Command pattern in OO):

> data C = C { unC :: Command }

In some way, this is very type-safe, since it will be cumbersome to un-wrap the commands to combine them in a "bad" way..

> go2 = C { (unC go) . (unC go) }

..thus, users are forced to use our special operator for combining commands. But there something I don't like about this. We're kind of forcing the users into a datastructure, just to restrict them. I think we loose a lot of nice functions (i.e. from the prelude) this way. Of course, we could define functions that makes it easier for the user, but the user still has to learn those functions. What I'm trying to say is that it sometimes is bad to invent a whole new API style from scratch, when for example a monadic style API has the benefit that more people know about it and that we can "piggyback" on all the tutorials on monads. Or maybe it's just me that is too focused on monads at the moment. ;)

I guess this could be a nice discussion? What do you think?

Right now, my biggest reason to be afraid of Joels solution is that it uses type classes, which is a very exotic feature, compared to other functional languages. There are obviously nice, but it would be hard to see how a "nice" Turtle Graphics API could be ported to i.e. F#, if we based the API on type classes.

Next: Changing interface on primitive commands

Tuesday, October 14, 2008

Joining Dotway!

Last Friday I joined Dotway! Dotway is a .NET consulting company and was founded in Malmö, but I will be working in the Gothenburg office.

Dotway is a Microsoft Gold partner (achieved through competencies) and offers services such as software development, design support, and training/mentoring. Dotway also practices agile and TDD, and "Dotway consultants are Certified ScrumMasters".

I will start working in the beginning of November. Very exciting!

Some links:
Dotway
Mikael Freidlitz
Johan Normén
Magnus Mårtensson
Øredev (a conference and a sister company)

Monday, October 13, 2008

Turtle Graphics Basics

Some weeks ago, I watched Don't fear the Monads, again. Beckman said something like "there nothing about monads that you don't already know" and "after some time, you'd be inventing monads yourself, but you probably wouldn't know that they were monads". Beckman inspired me to start a small (!) project on Turtle Graphics blog posts.

The idea is to write a very small piece of Haskell code in each post, where every post is a Turtle Graphics implementation. Or, not implementation, but rather just a model, so no real graphics. You can see them as small Turtle Graphics APIs, that focus entirerly on the data and not anything about presenting the data.

Now, not every API is an internal DSL, but for these posts I'll try to put on my language sun-glasses..

First we need a definition of a Turtle:
> data Turtle = Turtle {
> x :: Double,
> y :: Double,
> alpha :: Double -- alpha = 0 means East
> }
> deriving (Show)
The first idea (the trivial/naïve implementation) is to define functions with the type signatures Turtle -> Turtle. The functions I have in mind is go, left, right, and rotate, hopefully all self-explanatory. Let's do a type synonym, because it's fun:

> type Command = Turtle -> Turtle

Here are the commands, very basic:
> go, left, right :: Command
> go t = t { x = x t + step * cos (alpha t),
> y = y t + step * sin (alpha t),
> alpha = alpha t }

> left t = t { alpha = alpha t + pi/2 }
> right t = t { alpha = alpha t - pi/2 }

> rotate :: Double -> Command
> rotate v t = t { alpha = alpha t + v }

> step = 1
Note that rotate has a different type. Also note the order of the arguments: we can use currying so that if we give rotate just one argument (an angle), we will get a Command.

Let us just see what the user code looks like:

*Main> let t = Turtle {x = 1, y = 1, alpha = 0}
*Main> t
Turtle {x = 1.0, y = 1.0, alpha = 0.0}

*Main> go t
Turtle {x = 2.0, y = 1.0, alpha = 0.0}

We can combine functions with the operator (.)

*Main> (go . go) t
Turtle {x = 3.0, y = 1.0, alpha = 0.0}

And, of course, we can define new functions in terms of the basic ones:

*Main> let go2 = go . go
*Main> go2 t
Turtle {x = 3.0, y = 1.0, alpha = 0.0}

The presentation is a bit rough, especially for non-zero angles..

*Main> right t
Turtle {x = 1.0, y = 1.0, alpha = -1.5707963267948966}

..but I assume you can calculate from radians to degrees in your head.. ;)

As you might have seen, the ordering of arguments for rotate was important:

*Main> (go . (rotate pi) . go) t
Turtle {x = 1.0, y = 1.0000000000000002, alpha = 3.141592653589793}

If the ordering of arguments were different, the above would not have been possible to write. Instead we would have been forced to write a lambda-expression, which is maybe not the best example of a good user code (if you can avoid it, at least).

Note that we also can remove the definitions of left and right, and replace them with

> left' = rotate (pi/2)
> right' = rotate (-pi/2)

Now, a nice feature would be to let a user give a list of Commands and a Turtle to a function, returning the final position:

> runR :: [Command] -> Turtle -> Turtle
> runR [] t = t
> runR (c:cs) t = runR cs (c t)

Here's where I think it can be useful to know something about functions is general. For example, functions with type a -> a forms a monoid [1,2] together with the operator (.) and identity id. This allows us to write runR in a more readable form (now called run):

> run :: [Command] -> Turtle -> Turtle
> run cs t = (foldr (.) id cs) t

A monoid is a nice thing to be, but what is really the purpose with the run function? Isn't the whole goal with a "Turtle Graphics" that we compute a list of positions, so that we can plot them somewhere? It's no use just to calculate a final position: the picture will become pretty boring eventually.. ;)

What we need is a function that takes a list of commands and a start position, returning a list of positions:

> runHistory :: [Command] -> Turtle -> [Turtle]

We make runHistory a wrapper function around runToList:

> runHistory cs t = runToList cs [t]

> runToList :: [Command] -> [Turtle] -> [Turtle]
> runToList [] ts = ts
> runToList _ [] = []
> runToList (c:cs) (t:ts) = runToList cs ((c t) : t : ts)

<Update>

Joel pointed out (in the comments) that runHistory could be written as:

> runHistory = flip (scanr ($)) . reverse

It's of course a lot better than my definition(s), from a readable code perspective. I imagine that my version is more performant (since I do not reverse), but as we all know, performance only matters until you notice the problem (as I pointed out in the comments myself). So, I fell into the trap of pre-optimizing.. Oh my, oh my.

</Update>

Let's try it out:

*Main> runHistory [go,right,rotate pi, go,go] t
[Turtle {x = 2.0, y = 3.0, alpha = 1.5707963267948966},Turtle {x = 2.0, y = 2.0, alpha = 1.5707963267948966},Turtle {x = 2.0, y = 1.0, alpha = 1.5707963267948966},Turtle {x = 2.0, y = 1.0, alpha = -1.5707963267948966},Turtle {x = 2.0, y = 1.0, alpha = 0.0},Turtle {x = 1.0, y = 1.0, alpha = 0.0}]

Hmm, the presentation gets real ugly. Perhaps an implementation of (Show) would be nice, but that's out of scope for this post.

I think there's some smelly code here. We have "bolted on" a history feature on top of the basic commands, so the only knowledge of a history (or log) is in runHistory itself. From a logging perspective, the basic functions do not compose at all! Let me show you what I mean..

Suppose we define a go2 in terms of go (see above). Clearly, we would like go2 to write to the log twice. With the current implementation, this is impossible! There's no way that runHistory can write more than one time to the log, per command. Well, it could be done, but it's not pretty:

*Main> let go2 = [go,go]
(*Main> let prog = [go,go2,go] -- type error)
*Main> let prog = [[go],go2,[go]]
*Main> runHistory (concat prog) t

Even uglier:

*Main> let go3 = [go2,[go]]
(*Main> let prog = [[go],go3,[go]] -- type error)
*Main> let prog = [[[go]],go3,[[go]]]
*Main> runHistory (concat (concat prog)) t

From this, it's obvious that we need to let the basic functions be aware of history/logging. That would be the goal of future posts.


Comment/spoiler: Kenn Knowles has also written a blog post on a Turtle Graphics implementation. Though, the aim of my post(s) is to start out real basic and then evolve the code through several posts. Basically, Kenn's implementation is a "state-over-writer" monad transformer, with a self-implemented difference list as the writer monoid.

Wednesday, October 8, 2008

Better DI

I was watching "InfoQ: Mock Roles Not Object States" with Nat Pryce and Steve Freeman yesterday. I had read the paper previous to watching the video, and I pretty much expected the same content but in a different form. Boy was I wrong..

In particular, they talked a few minutes on an argument against Dependency Injection (DI), namely that the constructor gets lots and lots of arguments. I used DI the first time a couple of weeks ago, so I'm pretty new to it, and I wasn't sure I was doing exactly the right thing. And, yes, the constructors at some places became huge.

What the InfoQ presentation thought me was that not all interfaces a class use are dependencies per se. Classes can for example be equipped with default parts or policies, that can be changed after creation. The important thing is that the instance will work anyway, which is not the case if an instance is missing out a dependency.

This nice picture (screenshot from their slides) made it click for me:



Big thanks to Johan Normén who mentioned the paper on the SweNug meeting two weeks ago!