Wednesday, October 22, 2008

Category Theory

Guess what landed on my hallway floor today: "Basic Category Theory for Computer Scientists". Thank you Mr Mailman!


There's a lot of "greek" in there! Hopefully, I'll decipher it (and understand it, of course).

Tuesday, October 21, 2008

CoachTV

In the middle of August, David Heinemeier Hansson twittered this:
Lars Pind is doing video coaching: http://coachtvblog.com/?p=3 -- good thoughts on probability and significance. 4:59 PM Aug 16th
Since that date, I have been following Lars Pind's fantastic video blog, CoachTV.

I think it's hard to analyze yourself from the outside. Reminds me of a quote of Richard Feynman, the 1965 Nobel prize winner in physics:
"The first principle is that you must not fool yourself—and you are the easiest person to fool."
It's hard to summarize what Pind's message is, so I rather not try. Instead, I want to re-post a comment that I did on one of his episodes. What triggered me to post the comment was that Pind talked about eating and that the next time the viewer ate something, he/she should try to really look at the food, feel the texture, slowly swallow, feel the taste, etc, etc. You get the picture? Obviously, the overall "taste experience" is not only about always eating good food, but rather that it is up to you, if you bother to enjoy it or not. Made me think about music:
Lars, you said that when we eat or drink something, we should try to feel the taste and texture more. That reminded me of the composer John Cage, who had the same opinion about sound. His most famous piece is “4′33″, which is 4 minutes and 33 seconds of silence, written for piano. In summary, Cage had the opinion that there’s music everywhere, but it’s up to us to listen to it. So, even rush hour traffic can be music. Or when it’s so quiet that you can hear our own blood flow and pulse.

It’s up to ourselves to broaden our senses and perspectives, so that we can enjoy the music in our everyday life, also when sound is not involved per se.
Could it be that the same reasoning goes for your other sensations and feelings as well? If not, why?

Note: I actually wrote this post before watching episode #26 of CoachTV, where Lars asks the viewers to "tell our friends" about his show. Just thought you should know that.. :)

Monday, October 20, 2008

Podcast: Herding Code

There is a fairly new (May 2008) podcast that I listened to a lot lately (including their old episodes): Herding Code. These episodes are particularly nice:
Enjoy :)

Sunday, October 19, 2008

TDD, reflection and the PropertiesEqual extension method

In my last post I wrote about the extension method ForEach, which is a very simple but useful method, at least when it comes to readability.

In this post I'll try to explain another extension method, which I'll call PropertiesEqual. It's purpose is to extend the object class with a method to compare the properties of two objects:

public static bool PropertiesEqual<T>(this T obj1, T obj2)
{
return true if all properties of obj1 equals all properties of obj2
}

You probably know of the object.Equals method, which per default compares the memory addresses of two objects. That is, two objects are equal only if they are exactly the same object. If you really want to compare the content of two objects, you need to override this function in your class and manually compare them.

When I designed this function, I started with two simple test cases:
1. If two objects of the same class have the same public properties, yield true
2. If two objects of the same class have different public properties, yield false

Translated to code, this becomes:

class TestClass
{
public int A { get; set; }
public int B { get; set; }
}
[TestMethod()]
public void PropertiesEqualTest()
{
Assert.IsTrue(new Test { A = 1, B = 1 }.PropertiesEqual(new Test { A = 1, B = 1 }));
Assert.IsFalse(new Test { A = 1, B = 1 }.PropertiesEqual(new Test { A = 1, B = 0 }));
}

The implementation is very straight forward:

public static bool PropertiesEqual<T>(this T obj1, T obj2)
{
return typeof(T).GetProperties().All(property =>
{
var prop1 = property.GetValue(obj1, null);
var prop2 = property.GetValue(obj2, null);
return prop1.EqualsTo(prop2);
});
}

typeof(T).GetProperties() will return all public properties of T, and property.GetValue(obj, null) will return the value of a given property. The All extension method returns true only if all elements of the sequence satisfy the given condition, i.e. all properties are equal.

The test cases will pass fine, and we now have a simple way of comparing properties of two objects! In the next post I'll try to describe how to extend the method with support for recursive properties (compare properties of a property), and in the one after that I'll write about how to implement an IEqualityComparer based on this method.

EDIT: Note, these series aren't much of the type "here is a revolutionary new technique", but more of "here is how I would write the code for this". My focus is to get you to understand how I think when I design methods, not to tell you that "this is the way"!

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!