<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;DU4EQn87cSp7ImA9WxJVGE8.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990</id><updated>2009-07-06T07:05:03.109+10:00</updated><title>dave^2 = -1</title><subtitle type="html">A software development blog by some bloke called Dave.</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.davesquared.net/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default?start-index=26&amp;max-results=25&amp;redirect=false&amp;v=2" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>279</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><link rel="self" href="http://feeds.feedburner.com/davesquared" type="application/atom+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><entry gd:etag="W/&quot;CUYBSXc7eCp7ImA9WxJVEU0.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-3013805586070462248</id><published>2009-06-27T21:38:00.004+10:00</published><updated>2009-06-27T21:45:58.900+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-06-27T21:45:58.900+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="vs.net" /><title>ReSharper Live Template for Dependency Properties (C#)</title><content type="html">&lt;p&gt;The syntax for declaring WPF dependency properties can get a little tedious to type. I ended up creating a ReSharper Live Template which has been working nicely for me:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
public static readonly DependencyProperty $PropertyName$Property = 
    DependencyProperty.Register(&amp;quot;$PropertyName$&amp;quot;, typeof($PropertyType$), typeof($PropertyOwner$));

public $PropertyType$ $PropertyName$ {
    get { return ($PropertyType$) GetValue($PropertyName$Property); }
    set { SetValue($PropertyName$Property, value); }
}
&lt;/pre&gt;

&lt;p&gt;Then configure the substitutable variables as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PropertyName, no macro, #3 editable&lt;/li&gt;
&lt;li&gt;PropertyType, Guess type expected at this point, #2 editable&lt;/li&gt;
&lt;li&gt;PropertyOwner, Containing type name, not editable&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This lets me type in &lt;code&gt;dp&lt;/code&gt; and fill in the blanks. Hope this helps. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-3013805586070462248?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=iw3O6Z8NKXU:3kfqYB0dM9k:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=iw3O6Z8NKXU:3kfqYB0dM9k:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=iw3O6Z8NKXU:3kfqYB0dM9k:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=iw3O6Z8NKXU:3kfqYB0dM9k:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=iw3O6Z8NKXU:3kfqYB0dM9k:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=iw3O6Z8NKXU:3kfqYB0dM9k:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=iw3O6Z8NKXU:3kfqYB0dM9k:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/iw3O6Z8NKXU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/3013805586070462248/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=3013805586070462248" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3013805586070462248?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3013805586070462248?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/06/resharper-live-template-for-dependency.html" title="ReSharper Live Template for Dependency Properties (C#)" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;Ck8GQHozfip7ImA9WxJWEUs.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-8937032772400976910</id><published>2009-06-17T00:00:00.000+10:00</published><updated>2009-06-17T00:00:21.486+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-06-17T00:00:21.486+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><title>Occasional trouble mocking generic methods</title><content type="html">&lt;p&gt;I've seen a few people get bitten by an edge case of using generics with mocking frameworks. Let's look at a contrived example and see what's going on. We're using Rhino Mocks 3.5 in this case, but the symptoms described here are not specific to that mocking framework, but rather are related to how generics work in .NET.&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
public interface IFish{}
public class Eric : IFish{}
public interface IAquarium {
    IEnumerable&amp;lt;T&amp;gt; FindEverythingLike&amp;lt;T&amp;gt;(T thisThing);
}

[Test]
public void LookingForALicenceForMyPetFishEric() {
    var petFish = new Eric();
    var expectedErics = new[] {petFish};

    IAquarium stubAquarium = MockRepository.GenerateStub&amp;lt;IAquarium&amp;gt;();
    stubAquarium
        .Stub(aquarium =&amp;gt; aquarium.FindEverythingLike(Arg&amp;lt;IFish&amp;gt;.Is.Anything))
        .Return(expectedErics);

    var actualErics = stubAquarium.FindEverythingLike(petFish);
    Assert.That(actualErics, Is.EqualTo(expectedErics));
}
&lt;/pre&gt;

&lt;p&gt;Here we're asking our stubbed &lt;code&gt;IAquarium&lt;/code&gt; to return an &lt;code&gt;expectedErics&lt;/code&gt; array whenever it gets any &lt;code&gt;IFish&lt;/code&gt; as an argument to the generic &lt;code&gt;FindEverythingLike&amp;lt;T&amp;gt;()&lt;/code&gt; method. We then pass our &lt;code&gt;petFish&lt;/code&gt; to the method and get the actual enumerable returned from our stub. So what does this assertion give us?&lt;/p&gt;

&lt;pre&gt;
MockingGenerics.LookingForALicenceForMyPetFishEric : FailedNUnit.Framework.AssertionException:   Expected: &amp;lt; &amp;lt;Workshop.Tests.Eric&amp;gt; &amp;gt;
  But was:  null
&lt;/pre&gt;

&lt;p&gt;Oops, our stubbed value hasn't been returned. Our &lt;code&gt;petFish&lt;/code&gt; is an instance of class &lt;code&gt;Eric&lt;/code&gt;, which implements &lt;code&gt;IFish&lt;/code&gt;, so why isn't our stub returning our &lt;code&gt;expectedErics&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;The reason for this is that we are actually stubbing out &lt;code&gt;FindEverythingLike&amp;lt;IFish&amp;gt;()&lt;/code&gt;, but are calling &lt;code&gt;FindEverythingLike&amp;lt;Eric&amp;gt;()&lt;/code&gt;. While we declare this as a single generic method, the CLR actually calls these as two completely different method instances. This is obscured a bit by the fact that type inference is used to determine which method instance is called. If we don't rely on type inference we can get the test to pass:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
    var actualErics = stubAquarium.FindEverythingLike&amp;lt;IFish&amp;gt;(petFish);
    Assert.That(actualErics, Is.EqualTo(expectedErics));
&lt;/pre&gt;

&lt;p&gt;In the real examples where I've seen errors like this we generally have more collaborators involved and the problem becomes harder to detect. It's not a common case, requiring us passing different static types to a generic method where at first glance it looks reasonable to expect our call to resolve to the one method.&lt;/p&gt;

&lt;p&gt;Just to belabour the point for one more example, let's just confirm that it is the static type of our reference that determines which method instance is called, rather than the actual instance type:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
[Test]
public void GenericsAndMockingCanBeTroublesome() {
    IAquarium mockAquarium = MockRepository.GenerateMock&amp;lt;IAquarium&amp;gt;();    
    Eric petFish = new Eric();
    IFish sameFish = petFish;

    mockAquarium.FindEverythingLike(petFish);
    mockAquarium.AssertWasCalled(aquarium =&amp;gt; aquarium.FindEverythingLike(sameFish));
}
&lt;/pre&gt;

&lt;p&gt;This case fails, as we are calling &lt;code&gt;mockAquarium.FindEverythingLike&amp;lt;Eric&amp;gt;()&lt;/code&gt;, but asserting that &lt;code&gt;FindEverythingLike&amp;lt;IFish&amp;gt;()&lt;/code&gt; was called. Even though it is the same instance, the declared types of each reference at compile time are the ones that are used to dispatch to our generic method instance.&lt;/p&gt;

&lt;p&gt;Hope this helps save someone a couple of minutes of frustration. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-8937032772400976910?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qiAVo_0SQ5M:rXR0EmqSsxg:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=qiAVo_0SQ5M:rXR0EmqSsxg:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qiAVo_0SQ5M:rXR0EmqSsxg:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qiAVo_0SQ5M:rXR0EmqSsxg:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=qiAVo_0SQ5M:rXR0EmqSsxg:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qiAVo_0SQ5M:rXR0EmqSsxg:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qiAVo_0SQ5M:rXR0EmqSsxg:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/qiAVo_0SQ5M" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/8937032772400976910/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8937032772400976910" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8937032772400976910?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8937032772400976910?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/06/occasional-trouble-mocking-generic.html" title="Occasional trouble mocking generic methods" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;CUMMRHsyeip7ImA9WxJXGE0.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-8550708669427413171</id><published>2009-06-11T23:10:00.002+10:00</published><updated>2009-06-12T20:44:45.592+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-06-12T20:44:45.592+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="misc" /><title>Scenario-based unit testing post in PDF format</title><content type="html">&lt;p&gt;My last post on &lt;a href="http://www.davesquared.net/2009/06/moving-to-scenario-based-unit-testing.html"&gt;Moving to scenario-based unit testing in .NET&lt;/a&gt; was pretty long, even for me. I've just gone and done a rough conversion of it to PDF, so if you felt the topic was vaguely interesting but were put off by having to scroll through loads of my aesthetically-challenged blog screens, then feel free to give the PDF a go. I feel it would have really helped me had I read it a year or so ago, so I thought I'd put it in a more readable format to try and encourage someone else to actually read it. :)&lt;/p&gt;

&lt;p&gt;Unfortunately the conversion process didn't improve the actual content of the post, so you'll still have to bear with my insufferable ramblings if you decide to subject yourself to it. ;)&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Download as PDF: &lt;/b&gt; &lt;a href="http://davesquared.googlecode.com/files/MovingToScenarioBasedTesting.pdf"&gt;MovingToScenarioBasedTesting.pdf&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-8550708669427413171?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=fWEX52Ilsp8:wCftHsZpS0I:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=fWEX52Ilsp8:wCftHsZpS0I:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=fWEX52Ilsp8:wCftHsZpS0I:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=fWEX52Ilsp8:wCftHsZpS0I:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=fWEX52Ilsp8:wCftHsZpS0I:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=fWEX52Ilsp8:wCftHsZpS0I:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=fWEX52Ilsp8:wCftHsZpS0I:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/fWEX52Ilsp8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/8550708669427413171/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8550708669427413171" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8550708669427413171?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8550708669427413171?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/06/scenario-based-unit-testing-post-in-pdf.html" title="Scenario-based unit testing post in PDF format" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;CUMBRHYzcCp7ImA9WxJXGE0.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-5245798356704663390</id><published>2009-06-10T22:29:00.006+10:00</published><updated>2009-06-12T20:44:15.888+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-06-12T20:44:15.888+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="tdd" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title>Moving to scenario-based unit testing in .NET</title><content type="html">&lt;div class="note"&gt;&lt;p&gt;This post is pretty long, even for me. You can download it as a &lt;a href="http://davesquared.googlecode.com/files/MovingToScenarioBasedTesting.pdf"&gt;PDF file&lt;/a&gt; (roughly converted) which might be a bit easier to read. Unfortunately the conversion process didn't improve the actual content of the post, so you'll still have to bear with my insufferable ramblings if you decide to subject yourself to it. ;)&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Download as PDF: &lt;/b&gt; &lt;a href="http://davesquared.googlecode.com/files/MovingToScenarioBasedTesting.pdf"&gt;MovingToScenarioBasedTesting.pdf&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;

&lt;p&gt;From my observations most developers (myself included) start writing tests using &lt;a href="http://xunitpatterns.com/Testcase%20Class%20per%20Class.html"&gt;one testcase class per class under test&lt;/a&gt;. Due to an unfortunate attribute naming choice, NUnit users may know this as &amp;quot;fixture per class&amp;quot;, and implement it as one class marked &lt;code&gt;[TestFixture]&lt;/code&gt; holding all the tests that relate to one production class.&lt;/p&gt;

&lt;p&gt;I think the reason this approach is so common is because introductory testing and TDD examples tend to focus on smallish utilities like stacks or basic calculators, where fixture setups and object interactions tend not to get out of hand. In my experience, taking the knowledge learned during from basic examples and trying to apply them to Real Life&lt;sup&gt;TM&lt;/sup&gt; ends in pain, frustration, nausea, alcoholism and, in rare cases, spontaneous human combustion. Even worse, it may cause developers to abandon writing unit tests altogether!&lt;/p&gt;

&lt;p&gt;There are many alternatives for organising tests (testcase class per fixture, feature, method, etc.), but the one I've found easiest to adopt and use is a testcase class per &lt;i&gt;scenario&lt;/i&gt;. We've been using this at work across two teams for a few months now, and while not perfect it does seem to make writing, reading and maintaining tests relatively easy. In fact, I'm 99% sure that learning to write tests in this way initially (rather than the usual testcase class per class way) would avoid most of the problems we face when first trying to adopt unit testing and test driven development.&lt;/p&gt;

&lt;p&gt;The aim of this post is to describe what on earth I'm talking about, as well as how to move from testcase class per class to scenario-based testcase classes, and also outline some of the unresolved problems we've run into with this approach.&lt;/p&gt;

&lt;h2&gt;A note on terminology&lt;/h2&gt;
&lt;p&gt;I'm probably drastically misusing terminology here when I talk about scenario-based testing. The way I'm using the term &amp;quot;scenario&amp;quot; seems quite different to &lt;a href="http://en.wikipedia.org/wiki/Scenario_testing"&gt;scenario-based testing&lt;/a&gt; as described in Wikipedia, but I don't know a better name for it. The word &amp;quot;scenario&amp;quot; is used a lot when talking about &lt;a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development"&gt;Behaviour Driven Development (BDD)&lt;/a&gt; as well, but I wouldn't be so presumptuous to think this approach qualifies as BDD. It doesn't really seem to match the Dan North or Dave Astels definitions. Instead, I'd appreciate it if we ignore the terminology and just focus the basic ideas -- you can substitute whatever terminology you like! :)&lt;/p&gt;

&lt;h2&gt;The example&lt;/h2&gt;
&lt;p&gt;Let's look at the traditional way of introducing testing concepts -- a contrived example. Say we've been contracted by KAOS, an private company with a strong focus on research and development. Their latest project is something they casually refer to as The Doomsday Device. KAOS, being an agile sort of organisation, have given us some simple stories:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The screen should display a welcome message to the agent using the Doomsday Device.&lt;/li&gt;
&lt;li&gt;The user can click a button to fire the Doomsday Device&lt;/li&gt;
&lt;li&gt;After firing, the user cannot click the button again until the Doomsday Device has finished its firing sequence&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Seems fairly easy. We'll use a Model View Presenter style approach so we can test this logic without actually firing the device. Siegfried, the product owner, has assured us that the consequence of any bugs could be quite dire. He stresses &amp;quot;Vee are KAOS agents -- vee don't write bugs here!&amp;quot;.&lt;/p&gt;

&lt;h2&gt;Testcase class per class&lt;/h2&gt;
&lt;p&gt;We start off by creating a &lt;code&gt;DoomsDayDevicePresenterFixture&lt;/code&gt;, and then begin writing tests and filling in passing implementations. Here is what our fixture looks like when we're done:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
/* Fixture per class example */
[TestFixture]
public class DoomsDayDevicePresenterFixture {
    private IDoomsDayDeviceView stubView;
    private IDoomsDayDevice stubDoomsDayDevice;

    [SetUp]
    public void SetUp() {
        stubView = MockRepository.GenerateStub&amp;lt;IDoomsDayDeviceView&amp;gt;();
        stubDoomsDayDevice = MockRepository.GenerateStub&amp;lt;IDoomsDayDevice&amp;gt;();
        new DoomsDayDevicePresenter(this.stubView, this.stubDoomsDayDevice);
    }

    private void RaiseLoadedEventOnView() {
        stubView.Raise(view =&amp;gt; view.Loaded += null, this, EventArgs.Empty);
    }
    private void RaiseFireButtonPressedOnView() {
        stubView.Raise(view =&amp;gt; view.FireButtonPressed += null, this, EventArgs.Empty);
    }
    private void RaiseFiringCompletedOnDevice() {
        stubDoomsDayDevice.Raise(device =&amp;gt; device.FiringCompleted += null, this, EventArgs.Empty);
    }

    [Test]
    public void ShouldWelcomeEvilAgentWhenLoaded() {
        const String agentsName = &amp;quot;Siegfried&amp;quot;;
        stubDoomsDayDevice
            .Stub(device =&amp;gt; device.CurrentOperatorsName())
            .Return(agentsName);
        RaiseLoadedEventOnView();
        Assert.That(stubView.WelcomeMessage, Is.EqualTo(&amp;quot;Welcome KAOS Agent &amp;quot; + agentsName + &amp;quot;. What would you like to destroy today?&amp;quot;));
    }

    [Test]
    public void ShouldEnableFireButtonWhenViewLoaded() {
        RaiseLoadedEventOnView();
        Assert.That(stubView.FireButtonEnabled, Is.True);
    }    

    [Test]
    public void FireButtonShouldFireDoomsDayDevice() {
        RaiseLoadedEventOnView();
        RaiseFireButtonPressedOnView();
        stubDoomsDayDevice.AssertWasCalled(device =&amp;gt; device.Fire());
    }

    [Test]
    public void ShouldDisableFireButtonWhileFiring() {
        RaiseLoadedEventOnView();
        RaiseFireButtonPressedOnView();
        Assert.That(stubView.FireButtonEnabled, Is.False);
    }

    [Test]
    public void ShouldEnableFireButtonWhenFiringCompleted() {
        RaiseLoadedEventOnView();
        RaiseFireButtonPressedOnView();
        RaiseFiringCompletedOnDevice();
        Assert.That(stubView.FireButtonEnabled, Is.True);
    }    
}
&lt;/pre&gt;

&lt;p&gt;Our tests all pass. Hooray!&lt;/p&gt;

&lt;h2&gt;What's wrong with this?&lt;/h2&gt;
&lt;p&gt;What's wrong with this testcase class? Well, nothing really I guess. It's manageable enough for now. However when we start adding features we may find the lack of cohesion between the tests causes us pain (at least it always has for me. I'm quite happy to acknowledge I could just be doing it wrong).&lt;/p&gt;

&lt;p&gt;The main source of the cohesion problem is the setup used for each test. The testcase class has its own setup method, but the first few lines of each test performs some additional setup. In somes cases, such as the &lt;code&gt;ShouldDisableFireButtonWhileFiring()&lt;/code&gt; and &lt;code&gt;FireButtonShouldFireDoomsDayDevice()&lt;/code&gt;, this setup code is repeated. These two tests are really asserting two facts about the same situation (firing the device), but you can't easily see that from the test code. Test code can be a great way of communicating how your code works, but this lack of cohesion in the setups used can make it really difficult to parse out this information.&lt;/p&gt;

&lt;p&gt;Having setup information all over the place can make the test code hard to maintain. Changes like requiring a dependency to provide new data at a different time can cause large numbers of tests to break, especially when they've ended up with setups that don't truly reflect the contexts they use. Well factored tests can be a great enabler of change. Fragile tests have the opposite effect.&lt;/p&gt;

&lt;p&gt;One thing you can't see from this example, and to me one of the most important drawbacks, is the impact of this approach on test driven development. Most people I know who have learned/tried to learn TDD (especially when learning without a mentor) have done some of the examples, decided to apply it to a real project, sat down to write the first test and... have absolutely no idea where to start. Should we first test the presenter has wired up the correct events on the view? Should we construct a presenter and see if its null (don't laugh, I've seen it recommended!)? Knowing what tests to write to drive development was probably my greatest hurdle in learning TDD -- it is natural to keep thinking in terms of how we want objects and methods to work, rather than what we want the design to do, which robs you of the design benefits TDD can provide.&lt;/p&gt;

&lt;h2&gt;Testcase class per fixture?&lt;/h2&gt;
&lt;p&gt;The setup required for a series of tests is generally called the &lt;i&gt;test fixture&lt;/i&gt; -- basically, all the stuff that needs to be in place for the assertions in a test to apply and run successfully. To make managing these tests easier we could break them out into a series of testcase classes per fixture. But then we end up with another problem -- our fixtures overlap. Let's think this through for a moment and see if we can find out why this could pose a problem.&lt;/p&gt;

&lt;p&gt;All the tests start with a call to &lt;code&gt;RaiseLoadedEventOnView()&lt;/code&gt;, so we could just whack that in the setup and have a fixture for all our tests the rely on the loaded view. Except for the &lt;code&gt;ShouldWelcomeEvilAgentWhenLoaded()&lt;/code&gt;, which needs to stub out a value before we raise the loaded event. We could stub the value in the setup method as well, but then we lose the benefit of knowing which functionality relies on having that value available. Following this path leads to an increase in the amount of setup code, most of which doesn't apply to all the tests. This can end up obscuring what we are actually testing.&lt;/p&gt;

&lt;p&gt;If we were going to go by fixtures, what would we name them? We have one fixture that stubs an agent name and uses a loaded view, another that just needs a loaded view, two that share a fixture where we have a loaded view and a pressed button, and another that has a loaded view, pressed button, and a firing completed event. Based on fixture alone it's hard to come up with good names here, which is generally a sign that we have the wrong class break down.&lt;/p&gt;

&lt;p&gt;When I first looked at moving from testcase class per class, grouping tests by fixture was my first stop. I found I had trouble finding clean slices through the fixtures that would neatly group everything. Even when I thought I had it right, my next test would require a change to a fixture that invalidated the breakdown I had chosen. It seemed like I was getting closer to a good approach, but it was still missing something. It wasn't until some &lt;a href="http://www.shannoncornish.com/blog/"&gt;people&lt;/a&gt; &lt;a href="http://www.xerxesb.com/"&gt;much&lt;/a&gt; &lt;a href="http://blog.delfish.com/"&gt;smarter&lt;/a&gt; than me (although less bloggish :)) got together and came up with a better solution that everything started to click into place.&lt;/p&gt;

&lt;h2&gt;Testcase class per scenario&lt;/h2&gt;
&lt;p&gt;The change in thinking was to stop worrying about specific fixtures and setups and to group things by scenario. Bit anti-climatic I know, but the change in thought process seemed to fix the majority of the problems we were facing. By concentrating on scenario, and how our class under test should behave in that scenario, the fixtures naturally became more cohesive. The delineation between scenario-specific fixture setup and test logic became obvious. Fixtures and tests were easy to name, and trivial to write. For the first time I no longer struggled to come up with what to test next. Instead I just picked a scenario and started asserting facts about how my class should behave in that scenario and what state it should have.&lt;/p&gt;

&lt;p&gt;Of course, this really just ends up as another way of breaking things down by fixture, which I've spent the entirety of the last section complaining about. But I've found the change in thinking indispensable in getting this to work. It's very hard to establish up front exactly what fixtures you're going to need (which results in a lot of churning of test code), but it is generally fairly obvious what scenarios your objects need to work under. In a way, the nice fixture break down is a nice side-effect that comes out of having well-structure scenarios.&lt;/p&gt;

&lt;p&gt;I'm intending to post later on how to start from scratch using this approach, but seeing we've come this far lets look at the steps we can use to break our current testcase class into scenarios. Hopefully this will illustrate why I like this approach so much.&lt;/p&gt;

&lt;h2&gt;Refactoring toward scenario-based tests&lt;/h2&gt;
&lt;p&gt;The first step is to identify some scenarios in our existing testcase class. Any name referring to a time or event is a hint about the scenario the test relates to. The word &amp;quot;when&amp;quot; is a dead give-away. Scanning through our current tests I can see two that relate to &lt;i&gt;when the view is loaded&lt;/i&gt; (&lt;code&gt;ShouldWelcomeEvilAgentWhenLoaded()&lt;/code&gt; and &lt;code&gt;ShouldEnableFireButtonWhenViewLoaded()&lt;/code&gt;). We also have &lt;code&gt;ShouldDisableFireButtonWhileFiring()&lt;/code&gt;. When is the device firing? Looking at the code in that test, it is &lt;i&gt;when the fire button is pressed&lt;/i&gt;. The &lt;code&gt;FireButtonShouldFireDoomsDayDevice()&lt;/code&gt; also seems to relate to this scenario. And lastly we have &lt;code&gt;ShouldEnableFireButtonWhenFiringCompleted()&lt;/code&gt; -- so &lt;i&gt;when firing completed&lt;/i&gt; sounds like a good scenario for that one. (You don't have to identify all the scenarios up front, just enough to get you started.)&lt;/p&gt;

&lt;p&gt;The second step is to pick one of the identified scenarios and create a testcase class for it. We can then proceed in a couple of ways. One way is to start moving tests one at a time into our new file that relate to the new scenario. Another is to copy and paste the entirety of the old testcase class into our new file, and start removing things that don't relate to the scenario. We repeat this until all our old test cases are in scenarios.&lt;/p&gt;

&lt;p&gt;The final step is to factor out the duplication between our testcase scenarios into helper methods in a common base class or two. You can probably get away with doing this as you go, but I'd advise against doing it too prematurely. Wait until the code in two or three scenarios is screaming to be consolidated, and then do it. Otherwise you can wind up extracting commonalities that aren't really there, and we go back to losing cohesion between our setups and tests.&lt;/p&gt;

&lt;p&gt;Let's have a look at the &lt;i&gt;when view is loaded&lt;/i&gt; scenario. I'll create a new subfolder in our test project called &lt;code&gt;DoomsDayDevicePresenterScenarios&lt;/code&gt;, then create a &lt;code&gt;WhenViewLoaded.cs&lt;/code&gt; class. I'm quite a fan of underscore-overload (cue &lt;a href="http://www.davesquared.net/2008/05/bdd-test-naming-with-autohotkey.html"&gt;shameless post plug&lt;/a&gt;), so I'd prefer to use &lt;code&gt;When_view_loaded&lt;/code&gt;, but I'll try and skip potentially heated debates for now. :)&lt;/p&gt; 

&lt;p&gt;The code below is how it looks after refactoring out some duplication:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
namespace DaveSquared.Kaos.Tests.DoomsDayDevicePresenterScenarios {
    public partial class DoomsDayDevicePresenterScenario {
        [TestFixture]
        public class WhenViewLoaded : ScenarioBase {
            const string AgentsName = &amp;quot;Siegfried&amp;quot;;

            [SetUp]
            public void SetUp() {
                CreateDoomsDayDevicePresenterAndDependencies();
                stubDoomsDayDevice.Stub(device =&amp;gt; device.CurrentOperatorsName()).Return(AgentsName);
                RaiseLoadedEventOnView();
            }

            [Test]
            public void ShouldWelcomeEvilAgent() {
                Assert.That(stubView.WelcomeMessage, Is.EqualTo(&amp;quot;Welcome KAOS Agent &amp;quot; + AgentsName + &amp;quot;. What would you like to destroy today?&amp;quot;));
            }

            [Test]
            public void ShouldEnableFireButton() {
                Assert.That(stubView.FireButtonEnabled, Is.True);
            }
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;Look how beautifully simple those tests are -- both one line assertions. And it reads nicely too: when view loaded, should welcome evil agent, and should enable fire button. You'll notice I've committed one of the sins I mentioned in my rantings about testcase class per fixture -- I've stubbed out a value in our setup that doesn't relate to all our tests. There are a couple of reasons that I don't care in this case. First, our setup focuses on what is required for this scenario, and the current agent's name happens to be important to this scenario, even if not to all the tests. I'm still getting good cohesion vibes. Second, I can use constants and properties with decent names to make sure the expected state of the scenario is clear. Thirdly, it just doesn't seem to cause me any troubles in real life, unlike when I tried breaking things down by fixture alone.&lt;/p&gt;

&lt;div class="note"&gt;You may have noticed a weird partial class thingoe happening here. This was suggested by a &lt;a href="http://www.shannoncornish.com/blog/"&gt;colleague&lt;/a&gt; to make scenarios more discoverable from within Resharper. If all scenarios related to our presenter are inner classes of the &lt;code&gt;DoomsDayDevicePresenterScenario&lt;/code&gt; partial class, then Resharper's &amp;quot;go to type&amp;quot; command (&lt;code&gt;Ctrl + T&lt;/code&gt; on my configuration) will let us select the partial class, then list all the scenarios for us to jump to. It adds some code noise, and isn't strictly necessary, but does make navigating around your tests easier.&lt;/div&gt;

&lt;p&gt;Let's move on to our next scenario.&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
public partial class DoomsDayDevicePresenterScenario {
    [TestFixture]
    public class WhenFireButtonPressed : ScenarioBase {
        [SetUp]
        public void SetUp() {
            CreateDoomsDayDevicePresenterAndDependencies();
            RaiseLoadedEventOnView();
            RaiseFireButtonPressedOnView();
        }

        [Test]
        public void ShouldFireDevice() {
            stubDoomsDayDevice.AssertWasCalled(device =&amp;gt; device.Fire());
        }

        [Test]
        public void ShouldDisableFireButton() {
            Assert.That(stubView.FireButtonEnabled, Is.False);
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;Compare this to how one of these tests used to look.&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
/* plus [SetUp] method code */
[Test]
public void FireButtonShouldFireDoomsDayDevice() {
    RaiseLoadedEventOnView();
    RaiseFireButtonPressedOnView();
    stubDoomsDayDevice.AssertWasCalled(device =&amp;gt; device.Fire());
}
&lt;/pre&gt;

&lt;p&gt;Even though this is a trivial example, the new version is much clearer and cleaner. You'll have to take my word for it, but this applies even as you get to more complicated, real code. You tend to push more into the scenario setup (which is exactly what the setup is for) and the tests themselves stay trivial.&lt;/p&gt;

&lt;p&gt;Let's look at the final scenario, and at our base class which we have used to keep duplication in check (although not eliminated, as we'll discuss later).&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
[TestFixture]
public class WhenFiringCompleted : ScenarioBase {
    [SetUp]
    public void SetUp() {
        CreateDoomsDayDevicePresenterAndDependencies();
        RaiseLoadedEventOnView();
        RaiseFireButtonPressedOnView();
        RaiseFiringCompletedOnDevice();
    }

    [Test]
    public void ShouldEnableFireButton() {
        Assert.That(stubView.FireButtonEnabled, Is.True);
    }
}
&lt;/pre&gt;

&lt;pre class="brush:csharp"&gt;
public class ScenarioBase {
    protected IDoomsDayDeviceView stubView;
    protected IDoomsDayDevice stubDoomsDayDevice;

    protected void CreateDoomsDayDevicePresenterAndDependencies() {
        stubView = MockRepository.GenerateStub&amp;lt;IDoomsDayDeviceView&amp;gt;();
        stubDoomsDayDevice = MockRepository.GenerateStub&amp;lt;IDoomsDayDevice&amp;gt;();
        new DoomsDayDevicePresenter(this.stubView, this.stubDoomsDayDevice);
    }
    protected void RaiseLoadedEventOnView() {
        stubView.Raise(view =&amp;gt; view.Loaded += null, this, EventArgs.Empty);
    }
    protected void RaiseFireButtonPressedOnView() {
        stubView.Raise(view =&amp;gt; view.FireButtonPressed += null, this, EventArgs.Empty);
    }
    protected void RaiseFiringCompletedOnDevice() {
        stubDoomsDayDevice.Raise(device =&amp;gt; device.FiringCompleted += null, this, EventArgs.Empty);
    }
}
&lt;/pre&gt;

&lt;h2&gt;Issues with this approach&lt;/h2&gt;
&lt;h3&gt;Duplication in setup methods&lt;/h3&gt;
&lt;p&gt;All the &lt;code&gt;[SetUp]&lt;/code&gt; methods in our scenarios have some duplication -- creating the subject under test and raising basic events. Why don't we factor all this into the base class? There's a few points to consider here. First, do we really want to hide this duplicated setup code? Scott Bellware questions this under the subheading &lt;a href="http://www.code-magazine.com/article.aspx?quickid=0805061&amp;page=5"&gt;Reuse: Friend or Foe&lt;/a&gt; in an article on BDD for CoDe Magazine:&lt;/p&gt;

&lt;blockquote&gt;
&amp;quot;Specification code is intended to document the behaviors of the system, and this often means leaving duplicated code in-place to support the learnability of the specs... If you do move common context code to a base class, do so with care for how you’re impacting the learning experience of the code&amp;quot;
&lt;/blockquote&gt;

&lt;p&gt;Having the setup steps repeated to a degree in each scenario (although with the logic behind each step encapsulated as methods in the base class) is great for documenting the scenario, and also helpful with scenario's with fixtures that diverge from the more standard cases (an example of a divergent fixture is one that tests exceptions thrown from a constructor, so we can't have a constructed object setup already).&lt;/p&gt;

&lt;p&gt;On the flip side, developers have good reason to be wary of duplication, having Don't Repeat Yourself drummed into them from the moment they are first exposed to inheritance. You can do some really clever things in terms of context base classes. One of the cleverest of these I've seen is &lt;a href="http://blog.jpboodhoo.com/developwithpassionbdd.aspx"&gt;JP Boodhoo's developwithpassion.bdd approach&lt;/a&gt;, which has the downside of looking completely foreign to people who speak C#, but has the upside of being really nice once you get used to it.&lt;/p&gt;

&lt;p&gt;If the duplication bothers you, you can have a general context base class with an existing &lt;code&gt;[SetUp]&lt;/code&gt; method that provides hooks like &lt;code&gt;BeforeSetup()&lt;/code&gt;, &lt;code&gt;AfterDependenciesCreated()&lt;/code&gt; etc. This lets your scenarios hook into whichever parts of the setup chain it needs to and do things like stub out calls. The real trick comes when you want to chain together contexts, which is something &lt;a href="http://blog.jpboodhoo.com/developwithpassionbdd.aspx"&gt;JP's&lt;/a&gt; approach gives you, and something which you get for free with tools like rspec (using &lt;a href="http://blog.codefront.net/2007/12/30/why-i-love-rspec-nested-example-groups/"&gt;nested blocks&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;This is something the purist in me is still questioning, but in practice we've just been leaving the duplication in and have had little to no problems with it, mainly because the duplication is contained to a small, related area, and because the logic itself is neatly encapsulated in a base class.&lt;/p&gt;

&lt;h3&gt;What goes into the base class?&lt;/h3&gt;
&lt;p&gt;Anything that can conceivably apply to every scenario. Fields for dependencies, methods to create a subject under test, common operations like raising events etc. You can eliminate some of this by using an automocker, but this can hide design smells like your SUT having too many dependencies.&lt;/p&gt;

&lt;h3&gt;Tests that apply to multiple scenarios&lt;/h3&gt;
&lt;p&gt;Sometimes you'll come across a test that should really apply across all the scenarios, an invariant if you will. There's a few approaches for dealing with this. You can put the test in the base class, and it will automatically run against all inheriting scenarios. I hate this approach -- it means you can get multiple failures from one problem, and I don't like the lack of clarity you get with tests being pulled in mysteriously from a base class. You can also create a specific scenario for these things, calling it &lt;code&gt;Always&lt;/code&gt;, or if you like the when-convention, &lt;code&gt;WhenEver&lt;/code&gt; :).&lt;/p&gt;

&lt;p&gt;I really don't like either of these approaches. I've become increasingly suspicious of this actually being a test smell. If you have logic that doesn't depend on a specific scenario, then this could be a cue to extract this into another class to isolate it properly for testing. You can then check the subject under test uses the other class correctly, without worrying about the behaviour changing across multiple scenarios.&lt;/p&gt;

&lt;p&gt;We've used all three approaches, with my preference being for isolating the behaviour properly. The &lt;code&gt;WhenEver&lt;/code&gt; style approach feels a bit dirty but hasn't caused much grief. The inherited test thing has had mixed results.&lt;/p&gt;

&lt;h3&gt;Using in conjunction with other organisational methods&lt;/h3&gt;
&lt;p&gt;Sometimes you end up sprouting classes or writing utilities that don't seem to have a home or fit a particular scenario. In these cases falling back to lumping everything in the one fixture can work just fine. As this post tried to show, it's pretty easy to move to scenario-based testcase classes in future once some scenarios start emerging or when the single fixture starts giving you grief.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Writing tests around scenarios is a way organising your tests which, in my opinion, makes test code easier to write, helps identify common fixtures, and improves the readability and maintainability of tests. Writing testcase classes per scenario ends up breaking down tests by common fixture, but focusing on the scenario makes this breakdown occur more naturally and more maintainably. It is also pretty straight forward to refactor existing tests into this format.&lt;/p&gt;

&lt;p&gt;If anyone actually made it this far, I'd love to hear any comments you have on this, both so I can get valuable feedback, and also to lavish you with compliments for actually getting through this epic :). This technique has really dramatically improved how I practice TDD and approach testing, so hopefully it will also help someone else out there.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-5245798356704663390?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=d_wIPZ-TkeU:bRp4Y-xdFDg:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=d_wIPZ-TkeU:bRp4Y-xdFDg:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=d_wIPZ-TkeU:bRp4Y-xdFDg:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=d_wIPZ-TkeU:bRp4Y-xdFDg:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=d_wIPZ-TkeU:bRp4Y-xdFDg:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=d_wIPZ-TkeU:bRp4Y-xdFDg:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=d_wIPZ-TkeU:bRp4Y-xdFDg:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/d_wIPZ-TkeU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/5245798356704663390/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=5245798356704663390" title="18 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/5245798356704663390?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/5245798356704663390?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/06/moving-to-scenario-based-unit-testing.html" title="Moving to scenario-based unit testing in .NET" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">18</thr:total></entry><entry gd:etag="W/&quot;D0ICRXw-fip7ImA9WxJQGUg.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-7640912826339682525</id><published>2009-06-03T00:35:00.004+10:00</published><updated>2009-06-03T01:12:44.256+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-06-03T01:12:44.256+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="c#4" /><title>Dynamic disappointment</title><content type="html">&lt;p&gt;I've been eagerly awaiting .NET 4 and the new &lt;code&gt;dynamic&lt;/code&gt; feature in C#, but after taking the beta for a spin I've run in to a major disappointment. Let's take &lt;code&gt;dynamic&lt;/code&gt; for a quick spin and see what's got me so devastated.&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
public class Dynamic : DynamicObject {
    Dictionary&amp;lt;String, object&amp;gt; members = new Dictionary&amp;lt;string, object&amp;gt;();
    public override bool TrySetMember(SetMemberBinder binder, object value) {            
        members[binder.Name] = value;
        return true;
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result) {
        return members.TryGetValue(binder.Name, out result);
    }
}

[TestFixture]
public class Disappointment {
    [Test]
    public void CanCreateAndCallAMethod() {
        dynamic anObject = new Dynamic();
        anObject.AMethod = new Func&amp;lt;int&amp;gt;(() =&amp;gt; 1);
        Assert.That(anObject.AMethod(), Is.EqualTo(1));
    }
}
&lt;/pre&gt;

&lt;p&gt;Here we've created a sub-class of &lt;code&gt;DynamicObject&lt;/code&gt;, which lets us play in the world of dynamic lookups from C#. We override &lt;code&gt;TrySetMember(...)&lt;/code&gt; and &lt;code&gt;TryGetMember(...)&lt;/code&gt; to use a dictionary as a backing store for members. Our test assigns a method called &lt;code&gt;AMethod&lt;/code&gt; to a dynamic object at run time, then executes it. It passes! Awesome!&lt;/p&gt;

&lt;h2&gt;If it walks and quacks like a duck, too bad!&lt;/h2&gt;
&lt;p&gt;Let's declare an &lt;code&gt;ICanAdd&lt;/code&gt; interface, as well as a class that uses objects that support the &lt;code&gt;ICanAdd&lt;/code&gt; interface to, well, add stuff.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;
public interface ICanAdd {
    int Add(int a, int b);
}

public class SomethingThatAdds {
    private ICanAdd adder;
    public SomethingThatAdds(ICanAdd adder) {
        this.adder = adder;
    }
    public int FirstNumber { get; set; }
    public int SecondNumber { get; set; }
    public int AddNumbers() {
        return adder.Add(FirstNumber, SecondNumber);
    }
}
&lt;/pre&gt;

&lt;p&gt;We can add this method to our dynamic object so that it supports the same operations as the &lt;code&gt;ICanAdd&lt;/code&gt; interface:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
[Test]
public void CanCreateADynamicAdder() {
    dynamic adder = new Dynamic();
    adder.Add = new Func&amp;lt;int, int, int&amp;gt;((first, second) =&amp;gt; first + second);
    Assert.That(adder.Add(1, 3), Is.EqualTo(4));
}
&lt;/pre&gt;

&lt;p&gt;This works fine, but when we try to combine static and dynamic worlds we run into problems:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
[Test]
public void CannotUseDynamicAdderForAnythingUseful() {
    dynamic adder = new Dynamic();
    adder.Add = new Func&amp;lt;int, int, int&amp;gt;((first, second) =&amp;gt; first + second);
    var somethingThatCanAdd = new SomethingThatAdds(adder); /* Fails here at runtime */
    somethingThatCanAdd.FirstNumber = 10;
    somethingThatCanAdd.SecondNumber = 20;
    Assert.That(somethingThatCanAdd.AddNumbers(), Is.EqualTo(30));
}
&lt;/pre&gt;

&lt;p&gt;This compiles, but at runtime we get the test failing with the following &lt;code&gt;RuntimeBinderException&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;
DaveSquared.DynamicDisappointment.Disappointment.CannotUseDynamicAdderForAnythingUseful:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 
The best overloaded method match for 'DaveSquared.DynamicDisappointment.SomethingThatAdds.SomethingThatAdds(DaveSquared.DynamicDisappointment.ICanAdd)' has some invalid arguments
  at CallSite.Target(Closure , CallSite , Type , Object )
  at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
  at DaveSquared.DynamicDisappointment.Disappointment.CannotUseDynamicAdderForAnythingUseful() ...
&lt;/pre&gt;

&lt;p&gt;The exception is fairly clear -- the C# &lt;code&gt;RuntimeBinder&lt;/code&gt; is trying to call the &lt;code&gt;SomethingThatAdds(ICanAdd)&lt;/code&gt; constructor, but we've given it a &lt;code&gt;dynamic&lt;/code&gt; instance instead. Based on my fairly primitive understanding of this stuff, in order to integrate dynamic lookups into the statically typed CLR, &lt;code&gt;dynamic&lt;/code&gt; is actually implemented as a static type. So even though we're using dynamic member lookups at runtime, we still need to abide by the type system and pass methods the static types they expect.&lt;/p&gt;

&lt;p&gt;If we modify our original &lt;code&gt;SomethingThatAdds&lt;/code&gt; class to explicitly accept the &lt;code&gt;dynamic&lt;/code&gt; type then our last test passes:&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;
public class SomethingThatAdds {
    private dynamic adder;
    public SomethingThatAdds(dynamic adder) {
        this.adder = adder;
    }
    /* ... snip ... */
}
&lt;/pre&gt;

&lt;p&gt;I'm aware I'm probably expecting too much, but having to explicitly modify our code in order to make this kind of use of the dynamic feature for &lt;a href="http://en.wikipedia.org/wiki/Duck_typing"&gt;duck typing&lt;/a&gt; is, well, disappointing. It would be great to see something like &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx"&gt;Jon Skeet's &lt;code&gt;dynamic&amp;lt;T&amp;gt;&lt;/code&gt; idea&lt;/a&gt; get into the final release so we can get the best of both worlds. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-7640912826339682525?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Qm1wEGjKj7U:il8aswKRjG0:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=Qm1wEGjKj7U:il8aswKRjG0:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Qm1wEGjKj7U:il8aswKRjG0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Qm1wEGjKj7U:il8aswKRjG0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=Qm1wEGjKj7U:il8aswKRjG0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Qm1wEGjKj7U:il8aswKRjG0:G79ilh31hkQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=G79ilh31hkQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Qm1wEGjKj7U:il8aswKRjG0:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/Qm1wEGjKj7U" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/7640912826339682525/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=7640912826339682525" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/7640912826339682525?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/7640912826339682525?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/06/dynamic-disappointment.html" title="Dynamic disappointment" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total></entry><entry gd:etag="W/&quot;Ck4DQXw4fip7ImA9WxJRF0U.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-6883158350465625449</id><published>2009-05-20T10:56:00.000+10:00</published><updated>2009-05-20T10:56:10.236+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-05-20T10:56:10.236+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="git" /><title>Setting up Git difftool on Windows</title><content type="html">&lt;p&gt;After installing Windows 7 I had trouble getting &lt;a href="http://www.davesquared.net/2009/02/setting-up-diff-and-merge-tools-for-git.html"&gt;&lt;code&gt;git diff&lt;/code&gt; to work properly with diffmerge&lt;/a&gt;. In fact, any external tool I tried to define would hang PowerShell once it exited. Unfortunately in the time I had to look at it I couldn't figure out if this was due to a new version of PowerShell with Windows 7, the new version of &lt;a href="http://code.google.com/p/msysgit/"&gt;MSys Git&lt;/a&gt; I had installed, or something strange after switching to x64 architecture. What I did have time for was to find a workaround using &lt;code&gt;git difftool&lt;/code&gt;, which is a new command added to Git as of version 1.6.3.&lt;/p&gt;

&lt;p&gt;The workaround is essential just a tweak of &lt;a href="http://www.davesquared.net/2009/02/setting-up-diff-and-merge-tools-for-git.html"&gt;the steps we used previously to get &lt;code&gt;git diff&lt;/code&gt; working&lt;/a&gt;, so its probably easiest to have a quick skim through that before going through this.&lt;/p&gt;

&lt;h2&gt;Configuration tweaks&lt;/h2&gt;
&lt;p&gt;First alteration to the previous approach was to create a difftool wrapper for Diffmerge. I called this &lt;code&gt;git-diff-diffmerge-wrapper.sh&lt;/code&gt; and put it in my &lt;code&gt;Git/cmd&lt;/code&gt; directory (which is also on my PATH).&lt;/p&gt;

&lt;pre&gt;
#!/bin/sh
&amp;quot;C:/Program Files (x86)/SourceGear/DiffMerge/DiffMerge.exe&amp;quot; &amp;quot;$1&amp;quot; &amp;quot;$2&amp;quot; | cat
&lt;/pre&gt;

&lt;p&gt;Next step was to update &lt;code&gt;.gitconfig&lt;/code&gt; to disable the previously added external tool setup for &lt;code&gt;git diff&lt;/code&gt;, and configure &lt;code&gt;git difftool&lt;/code&gt; in its place.&lt;/p&gt;

&lt;pre&gt;
[diff]
 #external = git-diff-wrapper.sh
 tool = diffmerge

[difftool &amp;quot;diffmerge&amp;quot;]
 cmd = git-diff-diffmerge-wrapper.sh &amp;quot;$LOCAL&amp;quot; &amp;quot;$REMOTE&amp;quot;
 
# ... snipping rest of .gitconfig ... # 
&lt;/pre&gt;

&lt;p&gt;I've left the external tool commented out (prefixed by #). This syntax is more in line with the way the we configured the &lt;code&gt;git mergetool&lt;/code&gt; &lt;a href="http://www.davesquared.net/2009/02/setting-up-diff-and-merge-tools-for-git.html"&gt;last time&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Using &lt;code&gt;git difftool&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;Now whenever we type &lt;code&gt;git diff&lt;/code&gt; we will get the standard, textual git difference listing. If we want to use the externally configured tool, we need to type &lt;code&gt;git difftool&lt;/code&gt; (followed by the usual range of &lt;a href="http://www.kernel.org/pub/software/scm/git/docs/git-diff.html"&gt;diff options&lt;/a&gt;) and follow the prompts instead. I actually like having the ability to switch between a quick diff and firing up an external tool. With this approach we can also configure multiple diff tools and pick whichever one is our favourite at the moment (or just try out a new diff tool). The command also closely parallels that used to bring up an external tool for merging (&lt;code&gt;git mergetool&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;I wish I knew what caused my original issue, but at least I've got my graphical diff tools back for Git. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-6883158350465625449?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=PNDEhEifK5I:C4wsk1EQ7pY:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=PNDEhEifK5I:C4wsk1EQ7pY:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=PNDEhEifK5I:C4wsk1EQ7pY:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=PNDEhEifK5I:C4wsk1EQ7pY:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=PNDEhEifK5I:C4wsk1EQ7pY:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=PNDEhEifK5I:C4wsk1EQ7pY:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/PNDEhEifK5I" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/6883158350465625449/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=6883158350465625449" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/6883158350465625449?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/6883158350465625449?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/05/setting-up-git-difftool-on-windows.html" title="Setting up Git difftool on Windows" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;C04FQnw4cCp7ImA9WxVbFUQ.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-5212532788847946123</id><published>2009-04-02T00:10:00.005+11:00</published><updated>2009-04-02T00:18:33.238+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-02T00:18:33.238+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="ruby" /><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><title>Basic .NET builds using Rake</title><content type="html">&lt;p&gt;I was starting up a new hobby project the other night and thought I'd try using &lt;a href="http://rake.rubyforge.org/"&gt;Rake&lt;/a&gt; to script my build (instead of pure MSBuild, Nant, or just plain VS). Now Ruby and I generally don't get on too well, so I was really surprised with how easy I found it to setup, and even more surprised with how much I enjoyed it. :)&lt;/p&gt;

&lt;h2&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Um, &lt;a href="http://www.ruby-lang.org/en/downloads/"&gt;Ruby&lt;/a&gt;. The installer I used gave me Ruby with Rake included. We'll also need a simple .NET solution. I created one with a structure that looked a bit like this:&lt;/p&gt;

&lt;ul&gt;
&lt;li class="folder-icon"&gt;DaveSquared.SampleProject&lt;/li&gt;
  &lt;ul&gt;
    &lt;li class="folder-icon"&gt;build&lt;/li&gt;
      &lt;ul&gt;&lt;li class="file-icon"&gt;&lt;b&gt;rakefile.rb&lt;/b&gt;&lt;/li&gt;&lt;/ul&gt;
    &lt;li class="folder-icon"&gt;src&lt;/li&gt;
   &lt;ul&gt;
     &lt;li class="folder-icon"&gt;DaveSquared.SampleProject.Tests&lt;/li&gt;
  &lt;li class="folder-icon"&gt;DaveSquared.SampleProject.Web&lt;/li&gt;
  &lt;li class="file-icon"&gt;DaveSquared.SampleProject.sln&lt;/li&gt;
   &lt;/ul&gt;
    &lt;li class="folder-icon"&gt;tools&lt;/li&gt;
   &lt;ul&gt;
  &lt;li class="folder-icon"&gt;NUnit&lt;/li&gt;
   &lt;/ul&gt;
  &lt;/ul&gt;
&lt;/ul&gt;
 
&lt;p&gt;The SLN file contains two projects, &lt;code&gt;DaveSquared.SampleProject.Tests&lt;/code&gt; and &lt;code&gt;.Web&lt;/code&gt;. The &lt;code&gt;.Tests&lt;/code&gt; project references the &lt;code&gt;.Web&lt;/code&gt; project, as well as the NUnit framework buried somewhere in the &lt;code&gt;tools/NUnit&lt;/code&gt; directory. Both projects where configured to build to the &lt;code&gt;build/output&lt;/code&gt; directory (so &lt;code&gt;.Tests&lt;/code&gt; will build to &lt;code&gt;build/output/DaveSquared.SampleProject.Tests&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;We can now setup our &lt;code&gt;rakefile.rb&lt;/code&gt;, which I've plonked into the &lt;code&gt;build&lt;/code&gt; directory. We'll run the build from this directory, so we can specify all our paths relative to this build file.&lt;/p&gt;

&lt;h2&gt;Basic build and test run&lt;/h2&gt;

&lt;p&gt;After reading Dave Laribee's post on &lt;a href="http://codebetter.com/blogs/david_laribee/archive/2008/08/25/omg-rake.aspx"&gt;OMG Rake!&lt;/a&gt;, and Mark Guzman's excellent post on &lt;a href="http://hasno.info/2008/1/6/building-net-projects-with-rake"&gt;Building .NET projects with rake&lt;/a&gt;, I then proceeded to ruin all their good work by patching bits and pieces of their posts together and got this:&lt;/p&gt;

&lt;pre&gt;
require 'rake/clean'

DOT_NET_PATH = &amp;quot;#{ENV[&amp;quot;SystemRoot&amp;quot;]}\\Microsoft.NET\\Framework\\v3.5&amp;quot;
NUNIT_EXE = &amp;quot;../tools/Nunit/bin/nunit-console.exe&amp;quot;
SOURCE_PATH = &amp;quot;../src&amp;quot;
OUTPUT_PATH = &amp;quot;output&amp;quot;
CONFIG = &amp;quot;Debug&amp;quot;
 
&lt;b&gt;CLEAN.include(OUTPUT_PATH)&lt;/b&gt;

&lt;b&gt;task :default =&amp;gt; [&amp;quot;clean&amp;quot;, &amp;quot;build:all&amp;quot;]&lt;/b&gt;
 
namespace :build do
  
  &lt;b&gt;task :all =&amp;gt; [:compile, :test]&lt;/b&gt;
      
  desc &amp;quot;Build solutions using MSBuild&amp;quot;
  &lt;b&gt;task :compile do&lt;/b&gt;
    solutions = FileList[&amp;quot;#{SOURCE_PATH}/**/*.sln&amp;quot;]
    solutions.each do |solution|
      sh &amp;quot;#{DOT_NET_PATH}/msbuild.exe /p:Configuration=#{CONFIG} #{solution}&amp;quot;
    end
  end
   
  desc &amp;quot;Runs tests with NUnit&amp;quot;
  &lt;b&gt;task :test =&amp;gt; [:compile] do&lt;/b&gt;
    tests = FileList[&amp;quot;#{OUTPUT_PATH}/**/*.Tests.dll&amp;quot;].exclude(/obj\//)
    sh &amp;quot;#{NUNIT_EXE} #{tests} /nologo /xml=#{OUTPUT_PATH}/TestResults.xml&amp;quot;
  end
  
end
&lt;/pre&gt;

&lt;p&gt;Now the good thing about this is that I don't think you need to know much (any? I know virtually none) Ruby to understand what is going on here, or even to make basic modifications to the tasks (although it might be a struggle if you haven't used build tools like &lt;code&gt;make&lt;/code&gt; or &lt;/code&gt;nant&lt;/code&gt; before). But you can bring the full power of the language to bear when you need it. Let's have a quick step through the main parts of the file.&lt;/p&gt;

&lt;p&gt;The first line imports &lt;code&gt;rake/clean&lt;/code&gt;, which lets us use &lt;code&gt;CLEAN.include(OUTPUT_PATH)&lt;/code&gt; to tidy up for us. We've then got loads of constants to specify various paths: the location of .NET tools like &lt;code&gt;msbuild&lt;/code&gt;, and the relative paths to NUnit, our source, and our output. Our &lt;code&gt;:default&lt;/code&gt; task is set to run &lt;code&gt;clean&lt;/code&gt;, then &lt;code&gt;build:all&lt;/code&gt; (the =&amp;gt; syntax translates to &lt;i&gt;depends on&lt;/i&gt; in &lt;code&gt;make&lt;/code&gt; terms, so to run the default task rake will make sure its dependencies are run).&lt;/p&gt;

&lt;p&gt;If we drop into the &lt;code&gt;:build&lt;/code&gt; namespace, we have &lt;code&gt;:all&lt;/code&gt;, &lt;code&gt;:compile&lt;/code&gt; and &lt;code&gt;:test&lt;/code&gt; tasks defined. To &lt;code&gt;:compile&lt;/code&gt;, we use the wonderful &lt;code&gt;FileList&lt;/code&gt; class built into rake to get all &lt;code&gt;*.sln&lt;/code&gt; files in our source directory, then shell out to &lt;code&gt;msbuild&lt;/code&gt; to take care of the hardwork of compiling everything. The &lt;code&gt;:test&lt;/code&gt; task relies on convention, by finding all &lt;code&gt;*.Tests.dll&lt;/code&gt; files and running them through NUnit. We also make sure that &lt;code&gt;:test&lt;/code&gt; won't run until &lt;code&gt;:compile&lt;/code&gt; has run by setting &lt;code&gt;:compile&lt;/code&gt; as a dependency.&lt;/p&gt;

&lt;p&gt;Finally, our &lt;code&gt;:all&lt;/code&gt; task compiles and tests the build.&lt;/p&gt;

&lt;h2&gt;Running our rake build&lt;/h2&gt;

&lt;p&gt;By dropping into our build directory from the command line, just typing &lt;code&gt;rake&lt;/code&gt; will pickup our &lt;code&gt;rakefile.rb&lt;/code&gt; and execute our default task, which will clean, compile and test our build. We can also run a task at a time, say &lt;code&gt;rake clean&lt;/code&gt;, or &lt;code&gt;rake build:test&lt;/code&gt; (the &lt;code&gt;:test&lt;/code&gt; task is prefixed by &lt;code&gt;build&lt;/code&gt; because of its namespace).&lt;/p&gt;

&lt;p&gt;There's obviously tonnes we could do to make this nicer (like using &lt;a href="http://hasno.info/2008/1/6/building-net-projects-with-rake"&gt;Mark's .NET tasks&lt;/a&gt;, and/or removing the hard-coded Debug configuration), but hopefully this gives people a quick way to start getting into rake and ruby for building .NET projects.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-5212532788847946123?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yOwhTnaqRZA:xDSwvQg--uI:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=yOwhTnaqRZA:xDSwvQg--uI:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yOwhTnaqRZA:xDSwvQg--uI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yOwhTnaqRZA:xDSwvQg--uI:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=yOwhTnaqRZA:xDSwvQg--uI:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yOwhTnaqRZA:xDSwvQg--uI:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/yOwhTnaqRZA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/5212532788847946123/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=5212532788847946123" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/5212532788847946123?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/5212532788847946123?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/04/basic-net-builds-using-rake.html" title="Basic .NET builds using Rake" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">4</thr:total></entry><entry gd:etag="W/&quot;C0QARng6eyp7ImA9WxVbFUQ.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-1016764244850093485</id><published>2009-04-02T00:09:00.000+11:00</published><updated>2009-04-02T00:09:07.613+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-02T00:09:07.613+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><title>Explicitly test what you are trying to test</title><content type="html">&lt;p&gt;Had a problem today that initially took me by surprise. The problem was that this test passed:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void EmptyBlocksShouldBeEqual() {
    var first = new Block();
    var second = new Block();
    Assert.That(first, Is.EqualTo(second));
}
&lt;/pre&gt;

&lt;p&gt;Why was this a problem? Because &lt;code&gt;Block&lt;/code&gt; is a reference type and I had not overridden &lt;code&gt;Equals(Object o)&lt;/code&gt;, so we should fall back to the default &lt;code&gt;Object.Equals(Object o)&lt;/code&gt; method which compares object references. The references are clearly different, so this test should fail.&lt;/p&gt;

&lt;p&gt;To figure out why this test passes we need two pieces of information. First we need to know how &lt;code&gt;Block&lt;/code&gt; is defined:&lt;/p&gt;

&lt;pre&gt;
public class Block : IEnumerable&amp;lt;FrameParameters&amp;gt;  { /* ... snip ... */ }
&lt;/pre&gt;

&lt;p&gt;Second, we need to know that the NUnit &lt;code&gt;EqualConstraint&lt;/code&gt; implementation has specific handling for &lt;code&gt;IEnumerable&lt;/code&gt; classes. So when I called &lt;code&gt;Assert.That(first, Is.EqualTo(second));&lt;/code&gt;, this was just comparing the values returned via enumerating both &lt;code&gt;Block&lt;/code&gt; instances. This really wasn't what I wanted -- I was trying to test the &lt;code&gt;Equals()&lt;/code&gt; implementation. Here's the corrected test:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void EmptyBlocksShouldBeEqual() {
    var first = new Block();
    var second = new Block();
    Assert.That(&lt;b&gt;first.Equals(second)&lt;/b&gt;);
}
&lt;/pre&gt;

&lt;p&gt;The moral of the story: make sure you explicitly test what you are trying to test. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-1016764244850093485?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=6UwekDNZmak:21AcLXra4j0:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=6UwekDNZmak:21AcLXra4j0:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=6UwekDNZmak:21AcLXra4j0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=6UwekDNZmak:21AcLXra4j0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=6UwekDNZmak:21AcLXra4j0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=6UwekDNZmak:21AcLXra4j0:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/6UwekDNZmak" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/1016764244850093485/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=1016764244850093485" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/1016764244850093485?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/1016764244850093485?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/04/explicitly-test-what-you-are-trying-to.html" title="Explicitly test what you are trying to test" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;DE8DR3Y7fCp7ImA9WxVUFEs.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-8710334505962540695</id><published>2009-03-19T23:30:00.002+11:00</published><updated>2009-03-19T23:47:56.804+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-19T23:47:56.804+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="linq" /><title>Too LINQy?</title><content type="html">&lt;p&gt;This post contains a tale of two methods. Well, more precisely, a tale of one method implemented in two different ways -- once using LINQ-based functional-fu, and once using old school procedural code.&lt;/p&gt;

&lt;p&gt;Recently I was pairing on a task that required us to keep a running average of multiple sets of samples that came through our app. Unfortunately it was more than likely that some sets of samples would be different lengths (depending on exactly when sampling stopped). In these situations where we were missing samples the requirements were to leave the averages for the missing samples unchanged. When we had extra samples, we should use them as the new average at that position. Here's some tests that hopefully show what we were trying to do:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void ShouldAverageFirstTwoLotsOfSamples() {
    var firstSamples = new float[] { 1, 2, 3 };
    var secondSamples = new float[] { 3, 4, 5 };
    var expectedAverages = new float[] {2, 3, 4};
    _averager.AddSamples(firstSamples);
    _averager.AddSamples(secondSamples);
    Assert.That(_averager.GetAverages(), Is.EqualTo(expectedAverages));
}  

[Test]
public void ShouldAddExtraSamplesToAverages() {
    var firstSamples = new float[] { 1, 2, 3 };
    var secondSamples = new float[] { 3, 4, 5, 2 };
    var expectedAverages = new float[] { 2, 3, 4, 2 };    
    /* ... snip ... */
}

[Test]
public void ShouldHandleShorterNumberOfSamples() {
    var firstSamples = new float[] { 1, 2, 3 };
    var secondSamples = new float[] { 3, 4 };
    var expectedAverages = new float[] { 2, 3, 3};
    /* ... snip ... */
}
&lt;/pre&gt;

&lt;h2&gt;A LINQ implementation&lt;/h2&gt;
&lt;p&gt;After a brief flurry of &lt;code&gt;for&lt;/code&gt; looping, we decided to muck around with LINQ to filter and transform the sets of data in a pseudo-functional kind of way.&lt;/p&gt;

&lt;pre&gt;
public class AverageCalculator {
    private float[] _averages = new float[0];
    private uint _numberOfAverages;    

    public void AddSamples(float[] samples) {
        _numberOfAverages++;
        var numberOfNewSamples = samples.Length;
        var numberOfSamplesInLastAverage = _averages.Length;
        var leftOverSamples = samples.Skip(numberOfSamplesInLastAverage);
        var leftOverAverages = _averages.Skip(numberOfNewSamples);

        &lt;b&gt;_averages = _averages
            .Take(numberOfNewSamples)
            .Select(
                (average, sampleIndex) =&amp;gt; CalculateNewAverage(average, samples[sampleIndex], _numberOfAverages)
            )
            .Concat(leftOverAverages)
            .Concat(leftOverSamples)
            .ToArray();&lt;/b&gt;
    }

    private float CalculateNewAverage(float oldAverage, float newSample, uint totalSamples) {
        return oldAverage + (newSample - oldAverage) / totalSamples;
    }

    public float[] GetAverages() {
        return _averages;
    }
}
&lt;/pre&gt;

&lt;p&gt;Stepping through the logic, we take a maximum of &lt;code&gt;numberOfNewSamples&lt;/code&gt; from the running &lt;code&gt;_averages&lt;/code&gt;, then calculate the new averages based on each new sample. To handle the possibility of mismatched array sizes, we concatenate any left over items from each array. In reality, one of these arrays of left overs will be empty (depending on which array is larger).&lt;/p&gt;

&lt;p&gt;My first thought once the tests went green was "wow that's evil!", but compared with the procedural approach we started with, this one really began to grow on me. It was surprisingly easy to write, but I was concerned about its readability (initially we had the local variables in &lt;code&gt;AddSamples(...)&lt;/code&gt; inlined, but we extracted them out to try and make it more readable). We decided to test out the procedural equivalent and see if that was any clearer.&lt;/p&gt;

&lt;h2&gt;A procedural implementation&lt;/h2&gt;
&lt;pre&gt;
public void AddSamples(float[] samples) {
    _numberOfAverages++;

    var largestArray = (samples.Length &amp;gt;= _averages.Length) ? samples : _averages;
    var smallestArray = (samples.Length &amp;gt;= _averages.Length) ? _averages : samples;

    var newAverages = new float[largestArray.Length];
    for (int i = 0; i &amp;lt; newAverages.Length; i++) {
        newAverages[i] = (i &amp;lt; smallestArray.Length) 
                            ? CalculateNewAverage(_averages[i], samples[i], _numberOfAverages) 
                            : largestArray[i];
    }

    _averages = newAverages;
}
&lt;/pre&gt;

&lt;p&gt;The logic used here is to find which array is largest, and to create a new array of that size. We loop through every possible index, calculating the average until all of the smallest array is used, then append the left overs from the largest array. This seems quite neat to me, although I should mention that this is a refactored, sanitised version (as is the LINQ version). The initial implementation was more verbose and the logic less clear, and it somehow managed to take longer to get it to a state where the tests all passed.&lt;/p&gt;

&lt;h2&gt;Who's right?&lt;/h2&gt;

&lt;p&gt;Which approach do you like best? It probably comes down to how much &lt;a href="http://en.wikipedia.org/wiki/Imperative_programming"&gt;imperative&lt;/a&gt; vs. &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional&lt;/a&gt; programming you've done. (Or you hate both versions of the method, in which case please leave a comment with the correct approach. :)). Imperative programming concentrates on telling the computer &lt;i&gt;how&lt;/i&gt; to do something, while functional is more about telling the computer &lt;i&gt;what&lt;/i&gt; to do. For example, our LINQ version starts with some data and specifies what transformations we want to make to it. Our second version of the code focuses more on the mechanics -- create an array, loop, check the bounds etc.&lt;/p&gt;

&lt;p&gt;The second version's focus on implementation makes it fairly easy to mentally trace through how it works, but how clear is the intention behind the implementation? The LINQ version probably takes a bit more effort to understand how it works (especially as the first exposure most people have to programming tends to be to imperative-style control structures like &lt;code&gt;IF&lt;/code&gt;, &lt;code&gt;FOR&lt;/code&gt;, &lt;code&gt;WHILE&lt;/code&gt; and even &lt;CODE&gt;GOTO&lt;/CODE&gt;), but what it is doing might be a little clearer.&lt;/p&gt;

&lt;p&gt;Overall, I kind of prefer the LINQ version for its faint hint of functional elegance, but on the other hand the procedural version is just so darn familiar and comfortable to read for a C#/Java/C person like me. I'd love to hear any thoughts you have on these approaches, and how you are handling the encroachment of functional concepts into our formerly purely-procedural C# language.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-8710334505962540695?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=GKPsHccQgks:5k9JpSxE5bs:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=GKPsHccQgks:5k9JpSxE5bs:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=GKPsHccQgks:5k9JpSxE5bs:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=GKPsHccQgks:5k9JpSxE5bs:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=GKPsHccQgks:5k9JpSxE5bs:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=GKPsHccQgks:5k9JpSxE5bs:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/GKPsHccQgks" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/8710334505962540695/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8710334505962540695" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8710334505962540695?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8710334505962540695?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/03/too-linqy.html" title="Too LINQy?" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">6</thr:total></entry><entry gd:etag="W/&quot;CEINSXk8eCp7ImA9WxVUEUU.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-7750891187469413466</id><published>2009-03-15T22:15:00.001+11:00</published><updated>2009-03-16T16:49:58.770+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-16T16:49:58.770+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="*Garden Race" /><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="worstpostever" /><category scheme="http://www.blogger.com/atom/ns#" term="tdd" /><title>Garden Race Pt 3: It's GUI time!</title><content type="html">&lt;p&gt;&lt;i&gt;This post is &lt;a href="http://davesquared.blogspot.com/2008/05/garden-race-series.html"&gt;part of a series&lt;/a&gt; exploring the (very) basics of iterative development using the example of a simple &lt;a href="http://en.wikipedia.org/wiki/Snakes_and_ladders"&gt;Snakes and Ladders&lt;/a&gt;-like game. Links to each post in the series will be added to the &lt;a href="http://davesquared.blogspot.com/2008/05/garden-race-series.html"&gt;index page&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;

&lt;p&gt;After having a think about &lt;a href="http://davesquared.blogspot.com/2008/05/top-down-vs-bottom-up-design.html"&gt;top-down and bottom-up design&lt;/a&gt;, I concluded that delivering complete vertical slices was more important than whether you started at the top or bottom of the slice. As most of the work in previous iterations has been closer to the bottom of our design, it now seems a good time to start writing some tests around the GUI. This work will form the basis of this iteration.&lt;/p&gt;

&lt;div class="note"&gt;&lt;b&gt;&lt;i&gt;Confession&lt;/i&gt;&lt;/b&gt;: I had about 3 attempts at this installment of the series over the last year or so, each time having something crop up that stopped me working on it. Some of this post may be biased by previous attempts, although with my poor memory there shouldn't be too much chance of that. :) &lt;/div&gt;

&lt;h2&gt;Project status and work for iteration 3&lt;/h2&gt;

&lt;p&gt;Based on the previous two iterations, all we have left from the original list is the "feature squares" (the snakes and ladders style squares):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strike&gt;A player can roll the die, and then move that many spaces along the board.&lt;/strike&gt;&lt;/li&gt;
&lt;li&gt;A player that ends his or her turn on a "feature square" (a square containing a creature or obstacle), will be moved to the square connected with that feature.&lt;/li&gt;
&lt;li&gt;&lt;strike&gt;There can be 1-4 players, and each player has their turn in sequence.&lt;/strike&gt;&lt;/li&gt;
&lt;li&gt;&lt;strike&gt;A player that reaches the final square wins the game.&lt;/strike&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We'll leave the pending story on hold for now so we can get to the GUI bits. One thing to notice is that none of these stories, strictly speaking, demand a GUI. So let's add one, in consultation with our customers (i.e. firstborn and I):&lt;/p&gt;
&lt;ol start="5"&gt;
&lt;li&gt;Each player's position will be displayed on an 8 x 8 grid of squares.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This should give us enough to get rid of the command line demo code and give the customer something closer to a usable product. It will probably be enough to fill the whole iteration as well, as we may have to revisit some of the original stories and make sure we have exposed them all through our GUI (story 1 for example). I've also managed to miss a fairly major part of story 3 -- there is currently no way to choose how many players there are in the game.&lt;/p&gt;

&lt;p&gt;I think this indicates a problem with the approach so far. Imagine having to revisit every story after implementing 50 or so due to a change to the front end. One big thing we are missing that could help us avoid this are acceptance tests. If we had those, the relevant ones would fail and we could test drive out our way back to green. It could also be an indication that we have too much logic in the untested demo app. We were aware of this when we wrote the demo app though, and never intended to keep it around long enough for it to become a problem, so manually rechecking our 3 finished stories shouldn't be too big a deal.&lt;/p&gt;

&lt;p&gt;Let's start off using WPF for this, as it's shiny and new (well, compared with standard WinForms), and comes standard with our current .NET 3.5 platform. We'd obviously want to do some more research if doing this for real. I've done practically nothing with WPF to date, so I'm looking forward to publicly humiliating myself throughout the remainder of this post. (Why don't my regular readers look surprised? ;))&lt;/p&gt;

&lt;h2&gt;Where to start?&lt;/h2&gt;
&lt;p&gt;I'd like to replace our untested demo code with tested, production code that we can use as a foundation for a GUI. We need to make sure the functionality of our original stories are exposed via the GUI, rather than the demo app. The two things that jump out at me is that we need a way for a player to roll a die, and we also need some way to indicate the end of the game. The actual rules of the game are hopefully captured in our &lt;code&gt;Game&lt;/code&gt; class, so with a bit of luck we'll only need to verify our UI's interaction with that class. Then to complete our story we'll need to make sure each player's position is displayed on the game board.&lt;/p&gt;

&lt;p&gt;I'd love to avoid jumping straight to an MVP-style pattern here, in favour of starting from first principles and refactoring to patterns like that when it becomes painfully obvious we need to. However I have absolutely no idea how to do that test-first, so let's try the standard route of creating a &lt;code&gt;GamePresenter&lt;/code&gt; that will mediate between our &lt;code&gt;Game&lt;/code&gt; model and our UI. We'll start off with the basics of rolling the die and move on from there.&lt;/p&gt;

&lt;h2&gt;Rollin', rollin', rollin'&lt;/h2&gt;

&lt;p&gt;What should happen when a player interacts with the view to roll the die? Well for starters our model class, &lt;code&gt;Game&lt;/code&gt;, should probably be updated to reflect the fact the player is having their turn. We don't have an actual GUI button to press, but we know that we can fire off an event when a GUI button is clicked. If we add this event to a view interface, and our real GUI implements that interface, then we'll be able to write automated tests for large number of interactions with our GUI via its interface. Our GUI implementation itself should be fairly basic and concentrate on rendering and widgets rather than application logic (see the &lt;a href="http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf"&gt;Humble Dialog Box&lt;/a&gt; [PDF]).&lt;/p&gt;

&lt;pre&gt;
public class GamePresenterSpec {
    [Fact]
    public void Game_should_update_when_roll_die_is_clicked() {
        var fakeGameView = MockRepository.GenerateStub&amp;lt;IGameView&amp;gt;();
        var fakeGame = MockRepository.GenerateMock&amp;lt;IGame&amp;gt;();
        var gamePresenter = new GamePresenter(fakeGameView, fakeGame);

        fakeGameView.Raise(view =&amp;gt; view.RollClicked += null, this, EventArgs.Empty);
        fakeGame.AssertWasCalled(game =&amp;gt; game.Roll(Arg&amp;lt;int&amp;gt;.Is.Anything));
    }
}
&lt;/pre&gt;

&lt;p&gt;This test isn't really saying much, just that &lt;code&gt;game.Roll(...)&lt;/code&gt; should be called with any argument, which is how a player currently has their turn in our model. We need to extract an &lt;code&gt;IGame&lt;/code&gt; interface for this, and also create an &lt;code&gt;IGameView&lt;/code&gt; and a &lt;code&gt;GamePresenter&lt;/code&gt;.&lt;/p&gt;
    
&lt;pre&gt; 
public class GamePresenter {
    public GamePresenter(IGameView view, IGame game){}
}

public interface IGameView {
    event EventHandler RollClicked;
}

public interface IGame {
    void Roll(int dieValue);
}
&lt;/pre&gt;

&lt;p&gt;Our test compiles, but fails. We'll fix that now.&lt;/p&gt;

&lt;pre&gt;
public class GamePresenter {
    private readonly IGame _game;
    public GamePresenter(IGameView view, IGame game) {
        _game = game;
        view.RollClicked += view_RollClicked;
    }
    void view_RollClicked(object sender, EventArgs e) {
        _game.Roll(1);
    }
}
&lt;/pre&gt;  

&lt;p&gt;Our test now passes, and as I can't see much refactoring to do, let's try the next test. Looking at what we have so far, the most obvious deficiency to me seems to be that we are just rolling 1 in the game. We really need a die roll here (1d6 :)), but that would involve random numbers running around our tests causing havoc. So let's fake a &lt;code&gt;DieRoller&lt;/code&gt; that we can use to get known values during tests, and random values during the actual game.&lt;/p&gt;

&lt;pre&gt;
 public class GamePresenterSpec {
    private IGameView fakeGameView;
    private IGame fakeGame;
    private IDieRoller fakeDieRoller;

    private GamePresenter CreateGamePresenterAndDependencies() {
        fakeGameView = MockRepository.GenerateStub&amp;lt;IGameView&amp;gt;();
        fakeGame = MockRepository.GenerateMock&amp;lt;IGame&amp;gt;();
        fakeDieRoller = MockRepository.GenerateStub&amp;lt;IDieRoller&amp;gt;();
        return new GamePresenter(fakeGameView, fakeGame, fakeDieRoller);            
    }
    /* ... snip ... */
    [Fact]
    public void Game_should_roll_value_from_die_when_roll_die_is_clicked() {
        CreateGamePresenterAndDependencies();
        int dieFace = 3;
        fakeDieRoller.Stub(die =&amp;gt; die.Roll()).Return(dieFace);

        RaiseRollClickedEventOnView();
        fakeGame.AssertWasCalled(game =&amp;gt; game.Roll(dieFace));
    }

    private void RaiseRollClickedEventOnView() {
        fakeGameView.Raise(view =&amp;gt; view.RollClicked += null, this, EventArgs.Empty);
    }
}
&lt;/pre&gt;

&lt;p&gt;The new test stubs out a known value for &lt;code&gt;IDieRoller.Roll()&lt;/code&gt;, then makes sure that will get passed to our &lt;code&gt;Game&lt;/code&gt;. I've also shown that we've extracted the common fixture setup code into a &lt;code&gt;CreateGamePresenterAndDependencies()&lt;/code&gt; method, although we'd normally do this refactoring after all the tests get to green (unfortunately this stuff is surprisingly difficult to get into blog-form, so please excuse me taking some licence with presentation).&lt;/p&gt;

&lt;pre&gt;
public class GamePresenter {
    private readonly IGame game;
    private readonly IDieRoller roller;

    public GamePresenter(IGameView view, IGame game, &lt;b&gt;IDieRoller roller&lt;/b&gt;) {
        this.game = game;
        this.roller = roller;
        view.RollClicked += view_RollClicked;
     }

    void view_RollClicked(object sender, EventArgs e) {
        &lt;b&gt;game.Roll(roller.Roll());&lt;/b&gt;
    }
}

public interface IDieRoller {
    int Roll();
}
&lt;/pre&gt;

&lt;p&gt;And we're back at green. What else can we look at? Well we should probably display the result of the roll to the player. Like our &lt;code&gt;view.RollClicked&lt;/code&gt; event, we'll just make our view interface have a method for setting the result of a die roll (say, &lt;code&gt;ShowRollResult(dieFace)&lt;/code&gt;), and we'll let our actual GUI implementation worry about translating this message to the display.&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void View_should_show_result_of_roll() {
    CreateGamePresenterAndDependencies();
    int dieFace = 2;
    fakeDieRoller.Stub(die =&amp;gt; die.Roll()).Return(dieFace);
    RaiseRollClickedEventOnView();
    fakeGameView.AssertWasCalled(view =&amp;gt; view.ShowRollResult(dieFace));
}
&lt;/pre&gt;

&lt;pre&gt;
public class GamePresenter {
    private readonly IGameView view;
    /* ... snip ... */
    void view_RollClicked(object sender, EventArgs e) {
       &lt;b&gt;var dieValue = roller.Roll();&lt;/b&gt;
       game.Roll(dieValue);
       &lt;b&gt;view.ShowRollResult(dieValue);&lt;/b&gt;
    }
}
&lt;/pre&gt;

&lt;h2&gt;Whose turn is it anyway?&lt;/h2&gt;
&lt;p&gt;Tests pass, and can't see any refactoring to do. It is probably important to show whose turn it is, so let's try that now. First up, we need to show the current player when the game is first started.&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void View_should_show_current_player_when_game_is_created() {
    CreateGamePresenterAndDependencies();
    var currentPlayer = 1;
    fakeGame.Stub(game =&amp;gt; game.CurrentPlayer).Return(currentPlayer);
    fakeGameView.AssertWasCalled(view =&amp;gt; view.SetCurrentPlayer(currentPlayer));

}
&lt;/pre&gt;

&lt;p&gt;Oops, this won't work. We are using &lt;code&gt;CreateGamePresenterAndDependencies()&lt;/code&gt; to create everything in one step, but then we go on to stub out the &lt;code&gt;game.CurrentPlayer&lt;/code&gt; call. Let's separate the dependency creation from the creation of the subject under test.&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void View_should_show_current_player_when_game_is_created() {
    &lt;b&gt;CreateGameDependencies();&lt;/b&gt;
    var currentPlayer = 1;
    fakeGame.Stub(game =&amp;gt; game.CurrentPlayer).Return(currentPlayer);
    &lt;b&gt;new GamePresenter(fakeGameView, fakeGame, fakeDieRoller);&lt;/b&gt;
    fakeGameView.AssertWasCalled(view =&amp;gt; view.SetCurrentPlayer(currentPlayer));
}
&lt;/pre&gt;

&lt;div class="note"&gt;&lt;b&gt;Note:&lt;/b&gt; this kind of mucking around with the fixture is a drawback of using a fixture-per-class style of test organisation. This seems to be how most people start TDD (myself included), but I think using a fixture-per-scenario approach (more of a BDD style) is easier to use and probably to learn from. I'm using a more BDD-like approach for my real code now, and am finding it generally makes TDD much easier. I still haven't got it right yet though, so both for that reason and for consistency I'll stick with fixture-per-class for this post.&lt;/div&gt;

&lt;p&gt;To get this passing we'll need to pull up &lt;code&gt;Game.CurrentPlayer&lt;/code&gt; to the &lt;code&gt;IGame&lt;/code&gt; interface, then update the &lt;code&gt;GamePresenter&lt;/code&gt; constructor to pass this information to the view.&lt;/p&gt;

&lt;pre&gt;
public GamePresenter(IGameView view, IGame game, IDieRoller roller) {
    this.view = view;
    this.game = game;
    this.roller = roller;
    view.RollClicked += view_RollClicked;
    &lt;b&gt;view.SetCurrentPlayer(game.CurrentPlayer);&lt;/b&gt;
}
&lt;/pre&gt;

&lt;p&gt;That handles the start of the game, but we also need to change whose turn it is after each roll.&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void View_should_show_current_player_after_a_roll() {
    CreateGamePresenterAndDependencies();
    var player = 2;
    fakeGame.Stub(game =&amp;gt; game.CurrentPlayer).Return(player);
    RaiseRollClickedEventOnView();
    fakeGameView.AssertWasCalled(view =&amp;gt; view.SetCurrentPlayer(player));
}

/* In GamePresenter: */
void view_RollClicked(object sender, EventArgs e) {
    var dieValue = roller.Roll();
    game.Roll(dieValue);
    view.ShowRollResult(dieValue);
    &lt;b&gt;view.SetCurrentPlayer(game.CurrentPlayer);&lt;/b&gt;
}
&lt;/pre&gt;

&lt;div class="note"&gt;&lt;b&gt;Ugh:&lt;/b&gt; Looking back through my notes while I'm typing this up, I have something to the effect of &amp;quot;Seems ugly. Using WPF, shouldn't I be binding to the ViewModel/PresentationModel?&amp;quot;. This is fairly important -- I'm going to blatantly end up misusing WPF in this case because I'm not taking advantage of any of the nice databinding features it has. Let's press on though, if for no reason other than to point at the author and laugh at his incompetence. Maybe we can salvage what we have later on.&lt;/div&gt;

&lt;h2&gt;Where am I?&lt;/h2&gt;

&lt;p&gt;Ostensibly the story we are working on is to display each player's position on the grid. It should not be too hard to update each player's position after they take their turn. Because I haven't done enough of a spike to see how our view should work, let's just assume we have a &lt;code&gt;MovePlayerMarker(...)&lt;/code&gt; method on the view that will handle any animation or display stuff we need.&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Should_update_players_position_after_roll() {
    CreateGamePresenterAndDependencies();
    var player = 1;
    var newSquare = 10;
    var oldSquare = 5;
    fakeGame.Stub(game =&amp;gt; game.CurrentPlayer).Return(player);
    fakeGame.Stub(game =&amp;gt; game.GetSquareFor(player)).Return(oldSquare);
    fakeGame.Stub(game =&amp;gt; game.GetSquareFor(player)).Return(newSquare);
    RaiseRollClickedEventOnView();

    fakeGameView.AssertWasCalled(view =&amp;gt; view.MovePlayerMarker(player, oldSquare, newSquare));
}

/* In GamePresenter: */
void view_RollClicked(object sender, EventArgs e) {
    var dieValue = roller.Roll();
    &lt;b&gt;var player = game.CurrentPlayer;&lt;/b&gt;
    &lt;b&gt;var startingSquare = game.GetSquareFor(player);&lt;/b&gt;
    game.Roll(dieValue);
    view.ShowRollResult(dieValue);
    view.SetCurrentPlayer(player);
    &lt;b&gt;view.MovePlayerMarker(player, startingSquare, game.GetSquareFor(player));&lt;/b&gt;
}
&lt;/pre&gt;

&lt;p&gt;We are really starting to run into some of the limitations of our &lt;code&gt;Game&lt;/code&gt; class now. As soon as a player rolls the die in the game, the positions and current player changed, so we need to save this information prior to calling &lt;code&gt;game.Roll(...)&lt;/code&gt;. This may indicate we may have an overly intimate implementation. We need to know all kinds of stuff about the &lt;code&gt;Game&lt;/code&gt; implementation to use it, which is making our  &lt;code&gt;view_RollClicked(...)&lt;/code&gt; code fairly ugly as it steps through the procedure of running the game. Maybe we should instead expose a list of player positions that we could bind to instead?&lt;/p&gt;

&lt;p&gt;It looks like we are due for some refactoring, but I'm not really sure how to proceed with that. Instead of letting that hold us up as we worry about all the potential solutions we could pick, let's put that off and whack up a quick view implementation and see if that helps at all.&lt;/p&gt;

&lt;h2&gt;This time I'm playing to win!&lt;/h2&gt;

&lt;p&gt;Before we make that final step to the GUI implementation we still need to handle one more  case from our original console app -- winning the game. Here's two tests and an implementation that passes them both (although written one at a time, of course!).&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Should_show_winner_when_game_is_finished() {
    CreateGamePresenterAndDependencies();
    int player = 3;
    fakeGame.Stub(game =&amp;gt; game.CurrentPlayer).Return(player);
    fakeGame.Stub(game =&amp;gt; game.IsFinished).Return(true);
    RaiseRollClickedEventOnView();
    fakeGameView.AssertWasCalled(view =&amp;gt; view.ShowWinner(player));
}

[Fact]
public void Should_disable_die_roll_when_game_is_finished() {
    CreateGamePresenterAndDependencies();
    fakeGame.Stub(game =&amp;gt; game.IsFinished).Return(true);
    RaiseRollClickedEventOnView();
    fakeGameView.AssertWasCalled(view =&amp;gt; view.DisableDieRolls());
}

/* In GamePresenter: */
void view_RollClicked(object sender, EventArgs e) {
    var dieValue = roller.Roll();
    var player = game.CurrentPlayer;
    var startingSquare = game.GetSquareFor(player);
    game.Roll(dieValue);
    view.ShowRollResult(dieValue);
    view.SetCurrentPlayer(player);
    view.MovePlayerMarker(player, startingSquare, game.GetSquareFor(player));
    &lt;b&gt;if (game.IsFinished) {
        view.DisableDieRolls();
        view.ShowWinner(player);
    }&lt;/b&gt;
}
&lt;/pre&gt;

&lt;h2&gt;The worst, most blatant misuse of WPF in history!!!1!&lt;/h2&gt;

&lt;p&gt;I'm not proud of what you are about to see. In fact, I'm rarely proud of any of the crud I write on this blog, but if my normal stuff is a 2 out of 10, this is about a -30 * 10&lt;sup&gt;12&lt;/sup&gt;. My local check-in comment for this stuff is &amp;quot;Embarrassingly bad GUI using WPF controls&amp;quot;, which is pretty accurate. I'm using WPF controls, but saying this is WPF is like wrapping a 1000 line main method in a class declaration and calling it OO. But I did promise a GUI of sorts, so let's try and get something graphical working.&lt;/p&gt;

&lt;div class="note"&gt;&lt;b&gt;Don't do this!&lt;/b&gt; In case you missed my subtle hints throughout this post, don't repeat what you are about to see. It would be pure evil if it weren't for its lack of competence. Don't bother donning the goggles, they'll do nothing.&lt;/div&gt;

&lt;p&gt;First, I've created a new &lt;code&gt;DaveSquared.GardenRace.Gui&lt;/code&gt; WPF project to house this hideous monstrosity. I've created a new WPF form called &lt;code&gt;GardenRaceView&lt;/code&gt;. Here's the XAML.&lt;/p&gt;

&lt;pre&gt;
&amp;lt;Window x:Class=&amp;quot;DaveSquared.GardenRace.Gui.GardenRaceView&amp;quot;
    xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
    xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;
    Title=&amp;quot;GardenRaceView&amp;quot; Height=&amp;quot;526&amp;quot; Width=&amp;quot;716&amp;quot;&amp;gt;
    &amp;lt;Grid&amp;gt;
        &amp;lt;Grid.ColumnDefinitions&amp;gt;
            &amp;lt;ColumnDefinition Width=&amp;quot;528*&amp;quot; /&amp;gt;
            &amp;lt;ColumnDefinition Width=&amp;quot;166*&amp;quot; /&amp;gt;
        &amp;lt;/Grid.ColumnDefinitions&amp;gt;
        &amp;lt;UniformGrid Name=&amp;quot;gameBoard&amp;quot; Rows=&amp;quot;8&amp;quot; Columns=&amp;quot;8&amp;quot; /&amp;gt;
        &amp;lt;Label Grid.Column=&amp;quot;1&amp;quot; Height=&amp;quot;28&amp;quot; Margin=&amp;quot;0,12,46,0&amp;quot; Name=&amp;quot;currentPlayer&amp;quot; VerticalAlignment=&amp;quot;Top&amp;quot;&amp;gt;currentPlayer&amp;lt;/Label&amp;gt;
        &amp;lt;Button Grid.Column=&amp;quot;1&amp;quot; Height=&amp;quot;23&amp;quot; Margin=&amp;quot;46,46,46,0&amp;quot; Name=&amp;quot;rollDieButton&amp;quot; VerticalAlignment=&amp;quot;Top&amp;quot; Click=&amp;quot;rollDieButton_Click&amp;quot;&amp;gt;Roll&amp;lt;/Button&amp;gt;
        &amp;lt;Label Grid.Column=&amp;quot;1&amp;quot; Height=&amp;quot;28&amp;quot; Margin=&amp;quot;0,86,46,0&amp;quot; Name=&amp;quot;rollResult&amp;quot; VerticalAlignment=&amp;quot;Top&amp;quot;&amp;gt;rollResult&amp;lt;/Label&amp;gt;
        &amp;lt;Ellipse Visibility=&amp;quot;Hidden&amp;quot; Name=&amp;quot;player1Marker&amp;quot; Stroke=&amp;quot;Black&amp;quot; Height=&amp;quot;30&amp;quot; Margin=&amp;quot;5, 0, 0, 0&amp;quot; HorizontalAlignment=&amp;quot;Left&amp;quot; VerticalAlignment=&amp;quot;Top&amp;quot; Fill=&amp;quot;Red&amp;quot; Width=&amp;quot;30&amp;quot; /&amp;gt;
        &amp;lt;Ellipse Visibility=&amp;quot;Hidden&amp;quot; Height=&amp;quot;30&amp;quot; HorizontalAlignment=&amp;quot;Left&amp;quot; Name=&amp;quot;player2Marker&amp;quot; Stroke=&amp;quot;Black&amp;quot; Fill=&amp;quot;Blue&amp;quot; VerticalAlignment=&amp;quot;Top&amp;quot; Width=&amp;quot;30&amp;quot; /&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/pre&gt;

&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://1.bp.blogspot.com/_wEsHWMWy090/SbzbLY1x70I/AAAAAAAAA-A/zkIQsUa0BK4/s1600-h/gardenRaceView-DesignView.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://1.bp.blogspot.com/_wEsHWMWy090/SbzbLY1x70I/AAAAAAAAA-A/zkIQsUa0BK4/s400/gardenRaceView-DesignView.png" style="cursor: move;" alt="The game screen in VS 2008's design view. It looks even worse when running for real!" title="The game screen in VS 2008's design view. It looks even worse when running for real!" /&gt;&lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;This gives us two columns to work with: The left hand column to hold the board, and the right hand column for status and game controls. Let's wire this thing up. Here is the xaml.cs file. This was originally wired up piece by piece, manually testing in between (we don't have automated tests for the view remember).&lt;/p&gt;

&lt;pre&gt;
public partial class GardenRaceView : Window, &lt;b&gt;IGameView&lt;/b&gt; {
    public GardenRaceView() {
        InitializeComponent();
        FillSquares();
        MoveToStartingPositions();
        &lt;b&gt;var gameModel = new Game(64, 2);
        new GamePresenter(this, gameModel, new DieRoller());&lt;/b&gt;
    }

    private void MoveToStartingPositions() {
        MovePlayerMarker(1, 0, 0);
        MovePlayerMarker(2, 0, 0);
    }

    private void FillSquares() {                        
        for (var squareNumber=1; squareNumber &amp;lt;= 64; squareNumber++) {
            var square = new StackPanel();
            var squareLabel = new Label();                
            squareLabel.Content = squareNumber;
            square.Children.Add(squareLabel);
            gameBoard.Children.Add(square);
        }
    }

    public event EventHandler RollClicked;

    private void OnRollClicked() {
        EventHandler rollClickedHandler = RollClicked;
        if (rollClickedHandler != null) &lt;b&gt;rollClickedHandler(this, EventArgs.Empty)&lt;/b&gt;;
    }

    &lt;b&gt;public void ShowRollResult(int dieFace) {
        rollResult.Content = &amp;quot;You rolled a &amp;quot; + dieFace;
    }&lt;/b&gt;

    &lt;b&gt;public void SetCurrentPlayer(int player) {
        currentPlayer.Content = &amp;quot;Player &amp;quot; + player + &amp;quot;'s turn.&amp;quot;;
    }&lt;/b&gt;

    public void &lt;b&gt;MovePlayerMarker(int player, int fromSquare, int toSquare)&lt;/b&gt; {            
        var markerForPlayer = GetMarkerForPlayer(player);
        markerForPlayer.Visibility = Visibility.Visible;
        
        var containerForMarker = (Panel) markerForPlayer.Parent;
        containerForMarker.Children.Remove(markerForPlayer);

        &lt;b&gt;if (toSquare &amp;gt;= gameBoard.Children.Count) toSquare = gameBoard.Children.Count-1;&lt;/b&gt;
        var newSquare = (StackPanel) gameBoard.Children[toSquare];
        newSquare.Children.Add(markerForPlayer);            
    }

    private Shape GetMarkerForPlayer(int player) {
        if (player == 1) { return player1Marker; }
        if (player == 2) { return player2Marker; }
        throw new ArgumentOutOfRangeException();
    }

    &lt;b&gt;public void ShowWinner(int winningPlayer) {
        MessageBox.Show(&amp;quot;Player &amp;quot; + winningPlayer + &amp;quot; wins! Nice work!&amp;quot;);
    }&lt;/b&gt;

    &lt;b&gt;public void DisableDieRolls() {
        rollDieButton.IsEnabled = false;
    }&lt;/b&gt;

    private void rollDieButton_Click(object sender, RoutedEventArgs e) {
        &lt;b&gt;OnRollClicked();&lt;/b&gt;
    }
}
&lt;/pre&gt;

&lt;p&gt;If you haven't been blinded yet, the first thing you'll have seen is that we make our form implement our &lt;code&gt;IGameView&lt;/code&gt;. The majority of these implementations are trivial: &lt;code&gt;ShowRollResult(...)&lt;/code&gt;, &lt;code&gt;SetCurrentPlayer(...)&lt;/code&gt;, &lt;code&gt;ShowWinner(...)&lt;/code&gt;, &lt;code&gt;DisableDieRolls()&lt;/code&gt;, and firing the &lt;code&gt;RollClicked&lt;/code&gt; event. The &lt;code&gt;MovePlayerMarker(...)&lt;/code&gt; is fairly hideous, but it is pretty much all view-specific logic (except the highlighted code that does bound checking on the player's positions).&lt;/p&gt;

&lt;p&gt;There is also some code in the constructor to fill our &lt;code&gt;UniformGrid&lt;/code&gt; (in the incorrect order mind you), and then the code to instantiate our presenter and model code. I don't really see a pressing need for an IoC container here yet, do you? :)&lt;/p&gt;

&lt;p&gt;The only other implementation is the pseudo-random &lt;code&gt;DieRoller&lt;/code&gt; which we pass through to our presenter:&lt;/p&gt;

&lt;pre&gt;
internal class DieRoller : IDieRoller {
    Random random = new Random();
    public int Roll() {
        return random.Next(1, 6);
    }
}
&lt;/pre&gt;

&lt;p&gt;Somewhat surprisingly, this manages to actually work (er, well, somewhat work :)).&lt;/p&gt;

&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://3.bp.blogspot.com/_wEsHWMWy090/SbzbM3NRtJI/AAAAAAAAA-I/wvU4rTfK6X0/s1600-h/gardenRaceView-GameView.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="292" src="http://3.bp.blogspot.com/_wEsHWMWy090/SbzbM3NRtJI/AAAAAAAAA-I/wvU4rTfK6X0/s400/gardenRaceView-GameView.png" style="cursor: move;" width="400" alt="Screen shot from the game." title="Screen shot from the game. While WPF is meant to make beautiful GUIs easier to make than ever before, it's great to see some people still manage to produce complete garbage. On the positive side, I think this one is still better than Lotus Notes. :)" /&gt;&lt;/a&gt;&lt;/div&gt;


&lt;h2&gt;On what poor, pitiful, defenseless customers has my monstrosity been unleashed?&lt;/h2&gt;

&lt;p&gt;So what have we done? Besides unsubscribing from Dave's blog, we also managed to test drive a presenter and unleash a hideous GUI on our unsuspecting customers. We've done a very rough job on this story (my fault, not yours), but we are now displaying players' positions on a grid. The grid is not in the correct order for a snakes and ladders-style game (it is meant to snake around, starting at the bottom of the board and winding its way up to the top), but we can refine this later. We've also replaced our untested, console-only demo app with a tested, hideous bastardisation of WPF.&lt;/p&gt;

&lt;p&gt;We've also found lots of new tasks to do. First, learn WPF. Next, refactor this to have a more useful &lt;code&gt;Game&lt;/code&gt; class, and maybe change the presenter into more of a presentation model approach so we can use some WPF goodness. We also need to do something about our incomplete story about being able to play with 1 - 4 players -- at present we have 2 players hard coded in. And we also should put in some snake and/or ladder-like squares.&lt;/p&gt;

&lt;p&gt;Despite the obvious problems with the current code, I'd like to try and salvage some small glimmer of positivity from this post. We managed to test drive a whole host of GUI-specific functionality, before we even had a forms project. We managed to hook in a thin view on top of that foundation that, despite being ugly, just worked. (Really it did! If I was going to start lieing to you it would have been in an attempt to hide my incompetence during the rest of the post, not for something trivial like this ;)). And last but not least -- um, no, actually they're the only positives I can think of. :)&lt;/p&gt;

&lt;p&gt;I hope you can get some value from this post, even if its just a laugh or two at my expense. :) I'd love to hear your thoughts as to whether what we've got here is salvageable, and if so then how you would start evolving it in the right direction. In the meantime, I'm off to &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc785479.aspx"&gt;read up on WPF&lt;/a&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-7750891187469413466?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yKV7kfaMzOY:0oaoKaQMd_o:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=yKV7kfaMzOY:0oaoKaQMd_o:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yKV7kfaMzOY:0oaoKaQMd_o:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yKV7kfaMzOY:0oaoKaQMd_o:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=yKV7kfaMzOY:0oaoKaQMd_o:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=yKV7kfaMzOY:0oaoKaQMd_o:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/yKV7kfaMzOY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/7750891187469413466/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=7750891187469413466" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/7750891187469413466?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/7750891187469413466?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/03/garden-race-pt-3-its-gui-time.html" title="Garden Race Pt 3: It's GUI time!" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/_wEsHWMWy090/SbzbLY1x70I/AAAAAAAAA-A/zkIQsUa0BK4/s72-c/gardenRaceView-DesignView.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;Dk8GQHsyfyp7ImA9WxVWF04.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-8622745215984115093</id><published>2009-02-27T22:31:00.004+11:00</published><updated>2009-02-27T22:40:21.597+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-02-27T22:40:21.597+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><title>Testing a class for making asynchronous calls</title><content type="html">&lt;p&gt;In my &lt;a href="http://davesquared.blogspot.com/2009/02/testing-legacy-code-when-simple.html"&gt;last post&lt;/a&gt; I looked at doing all kinds of evil things to get some legacy code under test. The code in question launched a new thread to do some work, and I ended up wrapping this asynchronous call in a &lt;code&gt;ThreadDispatcher&lt;/code&gt; class for testing.&lt;/p&gt;

&lt;pre&gt;
public class &lt;b&gt;ThreadDispatcher&lt;/b&gt; {
  public AsyncCall Dispach(Action function) {
    var thread = new Thread(() =&amp;gt; function());
    thread.Start();
    &lt;b&gt;return new AsyncCall(thread);&lt;/b&gt;
  }
}

public class AsyncCall {
  private readonly Thread _thread;
  public AsyncCall(Thread thread) { _thread = thread; }
  public void WaitUntilCallFinishes() { _thread.Join(); }
}
&lt;/pre&gt;

&lt;p&gt;I could then test the dispatcher like this:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void RunsFunctionFromDifferentThread() {
  var dispatcher = new ThreadDispatcher();
  int callingThreadId = Thread.CurrentThread.ManagedThreadId;
  int dispatchedThreadId = callingThreadId;
  var asyncCall = dispatcher.Dispach(() =&amp;gt; dispatchedThreadId = Thread.CurrentThread.ManagedThreadId);
  &lt;b&gt;asyncCall.WaitUntilCallFinishes();&lt;/b&gt;
  Assert.That(dispatchedThreadId, Is.Not.EqualTo(callingThreadId));
}
&lt;/pre&gt;

&lt;p&gt;There's (at least) two problems with this. First, the return value of this function is a complete contrivance for the sake of testability (so our tests can call &lt;code&gt;asyncCall.WaitUntilCallFinishes()&lt;/code&gt; before checking any assertions). This isn't always a bad thing, but in this case we are adding functionality and complexity that the production code does not need (the fact that the return value is always ignored in production code doesn't seem very reassuring). The second problem is that if we want to use the &lt;code&gt;ThreadPool&lt;/code&gt; to run the work in the background then we don't get a reference to a &lt;code&gt;Thread&lt;/code&gt;, and therefore can't wait on it.&lt;/p&gt;

&lt;h2&gt;A neater approach&lt;/h2&gt;

&lt;p&gt;This week I was faced with an actual need to do something like this (the previous implementation was an exercise stemming from a discussion with a mate). I ended up using similar TDD steps to come up with what I feel is a nicer way of testing a fire-and-forget asynchronous call. The implementation itself is trivial, and removes all traces of waiting on/joining threads:&lt;/p&gt;

&lt;pre&gt;
public class AsynchronousDispatcher {
    public void Execute(Action action) {
        ThreadPool.QueueUserWorkItem(state =&amp;gt; action());
    }
}
&lt;/pre&gt;

&lt;p&gt;The fun part is the tests. Seeing as we've removed the concept of waiting from our implementation, this has to be handled from our tests instead. Which is fine, because the tests are the only place we need this functionality.&lt;/p&gt;

&lt;pre&gt;
[Test]
public void ShouldExecuteAction() {
    var wasRun = false;
    DispatchToThreadAndWaitUntilDone(() =&amp;gt; wasRun = true);
    Assert.That(wasRun, &amp;quot;Expected action to execute&amp;quot;);
}

[Test]
public void ShouldExecuteActionOnDifferentThread() {
    var currentThreadID = Thread.CurrentThread.ManagedThreadId;
    var dispatchedThreadID = currentThreadID;

    DispatchToThreadAndWaitUntilDone(() =&amp;gt; dispatchedThreadID = Thread.CurrentThread.ManagedThreadId);
    Assert.That(dispatchedThreadID, Is.Not.EqualTo(currentThreadID));
}

private void DispatchToThreadAndWaitUntilDone(Action action) {
    &lt;b&gt;var resetEvent = new AutoResetEvent(false);&lt;/b&gt;
    var dispatcher = new AsynchronousDispatcher();
    dispatcher.Execute(() =&amp;gt;
                           {
                               action();
                               &lt;b&gt;resetEvent.Set();&lt;/b&gt;
                           });
    &lt;b&gt;resetEvent.WaitOne();&lt;/b&gt;
}
&lt;/pre&gt;

&lt;p&gt;You'll see that the tests themselves are almost identical to the ones from last time, as most of the hard work is done in the &lt;code&gt;DispatchToThreadAndWaitUntilDone(Action action)&lt;/code&gt; function. This uses an &lt;code&gt;AutoResetEvent&lt;/code&gt; to handle synchronisation, and signals (&lt;code&gt;resetEvent.Set()&lt;/code&gt;) as part of the work being done on our new thread. While the new thread is busy doing its asynchronous thang, the thread running our test uses &lt;code&gt;WaitOne()&lt;/code&gt; to patiently sit around until it gets signaled that the asynchronous thread is done. We can then check that the results of the asynchronous operation matched what we expected, which for these tests is just that the code was run and that it used a different thread to run it.&lt;/p&gt;

&lt;p&gt;So now we've got a trivial and tested implementation we can use to make asynchronous calls. If we extract an interface (or make &lt;code&gt;Execute(...)&lt;/code&gt; virtual) we can easily mock this or replace it with a synchronous implementation to test classes that need to use &lt;code&gt;AsynchronousDispatcher&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Apologies if this is all a bit simplistic, but I thought the tests looked kinda neat so I thought I'd share. Feel free to rip gigantic holes in it all. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-8622745215984115093?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=RzQijK6w-o8:ypAb5snnSv0:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=RzQijK6w-o8:ypAb5snnSv0:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=RzQijK6w-o8:ypAb5snnSv0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=RzQijK6w-o8:ypAb5snnSv0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=RzQijK6w-o8:ypAb5snnSv0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=RzQijK6w-o8:ypAb5snnSv0:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/RzQijK6w-o8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/8622745215984115093/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8622745215984115093" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8622745215984115093?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8622745215984115093?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/02/testing-asynchronous-calls.html" title="Testing a class for making asynchronous calls" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total></entry><entry gd:etag="W/&quot;DUEBRHc_fSp7ImA9WxVXEUU.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-3076859047279344619</id><published>2009-02-10T00:29:00.027+11:00</published><updated>2009-02-10T00:54:15.945+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-02-10T00:54:15.945+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="tdd" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title>Testing legacy code when simple threading's involved</title><content type="html">&lt;p&gt;A good friend and &amp;quot;former colleague in (an) archaic dev team&amp;quot; (his words :)) recently sent me a problem he was having testing some code he inherited. The code seemed to work during manual testing, but threw exceptions when being tested using NUnit under certain conditions. Let's look at a drastically modified example of the code:&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class BigImportantClassFixture {
  [Test]
  public void CanGetKnownEmployee() {
    var existingEmployeeId = Guid.Empty
    var importantClass = new BigImportantClass();
    var employee = importantClass.GetEmployee(existingEmployeeId);
    Assert.That(employee.Name, Is.EqualTo(&amp;quot;Bilbo&amp;quot;));
  }
}

public class BigImportantClass {
  &lt;b&gt;public Employee GetEmployee(Guid employeeID) {
    Employee employee = EmployeeRepository.GetEmployeeByID(employeeID);
    Logging.AsyncLog(&amp;quot;Called GetEmployeeByID&amp;quot;);
    return employee;
  }&lt;/b&gt;
}

public static class Logging {
  public static void AsyncLog(string message) {            
    &lt;b&gt;var thread = new Thread(Log);
    thread.Start(message);&lt;/b&gt;
  }

  private static void Log(object message) {
    //Write line to log. This op may take some time
    Thread.Sleep(1000);
    Console.WriteLine(message);
  }
}
&lt;/pre&gt;

&lt;p&gt;Can you guess the exception that cropped up? The unit test runner tears down the app domain it uses to run the fixtures when it is finished. Because the code spawns a new thread, this means that if that thread is still running it gets aborted as the app domain exits, so we get a &lt;code&gt;ThreadAbortException&lt;/code&gt;. So how can we get this under test?&lt;/p&gt;

&lt;h2&gt;Questioning the approach&lt;/h2&gt;
&lt;p&gt;I think it would be remiss of us not to spend some time considering why we are using this approach. Is &lt;code&gt;GetEmployee()&lt;/code&gt; called a lot and so needs to be fast? Will the added burden of spinning up another thread per call help, or will it hinder overall performance due to the increased load on the system? Would we be better off with a synchronous call? Do we even need logging here? Have we looked at using &lt;a href="http://davybrion.com/blog/2008/05/adding-behavior-with-postsharp/"&gt;AOP for logging&lt;/a&gt;? Can libraries like &lt;a href="http://logging.apache.org/log4net/index.html"&gt;log4net&lt;/a&gt; handle asynchronous logging for us? Or should we implement our own queue and have that serviced by threads that can work on processing the logs in batches? Should we be using background threads from the &lt;code&gt;ThreadPool&lt;/code&gt;? Should we look at message queuing? Are static methods and opaque dependencies like this a work of pure evil? And if you were a tree, what tree would you be?&lt;/p&gt;

&lt;p&gt;These are all good questions to ask and something my mate is looking into (I think he's leaning toward the larch). For the rest of this post however, I'd like to concentrate on how we could get this code under test. The code currently seems to work, but we don't have automated tests covering it, so we'll try and keep code changes small to give us confidence we aren't breaking anything during the process. This means we'll try and avoid changes ripping out the dependencies and using constructor injection. &lt;a href="http://www.xerxesb.com/2009/retrofitting-tests-do-whatever-necessary/"&gt;Once it's under test, we can worry about making it purdy&lt;/a&gt; and move on to more complex refactorings, and maybe even change the whole logging implementation once we decide which approach to use.&lt;/p&gt;

&lt;h2&gt;Isolating the logging behaviour in  &lt;code&gt;GetEmployee()&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;Our &lt;code&gt;GetEmployee&lt;/code&gt; method does two things: looks up an &lt;code&gt;Employee&lt;/code&gt; and does some logging. We already have the beginning of a test for the employee lookup part, but the coupling to the logging functionality is causing some problems. It is also untested. Let's write a test that isolates the behaviour.&lt;/p&gt;

&lt;pre&gt;
[Test]
public void GetEmployeeCallIsLogged() {
  var mockLogger = MockRepository.GenerateMock&amp;lt;ILogger&amp;gt;();
  Logging.SetLogger(mockLogger);

  var importantClass = new BigImportantClass();
  importantClass.GetEmployee(Guid.Empty);

  mockLogger.AssertWasCalled(mock =&amp;gt; mock.AsyncLog(Arg&amp;lt;String&amp;gt;.Is.Anything));
}
&lt;/pre&gt;

&lt;p&gt;Normally I'd look at constructor injection for this sort of thing, but we're aiming for minimal modifications to the original code. Logging is also a bit of a special case &amp;mdash; you potentially need it everywhere and so you may not want to explicitly put &lt;code&gt;ILogger&lt;/code&gt; objects into every single object you have.&lt;/p&gt;

&lt;p&gt;To pass this test, we'll need to extract an &lt;code&gt;ILogger&lt;/code&gt; interface from our static &lt;code&gt;Logger&lt;/code&gt; class, and change the implementation to use a Singleton approach (so we can override the behaviour by changing the instance).&lt;/p&gt;

&lt;pre&gt;
public interface ILogger {
  void AsyncLog(string message);
}

public class Logging : ILogger {
  &lt;b&gt;private static ILogger instance = new Logging();
  public static void SetLogger(ILogger logger) { instance = logger; }&lt;/b&gt;

  public static void AsyncLog(string message) {            
    &lt;b&gt;instance.AsyncLog(message);&lt;/b&gt;
  }

  private static void Log(object message) {
    //Write line to log. This op may take some time
    Thread.Sleep(1000);
    Console.WriteLine(message);
  }

  void ILogger.AsyncLog(string message) {
    var thread = new Thread(Log);
    thread.Start(message);
  }
}
&lt;/pre&gt;

&lt;p&gt;This passes our test. Notice we've made virtually no changes to the pre-existing code and only a few minor additions. We've added a singleton instance and a trivial &lt;code&gt;SetLogger()&lt;/code&gt; method, and moved the code previously in the static &lt;code&gt;AsyncLog()&lt;/code&gt; method into the &lt;code&gt;ILogger.AsyncLog()&lt;/code&gt; instance method, with the static methods delegating to the instance one. We haven't had to change the &lt;code&gt;GetEmployee()&lt;/code&gt; method at all. Hopefully this means we haven't broken anything. A quick manual test verifies that everything is working as before.&lt;/p&gt;

&lt;p&gt;I'm a bit worried that we might replace the singleton instance with something evil during one test and inadvertently cause another test to break, but I guess that's a price of using singletons. At this point we just want to get the code under test before we go trying to make it all purdy. On the positive side, we can now test the employee lookup functionality independently of the logging, including testing that &lt;code&gt;GetEmployee()&lt;/code&gt; invokes the logging call as required.&lt;/p&gt;

&lt;h2&gt;An integration test for logging&lt;/h2&gt;
&lt;p&gt;We've isolated our logging behaviour and tested it is called correctly from &lt;code&gt;GetEmployee()&lt;/code&gt;, which means we can now write a test to make sure our logging works when it is called.&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class LoggingFixture {
  [Test]
  public void AsyncLogShouldDoFunkyLoggingStuff() {
    ILogger logging = new Logging();
    logging.AsyncLog(&amp;quot;some message&amp;quot;);
    Thread.Sleep(2000);
    //AssertDesiredSideEffectOccurred();
  }
}
&lt;/pre&gt;

&lt;p&gt;Because of our previous efforts we can work directly with a &lt;code&gt;Logging&lt;/code&gt; instance, rather than through the static methods. We still have a problem though. We want to check that whatever effect &lt;code&gt;AsyncLog()&lt;/code&gt; has occurred properly, but because it is called asynchronously we have to put in a hacky &lt;code&gt;Thread.Sleep()&lt;/code&gt; to make sure it is done. There are a few problems with this approach. Firstly, how do we know 2000 ms is enough? We might have our test intermittently breaking, which is a huge no-no. Secondly, it will make our tests run slow.&lt;/p&gt;

&lt;h2&gt;Isolating our threading problem&lt;/h2&gt;
&lt;p&gt;We'd really like the option of using &lt;code&gt;Thread.Join()&lt;/code&gt; or similar so our test can wait on the asynchronous operation to finish. But we currently don't have any way to access the threading part of the operation.&lt;/p&gt;
&lt;p&gt;One way to solve this problem is to implement the &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc163467.aspx"&gt;Asynchronous Programming Model&lt;/a&gt;. This lets the operation to be called asynchronously and waited on using polling/spin loop, call back or wait handle. Unfortunately it also looks like quite a lot of work, and a large amount of change to make without tests.&lt;/p&gt;

&lt;p&gt;Another possible solution is to isolate the threading behaviour from the logging operation, just as we did for separating the employee lookup from the logging. Let's try that &amp;mdash; we'll write a class that specialises in running a function in a new thread.&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class ThreadDispatcherFixture {
  [Test]
  public void CanRunFunctionCall() {
    var dispatcher = new ThreadDispatcher();
    bool wasRun = false;
    dispatcher.Dispach(() =&amp;gt; wasRun = true);
    Assert.That(wasRun);
  }
}

public class ThreadDispatcher {
  public void Dispach(Action function) {
    function();
  }
}
&lt;/pre&gt;

&lt;p&gt;This passes. Let's expand our test fixture, and try a naive implementation:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void RunsFunctionFromDifferentThread() {
  var dispatcher = new ThreadDispatcher();
  int callingThreadId = Thread.CurrentThread.ManagedThreadId;
  int dispatchedThreadId = -1;
  dispatcher.Dispach(() =&amp;gt; dispatchedThreadId = Thread.CurrentThread.ManagedThreadId);
  Assert.That(dispatchedThreadId, Is.Not.EqualTo(callingThreadId));
}
//...
public class ThreadDispatcher {
  public void Dispach(Action function) {
    var thread = new Thread(() =&amp;gt; function());
    thread.Start();
  }
}
&lt;/pre&gt;

&lt;p&gt;This passes the new &lt;code&gt;RunsFunctionFromDifferentThread()&lt;/code&gt; test, but luckily fails the original &lt;code&gt;CanRunFuctionCall()&lt;/code&gt; test when run on my machine. I say luckily because it is timing dependent &amp;mdash; the thread has not completed by the time the &lt;code&gt;Assert.That(wasRun)&lt;/code&gt; executes. If you slip in a &lt;code&gt;Thread.Sleep(...)&lt;/code&gt; for a few milliseconds you'll see both tests pass as the async thread starts to win our race condition.&lt;/p&gt;

&lt;p&gt;This is a really good illustration that test coverage does not equal correctness, nor is it an excuse to avoid thinking :). Given we've thought about the problem though, TDD can help lead us to a solution. We need to make sure our async thread has run before we call our assert, so let's ammend our tests to show this:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void CanRunFunctionCall() {
  var dispatcher = new ThreadDispatcher();
  bool wasRun = false;            
  var dispatchedThread = dispatcher.Dispach(() =&amp;gt; wasRun = true);
  &lt;b&gt;dispatchedThread.Join();&lt;/b&gt;
  Assert.That(wasRun);
}
[Test]
public void RunsFunctionFromDifferentThread() {
  var dispatcher = new ThreadDispatcher();
  int callingThreadId = Thread.CurrentThread.ManagedThreadId;
  int dispatchedThreadId = callingThreadId;
  var dispatchedThread = dispatcher.Dispach(() =&amp;gt; dispatchedThreadId = Thread.CurrentThread.ManagedThreadId);
  &lt;b&gt;dispatchedThread.Join();&lt;/b&gt;
  Assert.That(dispatchedThreadId, Is.Not.EqualTo(callingThreadId));
}
&lt;/pre&gt;

&lt;p&gt;And a reliably passing implementation (I hope):&lt;/p&gt;

&lt;pre&gt;
public &lt;b&gt;Thread&lt;/b&gt; Dispach(Action function) {
  var thread = new Thread(() =&amp;gt; function());
  thread.Start();
  &lt;b&gt;return thread;&lt;/b&gt;
}
&lt;/pre&gt;

&lt;p&gt;It may not be a good idea to pass a reference to the &lt;code&gt;Thread&lt;/code&gt; back, so it might be neater to wrap the &lt;code&gt;Join()&lt;/code&gt; functionality in a new class (with tests updated accordingly).&lt;/p&gt;

&lt;pre&gt;
public class ThreadDispatcher {
  public AsyncCall Dispach(Action function) {
    var thread = new Thread(() =&amp;gt; function());
    thread.Start();
    return new AsyncCall(thread);
  }
}

public class AsyncCall {
  private readonly Thread _thread;
  public AsyncCall(Thread thread) { _thread = thread; }
  public void WaitUntilCallFinishes() { _thread.Join(); }
}
&lt;/pre&gt;

&lt;p&gt;This is all new code, so we shouldn't have broken anything that was working in our original implementation.&lt;/p&gt;

&lt;h2&gt;Bringing logging and threading back together&lt;/h2&gt;

&lt;p&gt;Now we've separated logging and threading, we need to bring them back together so this thing actually works as required. Let's jump into our &lt;code&gt;LoggingFixture&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class LoggingFixture {
  [Test]
  public void AsyncLogShouldDoFunkyLoggingStuff() {
    ILogger logging = new Logging(new ThreadDispatcher());
    logging.AsyncLog(&amp;quot;some message&amp;quot;);
    Thread.Sleep(2000);
    //AssertDesiredSideEffectOccurred();
  }

  [Test]
  public void AsyncLogShouldUseThreadDispatcher() {
    var dispatcher = MockRepository.GenerateMock&amp;lt;ThreadDispatcher&amp;gt;();
    ILogger logging = new Logging(dispatcher);
    logging.AsyncLog(&amp;quot;some message&amp;quot;);
    dispatcher.AssertWasCalled(x =&amp;gt; x.Dispach(null), options =&amp;gt; options.IgnoreArguments());
  }
}

public class Logging : ILogger {
  private readonly ThreadDispatcher dispatcher;
  private static ILogger instance = new Logging(new ThreadDispatcher());

  &lt;b&gt;public Logging(ThreadDispatcher dispatcher) { this.dispatcher = dispatcher; }&lt;/b&gt;

  public static void SetLogger(ILogger logger) { instance = logger; }

  public static void AsyncLog(string message) {            
    instance.AsyncLog(message);
  }

  private static void Log(object message) {
    //Write line to log. This op may take some time
    Thread.Sleep(1000);
    Console.WriteLine(message);
  }

  void ILogger.AsyncLog(string message) {
    &lt;b&gt;dispatcher.Dispach(() =&amp;gt; Log(message));&lt;/b&gt;
  }
}
&lt;/pre&gt;

&lt;p&gt;This has probably been the most radical change to our code. We've changed the implementation of &lt;code&gt;AsyncLog&lt;/code&gt; to delegate the threading to our new &lt;code&gt;ThreadDispatcher&lt;/code&gt;. We've also added some dependency injection, using the &lt;code&gt;Logging&lt;/code&gt; constructor to pass in our &lt;code&gt;ThreadDispatcher&lt;/code&gt;. Everything is green. Even better, we can now update the original &lt;code&gt;AsyncLogShouldDoFunkyLoggingStuff()&lt;/code&gt; and test the logging behaviour in isolation.&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class LoggingFixture {
  private class FakeThreadDispatcher : ThreadDispatcher {
    public override AsyncCall Dispach(Action function) {
      function();
      return new AsyncCall(null);
    }
  }
  [Test]
  public void AsyncLogShouldDoFunkyLoggingStuff() {
    ILogger logging = new Logging(new FakeThreadDispatcher());
    logging.AsyncLog(&amp;quot;some message&amp;quot;);
    //No more Thread.Sleep(...) here. Our FakeThreadDispatcher will do a synchronous call.
    //AssertDesiredSideEffectOccurred();
  }
  //...
}
&lt;/pre&gt;

&lt;p&gt;You could also do some fancy mockFu for this, but in this case I think it's easier to hand code a &lt;code&gt;FakeThreadDispatcher&lt;/code&gt; (if changes to the base class cascade down to our fake and it starts getting painful we can switch a generated mock or stub).&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Our &lt;code&gt;Logging&lt;/code&gt; implementation only calls &lt;code&gt;Console.WriteLine()&lt;/code&gt;, so for our &lt;code&gt;AssertDesiredSideEffectOccurred()&lt;/code&gt; we would need to fake that out. We won't go that far down the rabbit hole though, as the real logging implementation would be probably do all kinds of exciting things that we could test. The point is that we can now test the logging in isolation from our threading. Our threading code is also tested, and we can test our original employee look up too (by setting a stub &lt;code&gt;ILogger&lt;/code&gt; when testing  &lt;code&gt;BigImportantClass&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Best of all, the only really changes of any consequence we made to our original code is implementing a singleton &lt;code&gt;Logging&lt;/code&gt; instance and extracting the thread launching code to a new class. So, from a unit testing point of view, we have gained a lot for very little risk.&lt;/p&gt;

&lt;p&gt;This was a very simple bunch of refactorings to perform. I hope that came across during the post, but sometimes these things don't translate well to post format. If that's the case then try picking up the code from the start of this post and go through the process of getting it under test.&lt;/p&gt;

&lt;p&gt;As always feel free to pick holes in this post and let me know via comment or email. Hope this helps!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-3076859047279344619?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=8B_fhTh1Xs0:knk_1yqGzvs:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=8B_fhTh1Xs0:knk_1yqGzvs:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=8B_fhTh1Xs0:knk_1yqGzvs:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=8B_fhTh1Xs0:knk_1yqGzvs:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=8B_fhTh1Xs0:knk_1yqGzvs:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=8B_fhTh1Xs0:knk_1yqGzvs:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/8B_fhTh1Xs0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/3076859047279344619/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=3076859047279344619" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3076859047279344619?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3076859047279344619?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/02/testing-legacy-code-when-simple.html" title="Testing legacy code when simple threading's involved" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;C04ERXY_fSp7ImA9WxVQGU8.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-4397291612256960391</id><published>2009-02-04T23:54:00.010+11:00</published><updated>2009-02-06T23:05:04.845+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-02-06T23:05:04.845+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="powershell" /><title>Git-aware PowerShell prompt</title><content type="html">&lt;p&gt;Today a &lt;a href="http://www.shannoncornish.com/blog/"&gt;colleague&lt;/a&gt; sent around an interesting link on how to put your &lt;a href="http://www.intridea.com/posts/git-status-in-your-prompt"&gt;git status in your bash prompt&lt;/a&gt;. I thought I'd spend a few minutes trying to get a similar effect in PowerShell (v2 CTP3). It's not particularly useful, but I found it an interesting exercise. Here's what I came up with, saved in &lt;code&gt;GitAwarePrompt.ps1&lt;/code&gt;. &lt;b&gt;Disclaimer:&lt;/b&gt; I know nothing about PowerShell so use anything from this post at your own risk. :) &lt;/p&gt;

&lt;pre&gt;
function Get-GitBranchNameWithStatusIndicator {
  $statusOutput = Invoke-Expression 'git status 2&amp;gt;$null'  &lt;b&gt;#1&lt;/b&gt;
  if (!$statusOutput) { return } &lt;b&gt;#2&lt;/b&gt;
  $branch = $statusOutput[0] &lt;b&gt;#3&lt;/b&gt;
  if ($branch -eq &amp;quot;# Not currently on any branch.&amp;quot;) {
    $branch = &amp;quot;No branch&amp;quot;
  } else {
    $branch =  $branch.SubString(&amp;quot;# On branch &amp;quot;.Length) 
  }
  $statusSummary = $statusOutput[-1] &lt;b&gt;#4&lt;/b&gt;
  if ($statusSummary -eq &amp;quot;nothing to commit (working directory clean)&amp;quot;) { &lt;b&gt;#5&lt;/b&gt;
    $statusIndicator = &amp;quot;&amp;quot; 
  } else {
    $statusIndicator = &amp;quot;*&amp;quot;
  }
  return $branch + $statusIndicator
}

function prompt { &lt;b&gt;#6&lt;/b&gt;
  $gitStatus = Get-GitBranchNameWithStatusIndicator
  Write-Host (&amp;quot;PS &amp;quot; + $(get-location)) -nonewline
  if ($gitStatus) {
    Write-Host (&amp;quot; [&amp;quot; + $gitStatus +&amp;quot;]&amp;quot;) -nonewline -foregroundcolor Gray
  }
  Write-Host (&amp;quot;&amp;gt;&amp;quot;) -nonewline
  return &amp;quot; &amp;quot;
}
&lt;/pre&gt;

&lt;p&gt;I've put some numbered comments on a couple of lines so we can go through the main parts of the script, or you can skip to the next heading if you just want to try out the script.&lt;/p&gt;

&lt;p&gt;Line #1 uses the &lt;code&gt;Invoke-Expression&lt;/code&gt; commandlet to run the &lt;code&gt;git status&lt;/code&gt; command and store the output in the local &lt;code&gt;$statusOutput&lt;/code&gt; variable. We are using &lt;code&gt;2&amp;gt;$null&lt;/code&gt; to drop any output written to standard error, otherwise whenever we try and write a prompt in a non-git directory we'll get a git error message appearing. You'll also notice we have the &lt;code&gt;git status 2&amp;gt;$null&lt;/code&gt; command surrounded by single quotes ('), rather than double quotes (&amp;quot;). The reason is that PowerShell automatically performs variable substitution within double quoted strings. So if we used double quotes the &lt;code&gt;$null&lt;/code&gt; would be replaced by with nothing (it's current value), which will cause us no end of problems (go on, ask me how I know! :)). &lt;/p&gt;

&lt;p&gt;If the &lt;code&gt;git status&lt;/code&gt; command errors out (say, if the current directory is not in a git repo), then &lt;code&gt;$gitStatus&lt;/code&gt; will be null. Line #2 checks for this and returns void if &lt;code&gt;$statusOutput&lt;/code&gt; is undefined. Otherwise &lt;code&gt;$statusOutput&lt;/code&gt; will an array of objects, with an item for each line of the command output. Line #3 grabs the first line of output, which contains a string which contains our branch name, and stores it in a variable. The &lt;code&gt;if/else&lt;/code&gt; that follow checks first to make sure we are actually on a branch, and parses the branch name from the line.&lt;/p&gt;

&lt;p&gt;Line #4 was a nice surprise for me -- PowerShell supports wrapped array indexing! Using an index of &lt;code&gt;-1&lt;/code&gt; grabs the last item in the array. Very pythonesque :). Line #5 then compares this with the output &lt;code&gt;git status&lt;/code&gt; gives when there are no changes, and the rest of the &lt;code&gt;if/else&lt;/code&gt; block sets the &lt;code&gt;$statusIndicator&lt;/code&gt; based on this result. (No &lt;a href="http://blogs.msdn.com/powershell/archive/2006/12/29/dyi-ternary-operator.aspx"&gt;built in ternary operator&lt;/a&gt; apparently.)&lt;/p&gt;

&lt;p&gt;Finally, line #6 defines a &lt;code&gt;prompt&lt;/code&gt; function, which PowerShell uses to write it's prompt.&lt;/p&gt;

&lt;h2&gt;Using the script&lt;/h2&gt;

&lt;p&gt;If we just run this script from within PowerShell it will do absolutely nothing. The reason is because any functions or variables defined will be cleaned up when the script exits. To change the scope and affect the current environment we need to &lt;a href="http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/run.mspx#EMBAC"&gt;dot-source&lt;/a&gt; the script, like this (depending on where you saved the script):&lt;/p&gt;

&lt;pre&gt;
PS &amp;gt; . $HOME/Documents/WindowsPowerShell/GitAwarePrompt.ps1
&lt;/pre&gt;

&lt;p&gt;Without the dot and space, you get nothing. With the dot-sourced script, we have created a &lt;code&gt;prompt&lt;/code&gt; function for PowerShell to call, and we get the status of our Git working directory from our command line:&lt;/p&gt;

&lt;pre&gt;
PS C:\Development\git\HelloWorld &lt;b&gt;[helloGit]&lt;/b&gt;&amp;gt; &amp;quot;Modify hello.txt&amp;quot; &amp;gt; hello.txt
PS C:\Development\git\HelloWorld &lt;b&gt;[helloGit*]&lt;/b&gt;&amp;gt; git commit -a -m &amp;quot;Commit change&amp;quot;
[helloGit]: created 8a7947c: &amp;quot;Commit change&amp;quot;
 1 files changed, 0 insertions(+), 0 deletions(-)
PS C:\Development\git\HelloWorld &lt;b&gt;[helloGit]&lt;/b&gt;&amp;gt; git checkout master
Switched to branch &amp;quot;master&amp;quot;
PS C:\Development\git\HelloWorld &lt;b&gt;[master]&lt;/b&gt;&amp;gt; &amp;quot;Change hello.txt again&amp;quot; &amp;gt; hello.txt
PS C:\Development\git\HelloWorld &lt;b&gt;[master*]&lt;/b&gt;&amp;gt;
PS C:\Development\git\HelloWorld &lt;b&gt;[master*]&lt;/b&gt;&amp;gt; cd ..
PS C:\Development\Git&amp;gt;
&lt;/pre&gt;

&lt;h2&gt;Setting the default prompt&lt;/h2&gt;

&lt;p&gt;You can also more permanently modify your PowerShell prompt by putting the script in your PowerShell profile, which is set to something like &lt;code&gt;~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1&lt;/code&gt; by default (if it doesn't exist, you can create it from PowerShell using &lt;code&gt; New-Item $PROFILE -ItemType file -Force&lt;/code&gt;). This can be something like the Git-aware prompt shown here, or something &lt;a href="http://mshforfun.blogspot.com/2006/05/perfect-prompt-for-windows-powershell.html"&gt;more interesting&lt;/a&gt;. Be careful you don't slow down your shell too much though: &lt;code&gt;prompt&lt;/code&gt; is obviously called on every new line!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-4397291612256960391?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=m_wroF59aeU:QPtyMmnSETI:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=m_wroF59aeU:QPtyMmnSETI:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=m_wroF59aeU:QPtyMmnSETI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=m_wroF59aeU:QPtyMmnSETI:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=m_wroF59aeU:QPtyMmnSETI:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=m_wroF59aeU:QPtyMmnSETI:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/m_wroF59aeU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/4397291612256960391/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=4397291612256960391" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4397291612256960391?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4397291612256960391?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/02/git-aware-powershell-prompt.html" title="Git-aware PowerShell prompt" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;C0cNRn0zcSp7ImA9WxJRF0U.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-506003894564689820</id><published>2009-02-03T23:23:00.047+11:00</published><updated>2009-05-20T10:58:17.389+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-05-20T10:58:17.389+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="git" /><title>Setting up diff and merge tools for Git on Windows</title><content type="html">&lt;p&gt;I finally got tired of reading diff outputs from git on the command line, and decided to hook up a visual diff and merge tool. After piecing together hints from various posts around ye olde intraweb I've now got somethings that works. I am using &lt;a href="http://code.google.com/p/msysgit/"&gt;Git on MSys&lt;/a&gt; to get Git working on Windows via a PowerShell command line, but a similar setup might work via Cygwin or via the &lt;code&gt;cmd.exe&lt;/code&gt; command line.&lt;/p&gt;

&lt;h2&gt;Setting up a diff tool&lt;/h2&gt;

&lt;div class="note"&gt;&lt;b&gt;Update 2009-05-20:&lt;/b&gt; This approach stopped working for me when I upgraded to Windows 7 and Git 1.6.3. I had to &lt;a href="http://www.davesquared.net/2009/05/setting-up-git-difftool-on-windows.html"&gt;switch to using &lt;code&gt;git difftool&lt;/code&gt; instead&lt;/a&gt;.&lt;/div&gt;

&lt;p&gt;The easiest way I found to do this was to create a shell script wrapper for your diff tool of choice. To make things easy on me I put the script, &lt;code&gt;git-diff-wrapper.sh&lt;/code&gt; in &lt;code&gt;C:\Program Files\Git\cmd&lt;/code&gt;, which is in my &lt;code&gt;Path&lt;/code&gt; environment variable. The file contents looks like this:&lt;/p&gt;

&lt;pre&gt;
#!/bin/sh

# diff is called by git with 7 parameters:
#  path old-file old-hex old-mode new-file new-hex new-mode
&lt;b&gt;&amp;quot;C:/Program Files/SourceGear/DiffMerge/DiffMerge.exe&amp;quot; &amp;quot;$2&amp;quot; &amp;quot;$5&amp;quot; | cat&lt;/b&gt;

#&amp;quot;C:/Program Files/WinMerge/WinMergeU.exe&amp;quot; &amp;quot;$2&amp;quot; &amp;quot;$5&amp;quot; | cat
#&amp;quot;C:/Program Files/KDiff3/kdiff3.exe&amp;quot; &amp;quot;$2&amp;quot; &amp;quot;$5&amp;quot; | cat
&lt;/pre&gt;

&lt;p&gt;The basic format of this is stolen directly from &lt;a href="http://code.google.com/p/msysgit/issues/detail?id=106"&gt;this post&lt;/a&gt; on the Msysgit site. Provided your diff tool can be called from the command line, you'll be able to set it up to work with Git using this template. In this case I've used it to setup a call to &lt;a href="http://www.sourcegear.com/diffmerge/"&gt;Sourcefear's DiffMerge&lt;/a&gt;, a nice free (as in beer) diff and merge tool. &lt;/p&gt;

&lt;p&gt;You'll also see I've commented out calls to &lt;a href="http://winmerge.org/"&gt;WinMerge&lt;/a&gt; and &lt;a href="http://kdiff3.sourceforge.net/"&gt;KDiff3&lt;/a&gt;, which are both free as in beer and speech. I ended up settling on DiffMerge because it is purdy (unlike KDiff3 -- sorry), and also does 3-way merges (unlike WinMerge, which was my previous diff tool of choice).&lt;/p&gt;

&lt;p&gt;The next step is telling Git about your wrapper. In your home directory (&lt;code&gt;C:\Users\(username)&lt;/code&gt; or the corresponding Documents and Settings equivalent) Git will normally have created a &lt;code&gt;.gitconfig&lt;/code&gt; file. If not then go ahead and create one. You'll need to have the following section in there:&lt;/p&gt;

&lt;pre&gt;
[diff]
 external = C:/Program Files/git/cmd/git-diff-wrapper.sh
&lt;/pre&gt;

&lt;p&gt;We can now use &lt;code&gt;git diff&lt;/code&gt; and it will fire up our diff tool of choice.&lt;/p&gt;

&lt;h2&gt;Setting up a merge tool&lt;/h2&gt;
&lt;p&gt;I had more trouble getting a merge tool working, largely because putting references to paths like &lt;code&gt;C:/Program Files/...&lt;/code&gt; in &lt;code&gt;.gitconfig&lt;/code&gt; seems to bork when used here. Again I ended up using the wrapper approach, creating &lt;code&gt;git-merge-diffmerge-wrapper.sh&lt;/code&gt; at &lt;code&gt;C:\Program Files\Git\cmd&lt;/code&gt; to call DiffMerge. This file ended up looking like this:&lt;/p&gt;

&lt;pre&gt;
#!/bin/sh

# Passing the following parameters to mergetool:
#  local base remote merge_result

"C:/Program Files/SourceGear/DiffMerge/DiffMerge.exe" "$1" "$2" "$3" --result="$4" --title1="Mine" --title2="Merging to: $4" --title3="Theirs"
&lt;/pre&gt;

&lt;p&gt;I unashamedly stole this from &lt;a href="http://www.therightstuff.de/2009/01/28/Setting-Up-SourceGear-DiffMerge-With-Git.aspx"&gt;Alexander Groß's post on getting DiffMerge running on Cygwin-based Git&lt;/a&gt; (with slight modifications, any faults are mine :)). We can then wire this up in &lt;code&gt;.gitconfig&lt;/code&gt; again:&lt;/p&gt;

&lt;pre&gt;
[merge]
    tool = diffmerge

[mergetool &amp;quot;diffmerge&amp;quot;]
 cmd = git-merge-diffmerge-wrapper.sh &amp;quot;$PWD/$LOCAL&amp;quot; &amp;quot;$PWD/$BASE&amp;quot; &amp;quot;$PWD/$REMOTE&amp;quot; &amp;quot;$PWD/$MERGED&amp;quot; 
    trustExitCode = false
 keepBackup = false
 
[mergetool &amp;quot;kdiff3&amp;quot;]
    path = C:/Program Files/KDiff3/kdiff3.exe
    keepBackup = false
    trustExitCode = false
&lt;/pre&gt;

&lt;p&gt;Now remember that &lt;code&gt;C:\Program Files\Git\cmd&lt;/code&gt; is on my &lt;code&gt;PATH&lt;/code&gt;, so I can set the command to call &lt;code&gt;git-merge-diffmerge-wrapper.sh&lt;/code&gt; without fully qualifying the path. The details on the arguments are available from the &lt;a href="http://www.kernel.org/pub/software/scm/git/docs/git-mergetool.html"&gt;git-mergetool(1) man page&lt;/a&gt;. I've also left in a KDiff3 version that seems to work too (Git has some built in support for KDiff3 I think, which is why you can get away with only specifying the path).&lt;/p&gt;

&lt;h2&gt;Time for a test drive&lt;/h2&gt;
&lt;p&gt;Let's make sure everything's in working order. I'll open up a PowerShell window and let's see how we go (you'll have to excuse me for using old DOS commands instead of fancy PowerShell ones, I've only just switched to PS after running into various issues with the &lt;code&gt;cmd.exe&lt;/code&gt; command line).&lt;/p&gt;

&lt;pre&gt;
PS&amp;gt; mkdir HelloWorld
PS&amp;gt; cd HelloWorld
PS&amp;gt; git init
  Initialized empty Git repository in C:/Development/Git/HelloWorld/.git/
PS&amp;gt; echo Hello World! &amp;gt; hello.txt
PS&amp;gt; git add hello.txt
PS&amp;gt; git commit -m &amp;quot;Initial commit&amp;quot;
  [master (root-commit)]: created 2a2cf34: &amp;quot;Initial commit&amp;quot;
   1 files changed, 0 insertions(+), 0 deletions(-)
   create mode 100644 hello.txt
PS&amp;gt; git checkout -b helloGit
  Switched to a new branch &amp;quot;helloGit&amp;quot;
PS&amp;gt; echo Hello Git! &amp;gt; hello.txt
PS&amp;gt; git add hello.txt
PS&amp;gt; git commit -m &amp;quot;Update from helloGit branch&amp;quot;
  [helloGit]: created e71437b: &amp;quot;Update from helloGit branch&amp;quot;
   1 files changed, 0 insertions(+), 0 deletions(-)
PS&amp;gt; git checkout master
  Switched to branch &amp;quot;master&amp;quot;
PS&amp;gt; echo Hello World! Hello indeed! &amp;gt; hello.txt
PS&amp;gt; git add hello.txt
PS&amp;gt; git commit -m &amp;quot;Update from master&amp;quot;
  [master]: created 5dee19d: &amp;quot;Update from master&amp;quot;
   1 files changed, 0 insertions(+), 0 deletions(-)
PS&amp;gt; git merge helloGit
  warning: Cannot merge binary files: HEAD:hello.txt vs. helloGit:hello.txt

  Auto-merging hello.txt
  CONFLICT (content): Merge conflict in hello.txt
  Automatic merge failed; fix conflicts and then commit the result.
&lt;/pre&gt;

&lt;div class="note"&gt;Because I've used &lt;code&gt;echo&lt;/code&gt; to stream data into &lt;code&gt;hello.txt&lt;/code&gt; the files have ended up in binary mode. Let's ignore that as it is just to get an easy demo going. The important thing is we now have a merge conflict to resolve.&lt;/div&gt;

&lt;p&gt;If we now type in &lt;code&gt;git mergetool&lt;/code&gt; Git ask's us if we'd like to run our merge tool. We can hit enter and up pops DiffMerge. If you wanted KDiff3, we could have called &lt;code&gt;git mergetool -t kdiff3&lt;/code&gt;, or any other merge tool in our &lt;code&gt;.gitconfig&lt;/code&gt; (by default the tool specified in the &lt;code&gt;merge.tool&lt;/code&gt; config option is used).&lt;/p&gt;

&lt;pre&gt;
PS&amp;gt; git mergetool
Merging the files: hello.txt

Normal merge conflict for 'hello.txt':
  {local}: modified
  {remote}: modified
Hit return to start merge resolution tool (diffmerge):

&lt;/pre&gt;

&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://picasaweb.google.com/lh/photo/7I08AQm42qGhkAfGm36b8g?authkey=XWXzeleCcGk&amp;feat=embedwebsite"&gt;&lt;img src="http://lh3.ggpht.com/_wEsHWMWy090/SYg3YF8-huI/AAAAAAAAA7A/UPOkNLHPSaU/s800/diffMerge-3way.png" /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Resolve the merge conflict however you like and then try this:&lt;/p&gt;

&lt;pre&gt;
PS&amp;gt; echo Wow, it worked! &amp;gt; hello.txt
PS&amp;gt; git diff
&lt;/pre&gt;

&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://picasaweb.google.com/lh/photo/Por6nx-Houtmfc3ILIE_dw?authkey=XWXzeleCcGk&amp;feat=embedwebsite"&gt;&lt;img src="http://lh5.ggpht.com/_wEsHWMWy090/SYg3ZSorfYI/AAAAAAAAA7I/-_oWC0BkRRE/s800/diffMerge-diff.png" /&gt;&lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;Hooray, we have our diff tool working! We can also run commands like &lt;code&gt;git diff HEAD~ HEAD&lt;/code&gt; and &lt;code&gt;git diff helloGit master&lt;/code&gt; and get the output via our diff tool.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;This setup earns the coveted &lt;a href="http://www.codinghorror.com/blog/archives/000818.html"&gt;Works on My Machine&lt;/a&gt; certification, but even if that's the only place it works then hopefully it still gives you enough information to configure your Windows diff and merge tools for use with Git.&lt;/p&gt;

&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;a href="http://www.codinghorror.com/blog/archives/000818.html" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img src="http://lh4.ggpht.com/_wEsHWMWy090/SYg42J2XdHI/AAAAAAAAA7Q/hHGvPBogwWY/s800/works-on-my-machine-starburst.png" /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;If you hunt down the relevant command line options you should be able to get pretty much any tool working: &lt;a href="http://cbilson.blogspot.com/2008/10/using-beyond-compare-as-git-mergetool.html"&gt;Beyond Compare&lt;/a&gt;, &lt;a href="http://blog.logicalrand.com/2008/9/9/use-p4merge-or-diffmerge-with-git-mergetool-on-os-x"&gt;p4merge&lt;/a&gt;, &lt;a href="http://palaso.org/archives/52"&gt;TortoiseMerge&lt;/a&gt; etc.&lt;/p&gt;

&lt;p&gt;Hope this helps.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-506003894564689820?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=7aQjSYpv3eY:DonKG3FQxqQ:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=7aQjSYpv3eY:DonKG3FQxqQ:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=7aQjSYpv3eY:DonKG3FQxqQ:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=7aQjSYpv3eY:DonKG3FQxqQ:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=7aQjSYpv3eY:DonKG3FQxqQ:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=7aQjSYpv3eY:DonKG3FQxqQ:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/7aQjSYpv3eY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/506003894564689820/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=506003894564689820" title="12 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/506003894564689820?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/506003894564689820?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/02/setting-up-diff-and-merge-tools-for-git.html" title="Setting up diff and merge tools for Git on Windows" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/_wEsHWMWy090/SYg3YF8-huI/AAAAAAAAA7A/UPOkNLHPSaU/s72-c/diffMerge-3way.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">12</thr:total></entry><entry gd:etag="W/&quot;D04MSXs-cSp7ImA9WxVRFU4.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-5616194819787817713</id><published>2009-01-21T21:56:00.001+11:00</published><updated>2009-01-21T22:06:28.559+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-21T22:06:28.559+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title>An introduction to the SOLID principles of OO design</title><content type="html">&lt;p&gt;I would be very hard pressed to go passed Robert &amp;quot;Uncle Bob&amp;quot; Martin's &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;SOLID principles&lt;/a&gt; as the single most useful tool for helping me with OO design. Some people seem to have a natural talent for OO design and thinking, and have an innate understanding of these principles without requiring the SOLID formalism. I, on the other hand, find them indispensable.&lt;/p&gt;

&lt;p&gt;Unfortunately the names used in the somewhat-cryptic &amp;quot;acronym of acronyms&amp;quot;[1] don't exactly lend themselves to being easily learned (Bob Martin and Scott discussed how this came about on a &lt;a href="http://www.hanselman.com/blog/HanselminutesPodcast145SOLIDPrinciplesWithUncleBobRobertCMartin.aspx"&gt;Hanselminutes episode on SOLID&lt;/a&gt;, which is well worth a listen). I thought I'd post my interpretation of the principles as a refresher for myself, and as an introduction for anyone trying the learn the terminology.&lt;/p&gt;

&lt;p&gt;I should point out I am far from a guru on this stuff, so if there's any misinformation in here please point it out in a comment or email, so I can correct the post and learn me some OO :).&lt;/p&gt;

&lt;h2&gt;Single Responsibility Principle&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;i&gt;&amp;quot;There should never be more than one reason for a class to change.&amp;quot; &amp;mdash; Robert Martin, SRP paper linked from &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The Principles of OOD&lt;/a&gt;&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;My translation: A class should concentrate on doing one thing&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The SRP says a class should focus on doing one thing, or have one &lt;i&gt;responsibility&lt;/i&gt;. This doesn't mean it should only have one method, but instead all the methods should relate to a single purpose (i.e. should be cohesive).&lt;/p&gt;

&lt;p&gt;For example, an &lt;code&gt;Invoice&lt;/code&gt; class might have the responsibility of calculating various amounts based on it's data. In that case it probably shouldn't know about how to retrieve this data from a database, or how to format an invoice for print or display.&lt;/p&gt;

&lt;p&gt;A class that adheres to the SRP should be easier to change than those with multiple responsibilities. If we have calculation logic and database logic and display logic all mixed up within one class it can be difficult to change one part without breaking others. Mixing responsibilities also makes the class harder to understand, harder to test, and increases the risk of duplicating logic in other parts of the design (decreases cohesion, functionality has no clear place to live).&lt;/p&gt;

&lt;p&gt;Violations of the SRP are pretty easy to notice: the class seems to be doing too much, is too big and too complicated. The easiest way to fix this is to split the class.&lt;/p&gt;

&lt;p&gt;The main trick in following the SRP is deciding how to define the single responsibility. There may be many ways to dissect a feature into responsibilities, but the ideal way is to use responsibilities that are likely to change independently, hence the official description: &amp;quot;A class should have one, and only one, reason to change&amp;quot;.&lt;/p&gt;

&lt;h2&gt;Open Closed Principle&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;i&gt;&amp;quot;Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.&amp;quot; &amp;mdash; Robert Martin paraphrasing Bertrand Meyer, OCP paper linked from &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The Principles of OOD&lt;/a&gt;&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;My translation: Change a class' behaviour using inheritance and composition&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Bob Martin's initial paper on the OCP linked from &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The Principles of OOD&lt;/a&gt; attributes the idea to Bertrand Meyer, who wrote that classes should be "open for extension, but closed for modification"[2]. The idea is that we can use OO techniques like inheritance and composition to change (or &lt;i&gt;extend&lt;/i&gt;) the behaviour of a class, without modifying the class itself.&lt;/p&gt;

&lt;p&gt;Say we have an &lt;code&gt;OrderValidation&lt;/code&gt; class with one big &lt;code&gt;Validate(Order order)&lt;/code&gt; method that contains all rules required to validate an order. If the rules change, we need to change or &lt;code&gt;OrderValidation&lt;/code&gt; class, so we are violating the OCP. If the &lt;code&gt;OrderValidation&lt;/code&gt; contained a collection of &lt;code&gt;IValidationRule&lt;/code&gt; objects that contained the rules, then we could write &lt;code&gt;Validate(Order order)&lt;/code&gt; to iterate through those to validate the order. Now if the rules change then we can just create a new &lt;code&gt;IValidationRule&lt;/code&gt; and add it to an &lt;code&gt;OrderValidation&lt;/code&gt; instance at run time (rather than to the class definition itself).&lt;/p&gt;

&lt;p&gt;Following the OCP should make behaviour easier to change, and also help us avoid breaking existing behaviour while making changes. The OCP also gets us to think about the likely areas of change in a class, which helps us choose the right abstractions required for our design.&lt;/p&gt;

&lt;p&gt;If you find you need to modify a similar area of code all the time (for example, validation rules) then it's probably time to apply the OCP and abstract away the changing part of the code. Another sign of a potential OCP violation is switching on a type &amp;mdash; if another type is created then we'll have to alter the switch statement. A &lt;a href="http://refactoring.com/catalog/replaceConditionalWithPolymorphism.html"&gt;healthy dose of polymorphism&lt;/a&gt; is generally the best treatment. :) I generally think of the OCP as an advertisement for the &lt;i&gt;Template Method&lt;/i&gt; and &lt;i&gt;Strategy&lt;/i&gt; design patterns.&lt;/p&gt;

&lt;h2&gt;Liskov Substitution Principle&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;i&gt;&amp;quot;Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.&amp;quot; &amp;mdash; Robert Martin, LSP paper linked from &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The Principles of OOD&lt;/a&gt;&lt;br/&gt;&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;My translation:  Subclasses should behave nicely when used in place of their base class&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The LSP sounds deceptively straightforward &amp;mdash; we should be able to substitute an instance of a subclass for its parent class and everything should continue to work. Easy right? Well, actually, no it's not, which is probably why we are often advised to &lt;a href="http://www.artima.com/lejava/articles/designprinciples4.html"&gt;favour composition over inheritance&lt;/a&gt;.  Ensuring a base class works in any situation the parent does is really hard work, and whenever you use inheritance its a good idea to keep the LSP firmly in mind.&lt;/p&gt;

&lt;p&gt;The canonical example of an LSP violation (in fact, the one used in the &lt;a href="http://www.hanselman.com/blog/HanselminutesPodcast145SOLIDPrinciplesWithUncleBobRobertCMartin.aspx"&gt;Hanselminutes episode on SOLID&lt;/a&gt; mentioned earlier) is the &lt;code&gt;Square&lt;/code&gt; IS-A &lt;code&gt;Rectangle&lt;/code&gt; relationship. Mathematically a square is a special case of a rectangle with all sides of equal length, but this breaks the LSP when modelled in code. What should &lt;code&gt;SetWidth(int width)&lt;/code&gt; do when called on a &lt;code&gt;Square&lt;/code&gt;? Should it set the height as well? What if you have a reference to it via its base class, &lt;code&gt;Rectangle&lt;/code&gt;? If you have code that expects one behaviour but gets another depending on which subtype it has, you can wind up with some very hard to find bugs.&lt;/p&gt;

&lt;p&gt;LSP violations can be easy to miss until you actually hit the condition where your inheritance hierarchy breaks down (I mean, a &lt;a href="http://blog.objectmentor.com/articles/2009/01/16/i-hate-cutesy-phrases"&gt;square IS-A rectangle&lt;/a&gt;, right?). The best way to reduce violations is to keep very aware of the LSP whenever using inheritance, including considering avoiding the problem using composition where appropriate.&lt;/p&gt;

&lt;h2&gt;Interface Segregation Principle&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;i&gt;&amp;quot;Clients should not be forced to depend upon interfaces that they do not use.&amp;quot; &amp;mdash; Robert Martin, ISP paper linked from &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The Principles of OOD&lt;/a&gt;&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;My translation: Keep interfaces small and cohesive&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The ISP is about keeping interfaces (both &lt;code&gt;interface&lt;/code&gt;, and &lt;code&gt;abstract class&lt;/code&gt; types of interfaces) small and limited only to a very specific need (a single responsibility even :)). If you have a fat interface then you are imposing a huge implementation burden on anyone that wants to adhere to that contract. Worse still is that there is a tendency for class to only provide valid implementations for a small portion of a fat interface, which greatly diminishes the advantages of having an interface at all (note that these partial implementations violate the LSP, as we can no longer treat all subclasses of the interface equally).&lt;/p&gt;

&lt;p&gt;The first time I recognised a violation of the ISP was writing a minimal implementation of an ASP.NET &lt;code&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.aspx"&gt;RoleProvider&lt;/a&gt;&lt;/code&gt;, which required an implementation of the following methods:&lt;/p&gt;

&lt;pre&gt;
public class MyRoleProvider : RoleProvider {
    public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { ... }
 public override void AddUsersToRoles(string[] usernames, string[] roleNames) { ... }
 public override string ApplicationName { get { ... } set { ... } }
 public override void CreateRole(string roleName) { ... }
 public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { ... }
 public override string[] FindUsersInRole(string roleName, string usernameToMatch) { ... }
 public override string[] GetAllRoles() { ... }
 public override string[] GetRolesForUser(string username) { ... }
 public override string[] GetUsersInRole(string roleName) { ... }
 public override bool IsUserInRole(string username, string roleName) { ... }
 public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { ... }
 public override bool RoleExists(string roleName) { ... }
}
&lt;/pre&gt;

&lt;p&gt;In my case I just wanted to use ASP.NET's built in facility for securing pages by role in the &lt;code&gt;web.config&lt;/code&gt;, which means I needed to implement &lt;code&gt;GetRolesForUser(...)&lt;/code&gt; and &lt;code&gt;Initialize(...)&lt;/code&gt;. Can you guess what the other implementations were? That's right, &lt;code&gt;throw new NotImplementedException();&lt;/code&gt;. This is very bad &amp;mdash; if we have a &lt;code&gt;RoleProvider&lt;/code&gt; instance we have no idea what sub-features it will support. On top of that we also have a lot of useless noise in our class. (If you like the &lt;code&gt;RoleProvider&lt;/code&gt;, you might also enjoy the &lt;code&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider_members.aspx"&gt;MembershipProvider&lt;/a&gt;&lt;/code&gt;.)&lt;/p&gt;

&lt;p&gt;The way to fix violations like this is to break down interfaces along the lines of responsibilities and apply the SRP. For the &lt;code&gt;RoleProvider&lt;/code&gt; case, even if we just split it into &lt;code&gt;IRolesForUserLookup&lt;/code&gt; and &lt;code&gt;IRoleManagement&lt;/code&gt; (yuk), that would let us only implement what we need. If we need all the features then we can implement both interfaces, but we should not be forcing clients to fake or throw in implementations that are meaningless to them.&lt;/p&gt;

&lt;h2&gt;Dependency Inversion Principle&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;i&gt;&amp;quot;A. High level modules should not depend upon low level modules. Both should depend upon abstractions.&lt;br/&gt;
B. Abstractions should not depend upon details. Details should depend upon abstractions.&amp;quot; &amp;mdash; Robert Martin, DIP paper linked from &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The Principles of OOD&lt;/a&gt;&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;My translation: Use lots of interfaces and abstractions&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The DIP says that if a class has dependencies on other classes, it should rely on the dependencies' interfaces rather than their concrete types. The idea is that we isolate our class behind a boundary formed by the abstractions it depends upon. If all the details behind those abstractions change then our class is still safe. This helps keep coupling low and makes our design easier to change.&lt;/p&gt;

&lt;p&gt;At its simplest, this can just be the difference between referencing an &lt;code&gt;EmployeeFinder&lt;/code&gt; class or an &lt;code&gt;IEmployeeFinder&lt;/code&gt; interface. The concrete &lt;code&gt;EmployeeFinder&lt;/code&gt; class can access a database or a file, but the client class only cares that it meets the &lt;code&gt;IEmployeeFinder&lt;/code&gt; contract. Better yet, our client class doesn't have to be tied in any way to the &lt;code&gt;EmployeeFinder&lt;/code&gt; class. It could instead use &lt;code&gt;SqlEmployeeFinder&lt;/code&gt;, &lt;code&gt;XmlEmployeeFinder&lt;/code&gt;, &lt;code&gt;WebServiceEmployeeFinder&lt;/code&gt; or &lt;code&gt;MockEmployeeFinder&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Where the DIP starts to become really useful and a bit more profound is in a related concept, &lt;i&gt;Dependency Injection&lt;/i&gt;. Dependency Injection is about getting other code to insert the actual dependency instances into our class, so we don't even have the client class &lt;code&gt;new&lt;/code&gt;ing up any of the concrete instances. This completely isolates our class and makes change and reuse much easier. (I've covered some introductory stuff in a &lt;a href="http://davesquared.blogspot.com/2008/06/attempting-to-understand-dependency.html"&gt;previous ramble on dependency injection&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The other side of the DIP relates to dependencies between high and low level modules in layered applications. For example, a class accessing the database should not depend on a UI form used to display that data. Instead the UI should rely on an abstraction (or abstractions) over the database access class. Traditional application layers (data, logic, ui) seem largely replaced by MVC, &lt;a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/"&gt;onions&lt;/a&gt; and &lt;a href="http://alistair.cockburn.us/Hexagonal+architecture"&gt;hexagons&lt;/a&gt; these days, so I tend to think about the DIP entirely from the point of view of abstracting dependencies.&lt;/p&gt;

&lt;h2&gt;SOLID principles as a whole&lt;/h2&gt;

&lt;p&gt;You can probably see that the SOLID principles overlap a lot. For example, the SRP provides a good way of splitting interfaces to follow the ISP. The ISP helps implementers conform to the LSP by making implementations small and cohesive. You may also notice that some of the principles contradict, or at least pull in opposing directions, such as the OCP requiring inheritance while the LSP tends to discourage it[3]. This interplay between the principles can provide a really useful guide while developing your design. I'm believe there are no perfect designs, just trade offs, and the SOLID principles can help you evaluate these and achieve a good balance. The fact that there is some measure of conflict between them also makes it obvious that none of the principles should be applied rigidly or dogmatically. Do you really need a huge interface explosion due while adhering to the OCP and DIP? Maybe, maybe not. But considering your design options in light of the SOLID principles can help you decide.&lt;/p&gt;

&lt;p&gt;A lot of SOLID principles seem to fall out fairly naturally if you practice TDD (or BDD). For example, writing an effective unit test for a class is much easier if you follow the DIP and isolate your class from its dependencies. If you are writing the tests first to drive your design, then your class will naturally tend to use the DIP. If you are retro-fitting tests, then you'll likely encounter more difficulties testing, and may end up with  interaction-style tests, re-writing the class to use the DIP, or worse, throwing it in the too hard-to-test basket.&lt;/p&gt;

&lt;p&gt;This is what people mean when they say that TDD and &amp;quot;testability&amp;quot; is not about testing, it is about design. Scott Bellware recently published a good post on &lt;a href="http://blog.scottbellware.com/2009/01/good-design-is-easily-learned.html"&gt;design, SOLID and testability&lt;/a&gt; that goes into this in more detail.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;This has been a quick introduction to the SOLID principles. Hopefully it will make it easier for people to jump into the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;gory details of all the principles&lt;/a&gt;. Even if you have an innate grasp on these principles, I think it is worth going to the trouble to learn them, if only to help get a common language with which to discuss these principles.&lt;/p&gt;

&lt;h2&gt;Recommended reading and listening&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Robert Martin's original SOLID papers from &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The Principles of OOD&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.hanselman.com/blog/HanselminutesPodcast145SOLIDPrinciplesWithUncleBobRobertCMartin.aspx"&gt;Hanselminutes episode on SOLID&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Scott Bellware's post on &lt;a href="http://blog.scottbellware.com/2009/01/good-design-is-easily-learned.html"&gt;Good Design is Easily-Learned&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Laila Bougria's post on &lt;a href="http://www.noctovis.net/blog/index.php/2009/01/15/design-principles/"&gt;Design Principles&lt;/a&gt;, including SOLID&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;References&lt;/h2&gt;
&lt;p&gt;
[1] Yammer exchange with &lt;a href="http://www.xerxesb.com/"&gt;Xerxes&lt;/a&gt;
&lt;br/&gt;
[2] Bertrand Meyer, &lt;a href="http://www.amazon.com/Object-Oriented-Software-Construction-Prentice-Hall-International"&gt;Object-Oriented Software Construction&lt;/a&gt;
&lt;br/&gt;
[3] Gene Shadrin, &lt;a href="http://java.sys-con.com/node/84633/print"&gt;Three Sources of a Solid Object-Oriented Design&lt;/a&gt;, SYS-CON Media Inc.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-5616194819787817713?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=QDpZhj_IPhs:NyKgCICluTg:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=QDpZhj_IPhs:NyKgCICluTg:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=QDpZhj_IPhs:NyKgCICluTg:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=QDpZhj_IPhs:NyKgCICluTg:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=QDpZhj_IPhs:NyKgCICluTg:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=QDpZhj_IPhs:NyKgCICluTg:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/QDpZhj_IPhs" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/5616194819787817713/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=5616194819787817713" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/5616194819787817713?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/5616194819787817713?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2009/01/introduction-to-solid-principles-of-oo.html" title="An introduction to the SOLID principles of OO design" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;DEMCRno5fCp7ImA9WxRbGE8.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-8100562135462992208</id><published>2008-12-09T23:15:00.006+11:00</published><updated>2008-12-09T23:41:07.424+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-09T23:41:07.424+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="misc" /><title>Happy 2nd Blogoversary</title><content type="html">&lt;p&gt;In a couple of days I will have been &lt;a href="http://davesquared.blogspot.com/2006/12/first-post.html"&gt;blogging for two years&lt;/a&gt;. Please excuse a little self-indulgence on my part while I go through the usual blogoversary formalities.&lt;/p&gt;

&lt;h2&gt;Some random statistics&lt;/h2&gt;
&lt;p&gt;Most of this is from Google Analytics, which should be a semi-decent approximation to reality.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;264 posts&lt;/li&gt;
&lt;li&gt;Around 130 valued feed subscribers (including some which aren't just me subscibing from different PCs). :)&lt;/li&gt;
&lt;li&gt;Over 30,000 visits and over 40,000 page views since August 2007. Most recently there's been about 3,000 visits a month. Not a huge amount, but probably more than this little blog warrants. :)&lt;/li&gt;
&lt;li&gt;Busiest day:  768 visits  on 3rd April 2008, thanks to a &lt;a href="http://davesquared.blogspot.com/2008/03/99-problems-with-python-1-10.html"&gt;Reddited Python post&lt;/a&gt;.
&lt;li&gt;Browser usage: Firefox 50%, IE 42%, Opera, Chrome and Safari around 2% each.&lt;/li&gt;
&lt;li&gt;OS usage: Windows 92%, Mac 4%, Linux ~4%&lt;/li&gt;
&lt;li&gt;17 visits from iPhones. Apparently one from an HPUX :)&lt;/li&gt;
&lt;li&gt;262 visits from Microsoft.&lt;/li&gt;
&lt;li&gt;Visits from 141 countries, with most from US, UK, India, Australia and Canada. Slightly less visits from Gibraltar, Maldives, Liechtenstein, and Madagascar :)&lt;/li&gt;
&lt;li&gt;Search engine stats: Google 99.36%. Yahoo came second. I'm guessing Blogger.com bias. :)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Most visited posts&lt;/h2&gt;
&lt;p&gt;The Python and ORM posts were due to unsolicited Redditing and DotNetKicking. The others care of Google.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/03/99-problems-with-python-1-10.html"&gt;99 problems with Python (1-10)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2007/10/confirm-delete-for-gridview.html"&gt;Confirm delete for GridView's CommandField using JavaScript&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/01/viewing-sql-generated-by-nhibernate.html"&gt;Viewing the SQL generated by NHibernate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2007/12/messing-around-with-various-orms.html"&gt;Messing around with various ORMs (series)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Posts I like but no one visited :)&lt;/h2&gt;
&lt;p&gt;Proving once and for all that just because you build it doesn't mean that they will come.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2007/06/explaining-good-code-to-non-geeks.html"&gt;Explaining good code to non-geeks&lt;/a&gt;. After reading this interested family members started to grok what I do for a living :)&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/01/python-like-range-implementation-in-c.html"&gt;Implementing Python-like Range in C#&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2007/10/fluently-constructing-test-objects.html"&gt;Fluently constructing test objects&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/05/bdd-test-naming-with-autohotkey.html"&gt;BDD test naming with AutoHotKey&lt;/a&gt;. Picked up by the legendary &lt;a href="http://blog.jpboodhoo.com/BDDAutoHotKeyScriptUpdateTake1.aspx"&gt;JP Boodhoo&lt;/a&gt;. Yes, I'm blushing :)&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/06/yet-another-way-of-raising-events-from.html"&gt;Yet another way of raising events from mocks&lt;/a&gt;, which ended up getting into Rhino Mocks 3.5.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/09/nhibernate-mappings-using-xml.html"&gt;NHibernate mappings using xml, attributes, and Fluent NHibernate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/06/attempting-to-understand-dependency.html"&gt;Attempting to understand dependency injection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/04/assortment-of-basic-tdd-tips.html"&gt;An assortment of basic TDD tips&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2007/10/getting-to-grips-with-resharper.html"&gt;Getting to grips with ReSharper&lt;/a&gt;. Bit old but still reasonably relevant.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://davesquared.blogspot.com/2008/10/from-delegates-to-lambdas-in-c.html"&gt;Learning C# lambda syntax from delegates&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Where to from here?&lt;/h2&gt;

&lt;p&gt;The purpose of my blog remains the &lt;a href="http://davesquared.blogspot.com/2007/11/happy-anniversary-to-me.html"&gt;same as last year&lt;/a&gt;: a way of helping me learn stuff. I still find blogging to be one of the best ways for me to solidify a concept in my mind.&lt;/p&gt;

&lt;p&gt;I've found with my new job (~5 months) I've been doing tonnes of coding in an Agile, TDD-toting team, and so a lot of my time and learning goes on there. My work also has an enormous library of text books which I've been working through, and I'm also tending (with the exception of this post :)) to be a bit more selective about what I post, so a lot of my Frankenstein-like learning experiments never see the light of a browser. All this has made my blog a bit quieter of late, but hopefully this has meant a higher signal-to-noise ratio over the last couple of months.&lt;/p&gt;

&lt;p&gt;Thanks to everyone that's subscribed, commented, or visited my little patch of the intraweb -- it's great to think that my ramblings occasionally help out. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-8100562135462992208?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=pl2DU06T_Ho:-YDjEWdMTFE:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=pl2DU06T_Ho:-YDjEWdMTFE:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=pl2DU06T_Ho:-YDjEWdMTFE:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=pl2DU06T_Ho:-YDjEWdMTFE:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=pl2DU06T_Ho:-YDjEWdMTFE:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=pl2DU06T_Ho:-YDjEWdMTFE:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/pl2DU06T_Ho" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/8100562135462992208/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8100562135462992208" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8100562135462992208?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8100562135462992208?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/12/happy-2nd-blogoversary.html" title="Happy 2nd Blogoversary" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">6</thr:total></entry><entry gd:etag="W/&quot;CkYMQ3g8eSp7ImA9WxRbGE8.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-2360363044446555694</id><published>2008-12-02T12:03:00.006+11:00</published><updated>2008-12-09T21:56:22.671+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-09T21:56:22.671+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><title>System.BadImageFormatException on 64-bit OS</title><content type="html">&lt;p&gt;I got the following exception when running the unit tests as part of a local build of our .NET project today:&lt;/p&gt;

&lt;pre&gt;System.BadImageFormatException : Could not load file or assembly '&lt;i&gt;(assembly name)&lt;/i&gt;' or one of its dependencies. 
An attempt was made to load a program with an incorrect format.&lt;/pre&gt;

&lt;p&gt;This seemed a bit odd, because the build was working on every other machine. Even odder, the build and tests ran fine within Visual Studio.&lt;/p&gt;

&lt;p&gt;Turns out this occurs when the CLR tries to load an assembly that contains unmanaged code built targeting a different platform. In my case, I was running it on my new machine which has 64-bit Vista, but one of the referenced assemblies contained native code compiled targeting x86. It was running fine in Visual Studio because VS is a 32-bit app, and so was calling everything in 32-bit mode via &lt;a href="http://en.wikipedia.org/wiki/WOW64"&gt;WoW64&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The solution? Build both 32-bit and 64-bit versions of the assembly causing the problem, or force our project to always run in 32-bit mode (within WoW64 on x64 machines) by specifically setting the platform target to x86 in the Visual Studio project build options (by default this is set to &amp;quot;Any CPU&amp;quot;).&lt;/p&gt;

&lt;p&gt;Hope this saves someone some hair-tearing. :)&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Update:&lt;/b&gt; I have found the &lt;a href="http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx"&gt;Corflags&lt;/a&gt; tool invaluable for flagging a DLL as needing to run under the 32 bit CLR. This is useful when you don't have the source to recompile the app, and has been put to good use getting the old, free version of &lt;a href="http://rabdullin.com/journal/2008/6/6/how-to-run-free-ncover-on-a-64-bit-machine.html"&gt;NCover to run on a 64-bit bit OS&lt;/a&gt;. A good write up on Corflags is &lt;a href="http://blogs.msdn.com/joshwil/archive/2005/05/06/415191.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;References:&lt;/b&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://forums.microsoft.com/msdn/showpost.aspx?postid=665884&amp;siteid=1"&gt;MSDN thread on this error with an EF pre-release&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-2360363044446555694?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qzgEjUHNOJ0:IyyzejaoV24:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=qzgEjUHNOJ0:IyyzejaoV24:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qzgEjUHNOJ0:IyyzejaoV24:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qzgEjUHNOJ0:IyyzejaoV24:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=qzgEjUHNOJ0:IyyzejaoV24:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=qzgEjUHNOJ0:IyyzejaoV24:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/qzgEjUHNOJ0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/2360363044446555694/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=2360363044446555694" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2360363044446555694?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2360363044446555694?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/12/systembadimageformatexception-on-64-bit.html" title="System.BadImageFormatException on 64-bit OS" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;DkABQ3Y7eSp7ImA9WxRUFks.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-4324217738947167040</id><published>2008-11-26T12:30:00.002+11:00</published><updated>2008-11-26T12:59:12.801+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-11-26T12:59:12.801+11:00</app:edited><title>Bookmarklet to get commit message for JIRA integration</title><content type="html">&lt;p&gt;At my work we use JIRA for issue tracking, and the &lt;a href="http://confluence.atlassian.com/display/JIRAEXT/FishEye+for+JIRA"&gt;FishEye&lt;/a&gt; plugin to integrate with our source control system. This means that for each commit against an issue we need to start our commit message with details of the issue so that JIRA/FishEye can pick it up. For example:&lt;/p&gt;

&lt;pre&gt;DAVE-1234 (Pairing with Dave is annoying)

* Updated code to crash while Dave is around, so pairing can finish.
&lt;/pre&gt;

&lt;p&gt;Here &amp;quot;DAVE-1234&amp;quot; is the issue number, and &amp;quot;Pairing with Dave is annoying&amp;quot; is the issue title. Speaking of annoying, it was becoming so to copy and paste the issue number and title from the issue's JIRA page, as the values do not appear together in our current page template. So I thought I would write up a bit of javascript to parse the details directly from the JIRA page. Yes, I would be better off getting the page template updated, but I've been intending to do that for weeks, so horrible-javascript-hack-over-lunch it is. :)&lt;/p&gt;

&lt;p&gt;The title of the JIRA page for an issue has all the information we need:&lt;/p&gt;

&lt;pre&gt;[#DAVE-1234] Pairing with Dave is annoying - Your JIRA Instance Name&lt;/pre&gt;

&lt;p&gt;You can hackily parse this using javascript:&lt;/p&gt;

&lt;pre&gt;
var title = document.title;

var endOfIssueKeyIndex = title.indexOf(&amp;quot;]&amp;quot;);
var endOfIssueNameIndex = title.lastIndexOf(&amp;quot; - &amp;quot;);
var issueKey = title.substring(&amp;quot;[#&amp;quot;.length, endOfIssueKeyIndex);
var issueName = title.substring(endOfIssueKeyIndex + &amp;quot;] &amp;quot;.length, endOfIssueNameIndex);

window.alert(issueKey + &amp;quot; (&amp;quot; + issueName + &amp;quot;)&amp;quot;);
&lt;/pre&gt;

&lt;p&gt;If you prefix that with &lt;code&gt;javascript:&lt;/code&gt; and copy and paste it into the location field of a FireFox bookmark, you can click on the bookmark to throw up an alert containing the text formatted as required (this will probably work on other browsers with a little tweaking as well). You can then CTRL+A to select the text and CTRL-C to copy it. If you put the bookmark on your FireFox bookmarks toolbar this almost becomes useful. :)&lt;/p&gt;

&lt;p&gt;FireFox reformats the bookmark location automatically, but here is what you end up with for completeness' sake:&lt;/p&gt;

&lt;pre&gt;
javascript:var%20title%20=%20document.title;%20%20var%20endOfIssueKeyIndex%20=%20title.indexOf("]");%20var%20endOfIssueNameIndex%20=%20title.lastIndexOf("%20-%20");%20var%20issueKey%20=%20title.substring("[#".length,%20endOfIssueKeyIndex);%20var%20issueName%20=%20title.substring(endOfIssueKeyIndex%20+%20"]%20".length,%20endOfIssueNameIndex);%20%20window.alert(issueKey%20+%20"%20("%20+%20issueName%20+%20")");
&lt;/pre&gt;

&lt;p&gt;It's also possible to get javascript to copy this directly to your clipboard, but it takes a bit more mucking around. It will obviously stuff up if your JIRA title is in a different format, or if you go around running it on arbitrary web pages :), but it &lt;a href="http://www.codinghorror.com/blog/archives/000818.html"&gt;works on my machine&lt;/a&gt; -- hope it works on yours too! :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-4324217738947167040?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=CX5C_BzcfTc:VTuxcWbcAf0:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=CX5C_BzcfTc:VTuxcWbcAf0:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=CX5C_BzcfTc:VTuxcWbcAf0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=CX5C_BzcfTc:VTuxcWbcAf0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=CX5C_BzcfTc:VTuxcWbcAf0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=CX5C_BzcfTc:VTuxcWbcAf0:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/CX5C_BzcfTc" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/4324217738947167040/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=4324217738947167040" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4324217738947167040?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4324217738947167040?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/11/bookmarklet-to-get-commit-message-for.html" title="Bookmarklet to get commit message for JIRA integration" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total></entry><entry gd:etag="W/&quot;DEcCQXw8fip7ImA9WxRWEUQ.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-108783555430829477</id><published>2008-10-28T22:53:00.003+11:00</published><updated>2008-10-28T23:14:20.276+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-10-28T23:14:20.276+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="tdd" /><title>Unusual formatting with test-first extension method abuse</title><content type="html">&lt;p&gt;My pair and I were looking at performing some unusual string formatting today. We kept finding that the extension methods in &lt;code&gt;System.Linq.Enumerable&lt;/code&gt; were pretty helpful, but they often seemed to &lt;a href="http://davesquared.blogspot.com/2008/03/ienumerable-and-foreach.html"&gt;fall just short&lt;/a&gt; of what we needed to make the code really readable. Once I got home I thought I'd see how far I'd get by dumping some functionality into extension methods with blatant disregard for the potential consequences. (Unfortunately I had to miss the &lt;a href="http://sydneyaltdotnet.blogspot.com/"&gt;Sydney ALT.NET&lt;/a&gt; meeting tonight, so I had a bit of time to play around.)&lt;/p&gt;

&lt;h2&gt;Formatting arrays for acceptance tests&lt;/h2&gt;
&lt;p&gt;Here is the basic behaviour we're after. Given an array or other enumerable of integers (or of any type with a sensible &lt;code&gt;ToString()&lt;/code&gt; method really), we want to return the items as a single, comma separated string. The strange part of it is that if every value in the enumeration is the same, we just want to return that one value as a single string. The reason for this unusual behaviour is to help get some easily usable output for the acceptance test framework we are using.&lt;/p&gt;

&lt;p&gt;As this is just a helper for acceptance tests (i.e. we won't be polluting namespaces in production code) I'll dump this functionality onto any &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; using an extension method. &lt;/p&gt;

&lt;h2&gt;Starting test first&lt;/h2&gt;
&lt;p&gt;Let's start with an easy case: what should happen when we have an empty enumerable?&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class FixtureFormatterTests {
    [Test]
    public void Empty_array_should_format_as_empty_string() {
        var emptyArray = new int[0];
        Assert.That(emptyArray.ToFixtureString(), Is.EqualTo(string.Empty));
    }
} 

public static class HelperExtensions {
 public static string ToFixtureString&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
   return string.Empty;
 }
} 
&lt;/pre&gt;

&lt;p&gt;After that monumentally brilliant piece of code, let's add the comma-separated string part of the requirement.&lt;/p&gt;

&lt;pre&gt;
[Test]
public void Array_with_different_values_should_give_comma_separated_string() {
 var ints = new[] {1, 2, 3, 4};
 Assert.That(ints.ToFixtureString(), Is.EqualTo(&amp;quot;1,2,3,4&amp;quot;));            
}
&lt;/pre&gt;

&lt;p&gt;Now we'll get it to pass. We'll lean heavily on the built-in &lt;code&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/57a79xd0.aspx"&gt;String.Join(String, String[])&lt;/a&gt;&lt;/code&gt; method to do the  work for us.&lt;/p&gt;

&lt;pre&gt;
public static string ToFixtureString&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
 if (enumerable.Count() == 0) return string.Empty;
 return string.Join(&amp;quot;,&amp;quot;, enumerable.Select(item =&amp;gt; item.ToString()).ToArray());
}
&lt;/pre&gt;

&lt;p&gt;This passes, but it's a bit ugly. Let's look at refactoring.&lt;/p&gt;

&lt;h2&gt;First refactoring&lt;/h2&gt;

&lt;p&gt;First, I've got a feeling that if our enumerable is empty, &lt;code&gt;String.Join(...)&lt;/code&gt; won't concatenate anything, and so will just return an empty string. This would render our first line redundant.&lt;/p&gt;

&lt;pre&gt;public static string ToFixtureString&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
 return string.Join(&amp;quot;,&amp;quot;, enumerable.Select(item =&amp;gt; item.ToString()).ToArray());
}&lt;/pre&gt;

&lt;p&gt;It still passes both our tests so we are safe (I love unit tests :)). We also have that ugly bit of code where we are translating our &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; into an array of strings, using the &lt;code&gt;Select()&lt;/code&gt; extension method. As I'm keen to start over using extensions methods, let's hide all that away in a Python-like &lt;code&gt;join()&lt;/code&gt; method. Python's &lt;code&gt;join()&lt;/code&gt; works like this:&lt;/p&gt;

&lt;pre&gt;
&amp;gt;&amp;gt;&amp;gt; ints = [1,2,3,4]
&amp;gt;&amp;gt;&amp;gt; &amp;quot;,&amp;quot;.join(str(i) for i in ints)
'1,2,3,4'
&lt;/pre&gt;

&lt;p&gt;I'd like to do that, but abstract away the sequence/enumerable to string conversion. Let's do this using an extension method to &lt;code&gt;char&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;
public static string Join&lt;T&gt;(this char separator, IEnumerable&lt;T&gt; enumerable) {
 return string.Join(separator.ToString(), enumerable.Select(item =&gt; item.ToString()).ToArray());
}

public static string ToFixtureString&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable) {
 &lt;b&gt;return ','.Join(enumerable);&lt;/b&gt;
}
&lt;/pre&gt;

&lt;p&gt;Assuming you know the whole &amp;quot;Join&amp;quot; concept, our &lt;code&gt;ToFixtureString()&lt;/code&gt; method is now pretty darned clean :). The original ugliness is now moved to the &lt;code&gt;Join()&lt;/code&gt; method, but at least it is all directly related to the purpose of that method. In its original spot I think it obscured the intention behind the &lt;code&gt;ToFixtureString()&lt;/code&gt; method.&lt;/p&gt;

&lt;h2&gt;Completing our &lt;code&gt;ToFixtureString()&lt;/code&gt; requirements&lt;/h2&gt;

&lt;p&gt;The last requirement we have for this is to only show one value if all the items in the enumerable are the same.&lt;/p&gt;

&lt;pre&gt;
[Test]
public void Array_with_the_same_values_should_return_that_value_as_a_single_string() {
 const int value = 2;
 var ints = new[] {value, value, value};
 Assert.That(ints.ToFixtureString(), Is.EqualTo(value.ToString()));
}
&lt;/pre&gt;

&lt;p&gt;Here's an attempt at get this to pass.&lt;/p&gt;

&lt;pre&gt;
public static string ToFixtureString&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
 &lt;b&gt;var firstItem = enumerable.First();
 if (enumerable.All(item =&amp;gt; item.Equals(firstItem)))
 {
  return firstItem.ToString();
 }&lt;/b&gt;
 return ','.Join(enumerable);
}
&lt;/pre&gt;

&lt;p&gt;This fails our &lt;code&gt;Empty_array_should_format_as_empty_string&lt;/code&gt; test because the &lt;code&gt;enumerable.First()&lt;/code&gt; call throws with &lt;code&gt;InvalidOperationException: Sequence contains no elements&lt;/code&gt;. So we're back to that &lt;code&gt;enumerable.Count() == 0&lt;/code&gt; line, which gets all our tests passing again.&lt;/p&gt;

&lt;pre&gt;
public static string ToFixtureString&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
 &lt;b&gt;if (enumerable.Count() == 0) return string.Empty;&lt;/b&gt;
 var firstItem = enumerable.First();
 if (enumerable.All(item =&amp;gt; item.Equals(firstItem)))
 {
  return firstItem.ToString();
 }
 return ','.Join(enumerable);
}
&lt;/pre&gt;


&lt;h2&gt;Refactoring out the empty enumerable check&lt;/h2&gt;

&lt;p&gt;I don't like &lt;code&gt;enumerable.Count()&lt;/code&gt;. It needs to go through the entire enumerator to get the count, when we really only care if the enumerable is empty. Sounds like time for some more extension method abuse. Here's some tests that require adding an &lt;code&gt;IsEmpty()&lt;/code&gt; extension method to &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class IsEmptyEnumerableTests {
 [Test]
 public void Empty_enumerable() {
  Assert.That(new int[0].IsEmpty());
 }

 [Test]
 public void Non_empty_enumerable() {
  Assert.That(new[]{1,2,3}.IsEmpty(), Is.False);
 }
}

public static class HelperExtensions {
 //...  
 &lt;b&gt;public static bool IsEmpty&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
  return !enumerable.GetEnumerator().MoveNext();
 }&lt;/b&gt;
}    
&lt;/pre&gt;

&lt;p&gt;This is a bit hacky, but means we only need to to see if our enumerator has a single item to determine whether it is empty, and we can make our &lt;code&gt;ToFixtureString()&lt;/code&gt; method a bit more expressive as a result:&lt;/p&gt;

&lt;pre&gt;
public static string ToFixtureString&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
 &lt;b&gt;if (enumerable.IsEmpty()) return string.Empty;&lt;/b&gt;
 var firstItem = enumerable.First();
 if (enumerable.All(item =&amp;gt; item.Equals(firstItem))) {
  return firstItem.ToString();
 }
 return ','.Join(enumerable);
}
&lt;/pre&gt;

&lt;h2&gt;Vague semblance of a conclusion&lt;/h2&gt;
&lt;p&gt;We now have our unusual formatting covered, and &lt;code&gt;IsEmpty()&lt;/code&gt; and &lt;code&gt;Join()&lt;/code&gt; extension methods to help make our code a bit cleaner. I'm not advocating this kind of thing for every day use, but I think it shows how useful extension methods can be to make your code more expressive. It comes at the cost of changing classes that most .NET developers are familiar with, so it's definitely something to be careful with.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-108783555430829477?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=ko2SydC3FRM:dKohMAC4cqI:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=ko2SydC3FRM:dKohMAC4cqI:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=ko2SydC3FRM:dKohMAC4cqI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=ko2SydC3FRM:dKohMAC4cqI:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=ko2SydC3FRM:dKohMAC4cqI:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=ko2SydC3FRM:dKohMAC4cqI:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/ko2SydC3FRM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/108783555430829477/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=108783555430829477" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/108783555430829477?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/108783555430829477?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/10/unusual-formatting-with-test-first.html" title="Unusual formatting with test-first extension method abuse" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;A04GR3wzfip7ImA9WxRXFkk.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-1364301814268100847</id><published>2008-10-22T01:21:00.008+11:00</published><updated>2008-10-22T15:32:06.286+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-10-22T15:32:06.286+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><title>Learning C# lambda syntax from delegates</title><content type="html">&lt;p&gt;As a sweeping generalisation, I've found that developers who are really proficient with delegates / anonymous delegates seem to have a bit of an adverse reaction to seeing the &lt;a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx"&gt;lambda syntax in C# .NET 3.5&lt;/a&gt;. Luckily I'm proficient with very little, so the transition was easy for me :). This is a post to try and make the transition easier for people more competent than me :).&lt;/p&gt;

&lt;h2&gt;From delegates to lambdas&lt;/h2&gt;
&lt;p&gt;Say I have a &lt;code&gt;Widget&lt;/code&gt; class, which just contains a &lt;code&gt;Name&lt;/code&gt; and a &lt;code&gt;WeightInGrams&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;
public class Widget {
        public Widget(string name, int weightInGrams) {
            Name = name;
            WeightInGrams = weightInGrams;
        }
        public string Name { get; set; }
        public int WeightInGrams { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;Now we want to search through an array of these and find how many are under 300 grams. Why? Er, why not? We'll use &lt;code&gt;Array.FindAll&lt;/code&gt; to do this old skool (as opposed to fancy LINQy stuff like using &lt;code&gt;Where()&lt;/code&gt;). &lt;code&gt;FindAll&lt;/code&gt; takes an array of type &lt;code&gt;T&lt;/code&gt; and a &lt;code&gt;Predicate&amp;lt;T&amp;gt;&lt;/code&gt;, which is a delegate that takes a &lt;code&gt;T&lt;/code&gt; and returns a &lt;code&gt;bool&lt;/code&gt; indicating whether the predicate has been matched.&lt;/p&gt;

&lt;pre&gt;
[TestFixture]
public class LambdaTests {
 [Test]
 public void SearchArrayUsingDelegate() {
  var widgets = SixWidgetsFrom100GramsTo600Grams();
  var widgets300GramsOrLess = Array.FindAll(widgets, &lt;b&gt;Weighs300GramsOrLess&lt;/b&gt;);
  Assert.That(widgets300GramsOrLess.Length, Is.EqualTo(NumberOfWidgets300GramsOrLess));
 }

 &lt;b&gt;private bool Weighs300GramsOrLess(Widget widget) {
  return widget.WeightInGrams &amp;lt;= 300;
 }&lt;/b&gt;

 private const int NumberOfWidgets300GramsOrLess = 3;
 static Widget[] SixWidgetsFrom100GramsTo600Grams() {
  return new[] {
    new Widget(&amp;quot;W1&amp;quot;, 100), new Widget(&amp;quot;W2&amp;quot;, 200), new Widget(&amp;quot;W3&amp;quot;, 300),
    new Widget(&amp;quot;W4&amp;quot;, 400), new Widget(&amp;quot;W5&amp;quot;, 500), new Widget(&amp;quot;W6&amp;quot;, 600)
     };
 }
} 
&lt;/pre&gt;

&lt;p&gt;As of .NET 2.0 we can use an anonymous delegate to do this inline:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void SearchArrayUsingAnonymousDelegate() {
 var widgets = SixWidgetsFrom100GramsTo600Grams();
 var widgets300GramsOrLess = 
  Array.FindAll(widgets, &lt;b&gt;delegate(Widget widget) { return widget.WeightInGrams &amp;lt;= 300; }&lt;/b&gt;);
 Assert.That(widgets300GramsOrLess.Length, Is.EqualTo(NumberOfWidgets300GramsOrLess));
}
&lt;/pre&gt;

&lt;p&gt;As of .NET 3.5 we have lambda syntax, which provides a terser way of expressing our predicate function:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void SearchArrayUsingLambda() {
 var widgets = SixWidgetsFrom100GramsTo600Grams();
 var widgets300GramsOrLess = 
  Array.FindAll(widgets, &lt;b&gt;widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300&lt;/b&gt;);
 Assert.That(widgets300GramsOrLess.Length, Is.EqualTo(NumberOfWidgets300GramsOrLess));
}
&lt;/pre&gt;

&lt;p&gt;Clear as mud? Let's have a closer look at how we convert from delegate to a lambda expression.&lt;/p&gt;

&lt;pre&gt;
//Original delegate:
delegate(Widget widget) { return widget.WeightInGrams &amp;lt;= 300; }

//Drop the &amp;quot;delegate&amp;quot; keyword, and add a funky &amp;quot;=&amp;gt;&amp;quot; operator, which goes by all sorts of creative names :)
(Widget widget) =&amp;gt; { return widget.WeightInGrams &amp;lt;= 300; }

//The C# 3.0 compiler has type inference, so we can also drop the argument type and let the compiler figure it out.
//If we have a single statement to the right of the &amp;quot;=&amp;gt;&amp;quot; operator, this will be returned from the function,
//so we can also drop the braces, end-of-statement semicolon and the explicit return.
widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300
&lt;/pre&gt;

&lt;p&gt;So what's the difference between our anonymous delegate and our lambda expression? In this example, absolutely nothing other than a terser (and somewhat addictive IMO) syntax. Let's compare the generated code for both just to prove this:&lt;/p&gt;

&lt;pre&gt;
[CompilerGenerated]
private static bool &amp;lt;SearchArrayUsingAnonymousDelegate&amp;gt;b__0(Widget widget) {
    return (widget.WeightInGrams &amp;lt;= 300);
}
[CompilerGenerated]
private static bool &amp;lt;SearchArrayUsingLambda&amp;gt;b__2(Widget widget) {
    return (widget.WeightInGrams &amp;lt;= 300);
}
&lt;/pre&gt;

&lt;p&gt;So based on this example anonymous delegates and lambdas are exactly the same, it's just a matter of getting used to writing a bit less noise code. :)&lt;/p&gt;

&lt;h2&gt;Exactly the same, except when they're different...&lt;/h2&gt;
&lt;p&gt;Of course there's a catch. Actually, I can think of two, and they both relate to &lt;a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx"&gt;expression trees&lt;/a&gt;. To support a lot of LINQ magic, lambda expressions can be converted to expression trees at compile time. An expression tree is basically just a bunch of objects representing each part of the lambda expression. A query provider, like the one provided by LINQ to SQL, can then process the expression tree and execute the expression in a different way, say, by converting it to TSQL and running it against database.&lt;/p&gt;

&lt;p&gt;To get the compiler to generate an expression tree from a lambda expression we just need to specify the type differently:&lt;/p&gt;

&lt;pre&gt;
Predicate&amp;lt;Widget&amp;gt; lambda = widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300;
Expression&amp;lt;Predicate&amp;lt;Widget&amp;gt;&amp;gt; expressionTree = widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300;
&lt;/pre&gt;

&lt;p&gt;So how does this relate to differentiating anonymous delegates and lambdas?&lt;/p&gt;

&lt;pre&gt;
//Compiles fine:
Expression&amp;lt;Predicate&amp;lt;Widget&amp;gt;&amp;gt; expressionTree = &lt;b&gt;widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300&lt;/b&gt;;

//WON'T COMPILE:
Expression&amp;lt;Predicate&amp;lt;Widget&amp;gt;&amp;gt; expressionTree = &lt;b&gt;delegate(Widget widget) { return widget.WeightInGrams &amp;lt;= 300; }&lt;/b&gt;;
&lt;b&gt;/* error CS1946: An anonymous method expression cannot be converted to an expression tree */&lt;/b&gt;

&lt;/pre&gt;

&lt;p&gt;As you can see from the code sample above, the compiler will simply refuse to convert the delegate form to an expression tree. So the way the compiler handles the two are quite different as soon as you introduce expression trees. I also mentioned a second catch. Take a look at this modification of the previous example:&lt;/p&gt;

&lt;pre&gt;
//WON'T COMPILE:
Expression&amp;lt;Predicate&amp;lt;Widget&amp;gt;&amp;gt; expressionTree = &lt;b&gt;widget =&amp;gt; { return widget.WeightInGrams &amp;lt;= 300; }&lt;/b&gt;;
&lt;b&gt;/*  error CS0834: A lambda expression with a statement body cannot be converted to an expression tree */&lt;/b&gt;
&lt;/pre&gt;

&lt;p&gt;This second catch is that there is actually a &lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/18/expressions-and-lambdas.aspx"&gt;difference between lambda &lt;b&gt;expressions&lt;/b&gt; and lambda &lt;b&gt;statements&lt;/b&gt;&lt;/a&gt;. A lambda statement contains braces and a function body, and can potentially have multiple lines like a standard delegate. A lambda expression is the single line with an implicit return. So in our original, Array-searching example, the following two statements are actually are different if you are trying to assign them to expression trees.&lt;/p&gt;

&lt;pre&gt;
//Lambda statement
widget =&amp;gt; { return widget.WeightInGrams &amp;lt;= 300; }

//Lambda expression
widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300
&lt;/pre&gt;

&lt;div class="note"&gt;
&lt;p&gt;&lt;b&gt;Aside:&lt;/b&gt; In case you were wondering, here is the expression tree generated by the compiler for the &lt;code&gt;widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300&lt;/code&gt; lambda expression, care of Reflector:&lt;/p&gt;

&lt;pre&gt;
ParameterExpression CS$0$0000;
Expression&amp;lt;Predicate&amp;lt;Widget&amp;gt;&amp;gt; expressionTree = 
  Expression.Lambda&amp;lt;Predicate&amp;lt;Widget&amp;gt;&amp;gt;(
 Expression.LessThanOrEqual(
  Expression.Property(
   CS$0$0000 = Expression.Parameter(typeof(Widget), &amp;quot;widget&amp;quot;), 
   (MethodInfo) methodof(Widget.get_WeightInGrams)), 
   Expression.Constant(300, typeof(int))), 
   new ParameterExpression[] { CS$0$0000 }
  );
&lt;/pre&gt;
&lt;/div&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;So in conclusion, lambdas are simply, for most intents and purposes, a neater syntax for defining delegates.&lt;/p&gt;

&lt;pre&gt;
//Delegate:
delegate(Widget widget) { return widget.WeightInGrams &amp;lt;= 300; }

//Drop the delegate and add the &amp;quot;=&amp;gt;&amp;quot; operator to get a lambda statement
(Widget widget) =&amp;gt; { return widget.WeightInGrams &amp;lt;= 300; }

//Use type inference and implicit return to get a lambda expression
widget =&amp;gt; widget.WeightInGrams &amp;lt;= 300
&lt;/pre&gt;

&lt;p&gt;The only differences that can bite you are when you are dealing with expression trees, either explicitly via the &lt;code&gt;Expression&amp;lt;&amp;gt;&lt;/code&gt; type, or implicitly by using the LINQ operators. Hope this helps, or at least has caused no significant damage to your understanding of lambdas :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-1364301814268100847?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=L1MVEmQWLbU:r7pPiIJpwBw:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=L1MVEmQWLbU:r7pPiIJpwBw:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=L1MVEmQWLbU:r7pPiIJpwBw:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=L1MVEmQWLbU:r7pPiIJpwBw:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=L1MVEmQWLbU:r7pPiIJpwBw:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=L1MVEmQWLbU:r7pPiIJpwBw:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/L1MVEmQWLbU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/1364301814268100847/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=1364301814268100847" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/1364301814268100847?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/1364301814268100847?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/10/from-delegates-to-lambdas-in-c.html" title="Learning C# lambda syntax from delegates" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;DEUCQHg7cSp7ImA9WxVRFU4.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-4204873532475900853</id><published>2008-10-01T23:16:00.022+10:00</published><updated>2009-01-21T22:11:01.609+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-21T22:11:01.609+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="testing" /><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title>The (very) basics of AAA with Rhino Mocks 3.5</title><content type="html">&lt;p&gt;A small contingent from my work made the trek out to the first &lt;a href="http://sydneyaltdotnet.blogspot.com/"&gt;Sydney ALT.NET&lt;/a&gt; meeting last night. It was great to be in a room full of people all intent on finding better ways to develop software. Afterward I was dragged kicking and screaming (&lt;code&gt;&amp;lt;/sarcasm&amp;gt;&lt;/code&gt; :)) by my colleagues to a local pub for debriefing over beers and a laptop. One topic discussed was the Arrange, Act, Assert (AAA) style of mocking using &lt;a href="http://ayende.com/Blog/archive/2008/05/16/Rhino-Mocks-3.5-Beta-Released.aspx"&gt;Rhino Mocks 3.5&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I thought I'd quickly run through my (admittedly basic) understanding of AAA, as I tend to use a slightly different approach to the one shown in the meeting. If I've got anything hideously wrong please leave a comment and let me know. I'm not going to cover anything about how to use mocking, but will just attempt to outline the difference between record/replay and AAA.&lt;/p&gt;

&lt;h2&gt;Record / Replay semantics&lt;/h2&gt;

&lt;p&gt;The traditional way of mocking has been to use record/replay. This means you &lt;i&gt;record&lt;/i&gt; a number of expectations against a mock object, then change the mock to &lt;i&gt;replay&lt;/i&gt; mode and exercise the subject under test (SUT). In replay mode, the mock will throw an exception if an unexpected method is called (for strict mocks). The final step is to &lt;i&gt;verify&lt;/i&gt; the expectations you recorded, which will throw an exception if one of the expected methods was not called.&lt;/p&gt;

&lt;p&gt;Let's have a look at one of my dodgy-as-usual examples (probably even worse than normal, as it was written in a pub around 11 pm after a long day :))&lt;/p&gt;

&lt;pre&gt;
public interface IEmailService {
    void Send(MailMessage msg);
}

public class InvoiceSender {
    private readonly IEmailService emailService;
    public InvoiceSender(IEmailService emailService) {
        this.emailService = emailService;
    }

    &lt;b&gt;public void SendInvoice(float amount, string to) {
        var msg = new MailMessage(&amp;quot;me@me.com&amp;quot;, to, &amp;quot;Invoice&amp;quot;, string.Format(&amp;quot;Please pay {0}&amp;quot;, amount));
        emailService.Send(msg);
    }&lt;/b&gt;
}
&lt;/pre&gt;

&lt;p&gt;Our subject under test is &lt;code&gt;InvoiceSender&lt;/code&gt;, and we want to verify that the &lt;code&gt;IEmailService.Send(MailMessage)&lt;/code&gt; method is being called from &lt;code&gt;SendInvoice(float, string)&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;
[Test]
public void Send_invoice_using_email_service_with_record_replay() {
 var mockRepo = new MockRepository();
 var mockEmailer = mockRepo.DynamicMock&amp;lt;IEmailService&amp;gt;();            
 var invoiceSender = new InvoiceSender(mockEmailer); 
 //Record expecations
 mockEmailer.Expect(service =&amp;gt; service.Send(null)).IgnoreArguments() ; 
 mockRepo.ReplayAll();
 //Exercise SUT
 invoiceSender.SendInvoice(1.0F, &amp;quot;me@me.com&amp;quot;);  
 //Verify expectations
 mockRepo.VerifyAll();            
}
&lt;/pre&gt;

&lt;p&gt;Here we've used Rhino Mocks to generate a mock implementation of the &lt;code&gt;IEmailService&lt;/code&gt; interface. We have recorded a single expectation against it: it is expecting to have its &lt;code&gt;Send(...)&lt;/code&gt; method called with any argument (hence the &lt;code&gt;IgnoreArguments()&lt;/code&gt; call -- for non-pub code we would probably want to check the argument).&lt;/p&gt;

&lt;p&gt;We then use &lt;code&gt;ReplayAll()&lt;/code&gt; to switch to replay mode, which tells our mocks that we have finished recording expectations and are ready to see what is really called on our mock. We then exercise the SUT, and verify that our expectations were met (i.e. &lt;code&gt;Send()&lt;/code&gt; was called on our mock). The test passes -- victory is ours!&lt;/p&gt;

&lt;h2&gt;Writing the test using AAA&lt;/h2&gt;

&lt;p&gt;There's nothing really wrong with the record/replay approach. If you like it that's great! Some people find it confusing (or at least &lt;a href="http://www.clariusconsulting.net/blogs/kzu/archive/2007/12/26/48177.aspx"&gt;unnatural&lt;/a&gt;), probably because it doesn't quite fit the &lt;a href="http://xunitpatterns.com/Four%20Phase%20Test.html"&gt;four phase test&lt;/a&gt; structure used for state-based testing (Setup, Exercise, Verify, Teardown).&lt;/p&gt;

&lt;p&gt;The AAA approach lets us use a more state-based testing approach with our mocks. Let's rewrite our previous test using AAA:&lt;/p&gt;

&lt;pre&gt;
[Test]
public void Send_invoice_using_email_service_with_AAA() {
    //Arrange
    var mockEmail = MockRepository.GenerateMock&amp;lt;IEmailService&amp;gt;();
    var invoiceSender = new InvoiceSender(mockEmail);
    //Act
    invoiceSender.SendInvoice(1.0F, &amp;quot;me@me.com&amp;quot;);
    //Assert
    mockEmail.AssertWasCalled(service =&amp;gt; service.Send(Arg&amp;lt;MailMessage&amp;gt;.Is.Anything)); 
}
&lt;/pre&gt;

&lt;p&gt;Here we are creating our mock using the new static &lt;code&gt;GenerateMock&amp;lt;T&amp;gt;()&lt;/code&gt; method introduced in Rhino Mocks 3.5. We then exercise the SUT with an identical line of code to the one used in the first test. Finally, we assert that the &lt;code&gt;Send()&lt;/code&gt; method on our mock was called as we expected. The test passes -- again we are victorious!&lt;/p&gt;

&lt;p&gt;First couple of things to notice are that we have no mention of recording or replaying expectations, and we've used less lines of code. Our test also fits in with the four phase test structure: Arrange -&amp;gt; Setup, Act -&amp;gt; Exercise, Assert -&amp;gt; Verify, with optional Teardown. This avoids mixing expectations and assertions throughout the test. Depending on your prior experience with record/replay, you might find this easier to read and understand than our first test.&lt;/p&gt;

&lt;p&gt;Under the hood Rhino Mocks is still going off and doing pretty much the same thing as its always done. The static &lt;code&gt;GenerateMock&amp;lt;T&amp;gt;()&lt;/code&gt; method simply creates a dynamic mock already in &lt;i&gt;replay&lt;/i&gt; mode. The mock remembers all calls against it, and we can then use &lt;code&gt;AssertWasCalled()&lt;/code&gt; and other methods to check these calls and make sure the ones we want are there.&lt;/p&gt;

&lt;div class="note"&gt;&lt;b&gt;Aside:&lt;/b&gt; One of the issues raised during the Sydney ALT.NET meeting was &lt;a href="http://martinfowler.com/articles/mocksArentStubs.html"&gt;mocks vs. stubs&lt;/a&gt;. I think AAA makes the distinction a bit more apparent. You'll tend to use a stub during the &lt;i&gt;Arrange&lt;/i&gt; part of your test to provide indirect inputs to the SUT, whereas you will use mocks to verify behaviour and indirect outputs of the SUT during the &lt;i&gt;Assert&lt;/i&gt; phase. From the &lt;a href="http://ayende.com/wiki/Rhino+Mocks+3.5.ashx#Thedifferencebetweenstubsandmocks"&gt;Rhino Mocks wiki page on 3.5&lt;/a&gt; (&lt;a href="http://ayende.com/wiki/History.aspx?Page=Rhino+Mocks+3.5&amp;Revision=40#Thedifferencebetweenstubsandmocks"&gt;rev. 40&lt;/a&gt;), &amp;quot;A stub will never cause a test to fail&amp;quot;, whereas mocks will fail if the expectations on them aren't met.&lt;/div&gt;

&lt;p&gt;This is only a very simplistic example to illustrate the basic differences for each approach. For more realistic cases the benefits of AAA become more apparent (see &lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/24/arrange-act-assert-and-bdd-specifications.aspx"&gt;Jimmy Bogard's post on AAA with BDD tests&lt;/a&gt; for a good example).&lt;/p&gt;

&lt;p&gt;These couple of lines of code are available from my Google Code repository if you want run the tests and have a bit of a play around: &lt;a href="http://davesquared.googlecode.com/files/DaveSquared.MockSample.zip"&gt;DaveSquared.MockSample.zip&lt;/a&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-4204873532475900853?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=E29X5IqqP74:F1yeYpUNvIA:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=E29X5IqqP74:F1yeYpUNvIA:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=E29X5IqqP74:F1yeYpUNvIA:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=E29X5IqqP74:F1yeYpUNvIA:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=E29X5IqqP74:F1yeYpUNvIA:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=E29X5IqqP74:F1yeYpUNvIA:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/E29X5IqqP74" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/4204873532475900853/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=4204873532475900853" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4204873532475900853?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4204873532475900853?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/10/very-basics-of-aaa-with-rhino-mocks-35.html" title="The (very) basics of AAA with Rhino Mocks 3.5" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;A04AQno-eip7ImA9WxRTGU8.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-3400512368792120207</id><published>2008-09-09T13:04:00.000+10:00</published><updated>2008-09-09T13:12:23.452+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-09-09T13:12:23.452+10:00</app:edited><title>Sydney ALT.NET group</title><content type="html">&lt;p&gt;Just wanted to quickly pass on the &lt;a href="http://sydneyaltdotnet.blogspot.com/2008/08/welcome-to-sydney-altnet-group.html"&gt;announcement&lt;/a&gt; that a &lt;a href="http://sydneyaltdotnet.blogspot.com/"&gt;Sydney ALT.NET group&lt;/a&gt; is starting up. &lt;a href="http://sydneyaltdotnet.blogspot.com/2008/09/sydney-altnet-first-meeting-will-be.html"&gt;First meeting&lt;/a&gt; is at the Thoughtworks office in the city on 30th September.&lt;/p&gt;

&lt;p&gt;Hopefully this will do well -- I'd love a group in Sydney where we can focus on software development practices in .NET, with specific tools and technologies taking a bit of a back seat.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-3400512368792120207?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=a5_MmI38H4M:mhQCq9Tbzzc:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=a5_MmI38H4M:mhQCq9Tbzzc:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=a5_MmI38H4M:mhQCq9Tbzzc:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=a5_MmI38H4M:mhQCq9Tbzzc:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=a5_MmI38H4M:mhQCq9Tbzzc:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=a5_MmI38H4M:mhQCq9Tbzzc:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/a5_MmI38H4M" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/3400512368792120207/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=3400512368792120207" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3400512368792120207?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3400512368792120207?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/09/sydney-altnet-group.html" title="Sydney ALT.NET group" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;D0ABQnwyfip7ImA9WxRTFU4.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-7663679128509581313</id><published>2008-09-04T23:25:00.006+10:00</published><updated>2008-09-04T23:42:33.296+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-09-04T23:42:33.296+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="tools" /><category scheme="http://www.blogger.com/atom/ns#" term="orm" /><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="nhibernate" /><title>NHibernate mappings using xml, attributes, and Fluent NHibernate</title><content type="html">&lt;p&gt;A few of us at work have been looking at NHibernate 2.0 as a potential ORM tool for our next project. The initial reactions have included (but weren't limited to) shudders of horror at seeing the mass of angle brackets present in the &lt;code&gt;.hbm.xml&lt;/code&gt; mapping files. I don't think this reaction is atypical -- I thought the same thing when I first tried NHibernate. However once I started using it (not for anything serious mind you, just for personal projects. I'm at pre-newbie stage still :)), I found the XML relatively painless. In fact once I'd set them up initially it was great to be able to deal with ordinary POCO (Plain Old C# Object) classes and only think about the persistence mappings when tweaking the DB.&lt;/p&gt;

&lt;p&gt;That said, there are alternatives hand coding the &lt;code&gt;.hbm.xml&lt;/code&gt; mapping files. I thought I'd cover a few of the options here: NHibernate Mapping Attributes, and Fluent NHibernate.&lt;/p&gt;

&lt;h2&gt;Getting started&lt;/h2&gt; 
&lt;p&gt;I decided to reuse the extra-simple scenario from my &lt;a href="http://davesquared.blogspot.com/2007/12/messing-around-with-nhibernate.html"&gt;ORM roundup&lt;/a&gt; posts. I have a table of suppliers, and a table of states (or provinces, territories, prefectures etc.). Both suppliers and states have names, which are stored as strings/varchars, and IDs, which are stored as Guids/uniqueidentifiers. Each supplier can service many states. So we have a simple many-to-many relationship between the two main entities. It looks a bit like this:&lt;/p&gt; 

&lt;p&gt;&lt;a href="http://bp0.blogger.com/_wEsHWMWy090/R2n9HuaPYDI/AAAAAAAAAfs/04T6Bg6e7mY/s1600-h/SampleSupplierSchema.png"&gt;&lt;img id="BLOGGER_PHOTO_ID_5145922358406504498" style="cursor: pointer" alt="" src="http://bp0.blogger.com/_wEsHWMWy090/R2n9HuaPYDI/AAAAAAAAAfs/04T6Bg6e7mY/s400/SampleSupplierSchema.png" border="0"&gt;&lt;/a&gt;&lt;/p&gt; 

&lt;p&gt;Now let's create some POCOs for to model our suppliers and states. I've added these to an Entities folder in an otherwise blank C# Class Library project.&lt;/p&gt;

&lt;pre&gt;
//State.cs
using System;
namespace Workshop.Entities {    
    public class State {
        public virtual Guid StateId { get; set; }        
        public virtual String Name { get; set; }
    }
}
//Supplier.cs
using System;
using System.Collections.Generic;
namespace Workshop.Entities {
    public class Supplier {
        private IList&amp;lt;State&amp;gt; statesServiced = new List&amp;lt;State&amp;gt;();
        
        public virtual Guid SupplierId { get; set; }
        public virtual String Name { get; set; }
        public virtual IList&amp;lt;State&amp;gt; StatesServiced { get { return statesServiced; } set { statesServiced = value; } }
    }
}
&lt;/pre&gt;

&lt;p&gt;These are nice ordinary classes, with no consideration given as to how they will be persisted. The only concession we have made is making everything &lt;code&gt;virtual&lt;/code&gt; by default, so that it is easy for NHibernate to create proxies from these classes.&lt;/p&gt;

&lt;p&gt;I'll also throw in an App.config so NHibernate knows which database to talk to. This time around I'm using NHibernate 2.0, which has a &lt;a href="http://davesquared.blogspot.com/2008/08/configuration-changes-in-nhibernate-20.html"&gt;new configuration format&lt;/a&gt; from the last time I looked at this example.&lt;/p&gt;

&lt;h2&gt;Hand coding Hibernate Mapping Files&lt;/h2&gt;

&lt;p&gt;Time to map our entity classes to our database. Let's start off with the standard, hand coded &lt;code&gt;.hbm.xml&lt;/code&gt; approach. We'll create a &lt;code&gt;State.hbm.xml&lt;/code&gt; file and a &lt;code&gt;Supplier.hbm.xml&lt;/code&gt; file to hold our mappings. We'll also set these files to be compiled in as embedded resources so we can get NHibernate to load the mappings from our DLL (in VS, right click the files in the Solution Explorer and edit the Build Action property).&lt;/p&gt;

&lt;pre&gt;
&amp;lt;!-- State.hbm.xml --&amp;gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;hibernate-mapping xmlns=&amp;quot;urn:nhibernate-mapping-2.2&amp;quot; assembly=&amp;quot;Workshop&amp;quot; namespace=&amp;quot;Workshop.Entities&amp;quot;&amp;gt;
  &amp;lt;class name=&amp;quot;State&amp;quot; table=&amp;quot;State&amp;quot;&amp;gt;
    &amp;lt;id name=&amp;quot;StateId&amp;quot; type=&amp;quot;guid&amp;quot;&amp;gt;
      &amp;lt;generator class=&amp;quot;guid&amp;quot; /&amp;gt;
    &amp;lt;/id&amp;gt;
    &amp;lt;property name=&amp;quot;Name&amp;quot; type=&amp;quot;String&amp;quot; /&amp;gt;
  &amp;lt;/class&amp;gt;
&amp;lt;/hibernate-mapping&amp;gt;

&amp;lt;!-- Supplier.hbm.xml --&amp;gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;hibernate-mapping xmlns=&amp;quot;urn:nhibernate-mapping-2.2&amp;quot; assembly=&amp;quot;Workshop&amp;quot; namespace=&amp;quot;Workshop.Entities&amp;quot;&amp;gt;
  &amp;lt;class name=&amp;quot;Supplier&amp;quot; table=&amp;quot;Supplier&amp;quot;&amp;gt;
    &amp;lt;id name=&amp;quot;SupplierId&amp;quot; type=&amp;quot;guid&amp;quot;&amp;gt;
      &amp;lt;generator class=&amp;quot;guid&amp;quot; /&amp;gt;
    &amp;lt;/id&amp;gt;
    &amp;lt;property name=&amp;quot;Name&amp;quot; type=&amp;quot;String&amp;quot; /&amp;gt;
    &amp;lt;bag name=&amp;quot;StatesServiced&amp;quot; table=&amp;quot;Supplier_StatesServiced&amp;quot;&amp;gt;
      &amp;lt;key column=&amp;quot;SupplierId&amp;quot; /&amp;gt;
      &amp;lt;many-to-many column=&amp;quot;StateId&amp;quot; class=&amp;quot;State&amp;quot; /&amp;gt;
    &amp;lt;/bag&amp;gt;
  &amp;lt;/class&amp;gt;
&amp;lt;/hibernate-mapping&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Here we are just telling NHibernate how to map each bit of entity data to the database schema. The HBM files include which main table is used to persist each entity, describes each entity's primary key and standard properties, as well as how the entities relate to each other (in this case we have a many-to-many mapping, using a &lt;code&gt;bag&lt;/code&gt; collection). These files are explained in more detail in my &lt;a href="http://davesquared.blogspot.com/2007/12/messing-around-with-nhibernate.html"&gt;Messing around with NHibernate&lt;/a&gt; post.
&lt;/p&gt;

&lt;h2&gt;Testing our mappings&lt;/h2&gt;
&lt;p&gt;I've populated my database with some sample data (I actually did it using NHibernate -- I find it easier to fill in the relationships that way than with hand written SQL). Let's create an NHibernateTests.cs file and add a test to make sure the entities are mapped correctly.&lt;/p&gt;

&lt;pre&gt;
public class NHibernateTests {
 protected static readonly ISessionFactory SessionFactory = getSessionFactory();
 
 &lt;b&gt;private static ISessionFactory getSessionFactory() {
  Configuration config = new Configuration();
  config.AddAssembly(Assembly.GetExecutingAssembly());
  return config.BuildSessionFactory();
 }&lt;/b&gt;
 
 [Fact]
 public void Get_suppliers_servicing_NSW() {
  using (ISession session = SessionFactory.OpenSession()) {
   var suppliers = session
    .CreateCriteria(typeof(Supplier))
    .CreateCriteria(&amp;quot;StatesServiced&amp;quot;)
    .Add( Restrictions.Eq(&amp;quot;Name&amp;quot;, &amp;quot;NSW&amp;quot;) )
    .SetProjection( Projections.Property(&amp;quot;Name&amp;quot;) )
    .List&amp;lt;String&amp;gt;();
   session.Close();
   Assert.NotEmpty(suppliers);
   Assert.Equal(4, suppliers.Count);
   Assert.Contains(&amp;quot;Tea Ah Maria&amp;quot;, suppliers);
   Assert.Contains(&amp;quot;Teas'r'us&amp;quot;, suppliers);   
  }
 } 
}
&lt;/pre&gt;

&lt;p&gt;This code intialises a new &lt;code&gt;ISessionFactory&lt;/code&gt; using the configuration settings in the &lt;code&gt;App.config&lt;/code&gt;, and the &lt;code&gt;config.AddAssembly(Assembly.GetExecutingAssembly());&lt;/code&gt; line adds the &lt;code&gt;.hbm.xml&lt;/code&gt; mappings embedded in our DLL.&lt;/p&gt;

&lt;p&gt;I've also used the &lt;code&gt;Get_suppliers_servicing_NSW()&lt;/code&gt; test to run a query against all the mapped entities. I'll run this test for each configuration change I make to ensure I haven't broken anything. The details of the test itself aren't really important, but if you are interested it just asks NHibernate to get suppliers that service the state of NSW, and then uses a projection to only bring back the name of the supplier. The assertions check that the expected number of supplier names are returned, and makes sure the list of names includes a couple of the expected values.&lt;/p&gt;

&lt;h2&gt;NHibernate Mapping Attributes&lt;/h2&gt;

&lt;p&gt;&lt;a href="http://nhforge.org/media/p/8.aspx"&gt;NHibernate Mapping Attributes&lt;/a&gt; (also know as NHMA) is a part of the NHibernate Contrib project, and can be used to declare mappings via attributes directly on your entities classes. This sort of spoils the whole POCO idea, but has the advantage of allowing you to make changes to the entity and it's mapping in the one spot. Let's see how this changes our &lt;code&gt;Supplier&lt;/code&gt; and &lt;code&gt;State&lt;/code&gt; classes.&lt;/p&gt;

&lt;pre&gt;
//State.cs
[Class]
public class State {
 [Id(0, Name=&amp;quot;StateId&amp;quot;, TypeType=typeof(Guid), Column=&amp;quot;StateId&amp;quot;)]
 [Generator(1, Class=&amp;quot;guid&amp;quot;) ]
 public virtual Guid StateId { get; set; }        

 [Property]
 public virtual String Name { get; set; }
}

//Supplier.cs
[Class]
public class Supplier {
 private IList&amp;lt;State&amp;gt; statesServiced = new List&amp;lt;State&amp;gt;();
 
 [Id(0, Name=&amp;quot;SupplierId&amp;quot;, TypeType=typeof(Guid))]
 [Generator(1, Class = &amp;quot;guid&amp;quot;)]        
 public virtual Guid SupplierId { get; set; }
 
 [Property]
 public virtual String Name { get; set; }
 
 [Bag(0, Table=&amp;quot;Supplier_StatesServiced&amp;quot;)]
 [Key(1, Column=&amp;quot;SupplierId&amp;quot;)]
 [ManyToMany(2, Column=&amp;quot;StateId&amp;quot;, ClassType = typeof(State))]
 public virtual IList&amp;lt;State&amp;gt; StatesServiced { get { return statesServiced; } set { statesServiced = value; } }
} 
&lt;/pre&gt;

&lt;p&gt;We no longer need our &lt;code&gt;.hbm.xml&lt;/code&gt; files, and have instead translated the relevant mapping information to attributes on the classes themselves. By using attributes NHMA can infer some of the mapping information we previously had to enter explicitly (for example, &lt;code&gt;&amp;lt;property name=&amp;quot;Name&amp;quot; type=&amp;quot;String&amp;quot; /&amp;gt;&lt;/code&gt; just becomes &lt;code&gt;[Property] public virtual String Name {...}&lt;/code&gt;), and we have traded our angle brackets for square ones :). There are also a few strange things going on here. Look at this extract from Supplier.cs:&lt;/p&gt;

&lt;pre&gt;
 [Id(&lt;b&gt;0&lt;/b&gt;, Name=&amp;quot;SupplierId&amp;quot;, TypeType=typeof(Guid))]
 [Generator(&lt;b&gt;1&lt;/b&gt;, Class = &amp;quot;guid&amp;quot;)]        
 public virtual Guid SupplierId { get; set; }
&lt;/pre&gt;

&lt;p&gt;Notice the element indexes on the attributes (&lt;code&gt;ID&lt;/code&gt; is 0, &lt;code&gt;Generator&lt;/code&gt; is 1)? This is because NHMA is actually generating your &lt;code&gt;.hbm.xml&lt;/code&gt; on the fly from the attributes, and it needs to know the order in which to write out the XML elements (attribute order isn't maintained using reflection). To further illustrate this attribute to XML translation, let's look at how this affects our &lt;code&gt;ISessionFactory&lt;/code&gt; initialisation for our tests:&lt;/p&gt;

&lt;pre&gt;
//In NHibernateTests.cs
private static ISessionFactory getSessionFactory() {
 var config = new Configuration();            
 HbmSerializer.Default.Validate = true;                        
 HbmSerializer.Default.Serialize(System.Environment.CurrentDirectory, Assembly.GetExecutingAssembly());
 config.AddDirectory(new DirectoryInfo(System.Environment.CurrentDirectory));            
 return config.BuildSessionFactory();
}
&lt;/pre&gt;

&lt;p&gt;This is using the NHMA default &lt;code&gt;HbmSerializer&lt;/code&gt; class to generate &lt;code&gt;.hbm.xml&lt;/code&gt; files in the current working directory. We then load in these mapping files just like before (except we are using the file system and not embedded assembly resources).&lt;/p&gt;

&lt;p&gt;So to my way of thinking all we have really achieved is simply rewritten all our original &lt;code&gt;.hbm.xml&lt;/code&gt; logic as attributes rather than XML, and made our previously nice clean POCO entities cluttered with persistence information and subsequently less readable. I really loved the idea of NHMA at first, but after trying it out I can't really see it providing much benefit over ye olde hand coded XML. As an added deterrent I couldn't really find much documentation on NHMA, so I ended up having to translate from the fairly well documented &lt;code&gt;.hbm.xml&lt;/code&gt; format anyway.&lt;/p&gt;

&lt;h2&gt;Fluent NHibernate&lt;/h2&gt;

&lt;p&gt;&lt;a href="http://code.google.com/p/fluent-nhibernate/"&gt;Fluent NHibernate&lt;/a&gt;, like NHMA, offers a non-XML way to configure your mappings. Instead of using attributes though, we are using standard .NET code via a fluent interface. This provides lots of neat advantages like automated refactoring and some compile time support, as well as being able to eliminate duplicated information between &lt;code&gt;.hbm.xml&lt;/code&gt; and the POCO entities themselves by using customisable conventions and inferring the relevant property types and names. Before we dive into this it's worth noting that Fluent NHibernate hasn't been released yet and so still has some rough edges. I'm using revision 80 from the &lt;a href="http://code.google.com/p/fluent-nhibernate/"&gt;project's SVN repository&lt;/a&gt;, so much of this will probably change before it hits version 1.0.&lt;/p&gt;

&lt;p&gt;I've reverted our &lt;code&gt;Supplier&lt;/code&gt; and &lt;code&gt;State&lt;/code&gt; classes back to Plain Old CLR Objects (removed all the NHMA attributes) and also taken out the &lt;code&gt;.hbm.xml&lt;/code&gt; files. The first thing we need to do is create some Fluent Nhibernate &lt;code&gt;ClassMap&lt;/code&gt; classes.&lt;/p&gt;

&lt;pre&gt;
public class StateMap : ClassMap&amp;lt;State&amp;gt; {
 public StateMap() {                
  Id(x =&amp;gt; x.StateId);
  Map(x =&amp;gt; x.Name);
 }
}

public class SupplierMap : ClassMap&amp;lt;Supplier&amp;gt; {
 public SupplierMap() {                
  Id(x =&amp;gt; x.SupplierId);
  Map(x =&amp;gt; x.Name);
  HasManyToMany&amp;lt;State&amp;gt;(x =&amp;gt; x.StatesServiced)
   .AsBag()
   .WithTableName(&amp;quot;Supplier_StatesServiced&amp;quot;)
   .WithParentKeyColumn(&amp;quot;SupplierId&amp;quot;)
   .WithChildKeyColumn(&amp;quot;StateId&amp;quot;);  
 }
}
&lt;/pre&gt;

&lt;p&gt;Each mapping class configures the mapping for an entity within the constructor (um, ignore the evil calls to virtual methods in the constructors :-\). This looks much, much neater than the previously approaches, as Fluent NHibernate does most of the work for us. Let's check the configuration for our test:&lt;/p&gt;

&lt;pre&gt;
private static ISessionFactory getSessionFactory() {
 var config = new Configuration();
 config.AddMappingsFromAssembly(Assembly.GetExecutingAssembly());
 return config.BuildSessionFactory();
}
&lt;/pre&gt;

&lt;p&gt;Looks pretty good to me. :) But it gets better -- say I always name my identifiers in the form &lt;code&gt;&lt;i&gt;EntityName&lt;/i&gt;Id&lt;/code&gt;. If Fluent NHibernate knew that, then I could reduce my supplier class map to this:&lt;/p&gt;

&lt;pre&gt;
public class SupplierMap : ClassMap&amp;lt;Supplier&amp;gt; {
 public SupplierMap() {                
  Id(x =&amp;gt; x.SupplierId);
  Map(x =&amp;gt; x.Name);
  &lt;b&gt;HasManyToMany&amp;lt;State&amp;gt;(x =&amp;gt; x.StatesServiced)
   .AsBag()
   .WithTableName(&amp;quot;Supplier_StatesServiced&amp;quot;);&lt;/b&gt;
 }
}
&lt;/pre&gt;

&lt;p&gt;After all, we know the keys used to map suppliers and states are going to be &lt;code&gt;SupplierId&lt;/code&gt; and &lt;code&gt;StateId&lt;/code&gt;, so the many-to-many mapping becomes trivial.  Fluent NHibernate currently assumes the names will in the form &lt;code&gt;supplier_id&lt;/code&gt;, but that's no big deal, because it also let's me change the conventions used:&lt;/p&gt;
&lt;pre&gt;
private static ISessionFactory getSessionFactory() {
 var config = new Configuration();
 var model = &lt;b&gt;getFluentNhibernatePersistenceModel()&lt;/b&gt;;
 model.Configure(config);            
 return config.BuildSessionFactory();
}

private static PersistenceModel getFluentNhibernatePersistenceModel() {
 var model = new PersistenceModel();
 &lt;b&gt;model.Conventions.GetForeignKeyName = prop =&gt; prop.Name + "Id";&lt;/b&gt; //By default assumes prop.Name + "_id"
 &lt;b&gt;model.Conventions.GetForeignKeyNameOfParent = type =&gt; type.Name + "Id";&lt;/b&gt;
 model.addMappingsFromAssembly(Assembly.GetExecutingAssembly());
 return model;
}
&lt;/pre&gt;

&lt;p&gt;Pretty neat, huh? You can imagine how trivial you could get the mappings if you set your conventions correctly.&lt;/p&gt;

&lt;p&gt;There is work under way to make this even easier using &lt;a href="http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/5d7a524fb6ffcae/769430df684265da"&gt;AutoMap&lt;/a&gt; functionality, which will be used to auto-magically infer mappings for your entities. You can then customise any special cases (like the many-to-many relationship we have in this case -- it will probably assume the more common one-to-many case by default).&lt;/p&gt;

&lt;h2&gt;Tools not covered here&lt;/h2&gt;

&lt;p&gt;I also had a quick look at &lt;a href="http://using.castleproject.org/display/Contrib/ActiveWriter"&gt;ActiveWriter&lt;/a&gt;, but couldn't get it working (failed when trying to save the model and generate the correct files. Possibly because I was using NH 2.0, more likely that I had no idea what I was doing with it :)). It provides a designer within Visual Studio that you can use to generate your mapping files and .NET entity classes. It has the usual drag-and-drop designer goodness -- dragging database tables onto the surface or using toolbox items to create classes and adjust the properties to map to tables etc. It is meant to work with both Castle ActiveRecord and NHibernate.&lt;/p&gt;

&lt;p&gt;The reason I didn't persevere with trying to get it to work is that I am well and truly over designers. I hate mousing all over a design surface and repeatedly hunting for the property you want and then repeatedly setting it over multiple boxes. No matter how nice the designer, I always seem to end up cursing it once the demo has finished and I start using it for real work. Of course this may just be a reflection on my advanced age and grumpy demeanor - YMMV. :) Oh yeah, and get off my lawn! :P&lt;/p&gt;

&lt;p&gt;There are a number of &lt;a href="http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/toolsetguide.html"&gt;other tools mentioned in the NHibernate 1.2 docs&lt;/a&gt;, including &lt;code&gt;hbm2net&lt;/code&gt; (generate classes from HBM), as well as generation tools like CodeSmith and MyGeneration, but most of these seem to focus on generating the C# classes or SQL scripts for creating the database schema from the &lt;code&gt;.hbm.xml&lt;/code&gt;. I think I'd prefer to control my entity and database creation, and instead try and make the mapping itself easier.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Fluent NHibernate looks absolutely fantastic, but is still in very early stages of development. If you don't like living on the bleeding edge, then the standard &lt;code&gt;.hbm.xml&lt;/code&gt; files really aren't that bad once you've set up a couple of them. The good thing is you can switch between all these mapping methods without changing anything but the &lt;code&gt;ISessionFactory&lt;/code&gt; initialisation code, which only occurs in one place within your application. All these changes were made with a continuously green test light. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-7663679128509581313?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Vc3iQxB64Dg:KXBpd3ff48M:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=Vc3iQxB64Dg:KXBpd3ff48M:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Vc3iQxB64Dg:KXBpd3ff48M:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Vc3iQxB64Dg:KXBpd3ff48M:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=Vc3iQxB64Dg:KXBpd3ff48M:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=Vc3iQxB64Dg:KXBpd3ff48M:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/Vc3iQxB64Dg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/7663679128509581313/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=7663679128509581313" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/7663679128509581313?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/7663679128509581313?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/09/nhibernate-mappings-using-xml.html" title="NHibernate mappings using xml, attributes, and Fluent NHibernate" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://bp0.blogger.com/_wEsHWMWy090/R2n9HuaPYDI/AAAAAAAAAfs/04T6Bg6e7mY/s72-c/SampleSupplierSchema.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">6</thr:total></entry><entry gd:etag="W/&quot;C08ARn8_cSp7ImA9WxRQEEw.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-393433192689478503</id><published>2008-08-30T23:55:00.003+10:00</published><updated>2008-10-03T15:30:47.149+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-10-03T15:30:47.149+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="python" /><title>Getting both item and index during C# enumerations</title><content type="html">&lt;p&gt;I recently got an &lt;a href="http://davesquared.blogspot.com/2008/01/python-like-range-implementation-in-c.html?showComment=1220059620000#c3630230372213218148"&gt;interesting comment&lt;/a&gt; on an older post of mine about implementing a &lt;a href="http://davesquared.blogspot.com/2008/01/python-like-range-implementation-in-c.html"&gt;Python-like range() function in C#&lt;/a&gt;. The commenter posed a solution to the slight feeling of disappointment experienced when you have a &lt;code&gt;foreach&lt;/code&gt; loop and then realise you need to access the loop index, forcing a conversion to a &lt;code&gt;for&lt;/code&gt; loop or manually incrementing a counter. The solution ended up with a syntax like this:&lt;/p&gt;

&lt;pre&gt;
//From &lt;a href="http://davesquared.blogspot.com/2008/01/python-like-range-implementation-in-c.html?showComment=1220059620000#c3630230372213218148"&gt;this comment&lt;/a&gt;:
int[] a = new int[] { 1, 2, 3, 4, 5 };
foreach (int i in Range.Array(a)) {
  // do something with i or a[i]
}
&lt;/pre&gt;

&lt;p&gt;Great concept! :) Let's take it a step further by drawing some more inspiration from Python. Here's a Python list comprehension that uses the &lt;code&gt;enumerate()&lt;/code&gt; function to loop over tuples of both index and item:&lt;/p&gt;

&lt;pre&gt;
&amp;gt;&amp;gt;&amp;gt; sampleList = ['a','b','c','d']
&amp;gt;&amp;gt;&amp;gt; [(index,item) for index, item in enumerate(sampleList)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
&lt;/pre&gt;

&lt;p&gt;Or in a more C#-like format:&lt;/p&gt;

&lt;pre&gt;
&amp;gt;&amp;gt;&amp;gt; for index, value in enumerate(sampleList):
     print(index, value)
 
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
&lt;/pre&gt;

&lt;p&gt;Let's see how this could work in C#. As usual, I'll start with a test:&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Can_enumerate_index_and_item() {
 String[] strings = {&amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;, &amp;quot;c&amp;quot;, &amp;quot;d&amp;quot;};
 int expectedIndex = 0;
 &lt;b&gt;foreach (var tuple in Enumerate.Over(strings)) {&lt;/b&gt;
  Assert.Equal(expectedIndex, tuple.Index);
  Assert.Equal(strings[tuple.Index], tuple.Item);
  expectedIndex++;
 }           
}
&lt;/pre&gt;

&lt;p&gt;To pass this we'll need a simple &lt;code&gt;Tuple&lt;/code&gt; class (&lt;a href="http://blogs.msdn.com/jaredpar/archive/tags/Tuple/default.aspx"&gt;better versions available&lt;/a&gt;) and an &lt;code&gt;Enumerate&lt;/code&gt; class (not entirely happy with the names, but we're just mucking around here). I'm going to violate &lt;a href="http://en.wikipedia.org/wiki/YAGNI"&gt;YAGNI&lt;/a&gt; guidelines here and not restrict us to just arrays of Strings.&lt;/p&gt;

&lt;pre&gt;
public class Tuple&amp;lt;T&amp;gt; {
 public int Index { get; private set; }
 public T Item { get; private set; }

 public Tuple(int index, T item) {
  Index = index;
  Item = item;
 }
}

public class Enumerate {
 public static IEnumerable&amp;lt;Tuple&amp;lt;T&amp;gt;&amp;gt; Over&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; items) {
  int index = 0;
  foreach (T item in items) {
   yield return new Tuple&amp;lt;T&amp;gt;(index++, item);
  }  
 }
}
&lt;/pre&gt;

&lt;div class="note"&gt;&lt;b&gt;Note added 2008-10-03:&lt;/b&gt; As a colleague of mine pointed out, this is a bit evil as it is implying &lt;code&gt;foreach&lt;/code&gt; will return items in the same order as indexed. This isn't actually guaranteed at all, so you might get cases where the returned index isn't the actual index of an item.&lt;/div&gt;

&lt;p&gt;The original test passes (along with a couple of others omitted for brevity), and we can now write a C# version of the Python &lt;code&gt;enumerate()&lt;/code&gt; sample at the start of this post:&lt;/p&gt;

&lt;pre&gt;
String[] strings = { &amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;, &amp;quot;c&amp;quot;, &amp;quot;d&amp;quot; };            
foreach (var tuple in Enumerate.Over(strings)) {
 Console.WriteLine(tuple.Index + &amp;quot;, &amp;quot; + tuple.Item);
}
/* Outputs:
0, a
1, b
2, c
3, d
*/
&lt;/pre&gt;

&lt;p&gt;I'm fairly sure there's a better (LINQ-y?) way of doing this, but this is all my Googling and I can come up with right now. :)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-393433192689478503?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=BStAT-iVp5g:EjFKyMrsWv8:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=BStAT-iVp5g:EjFKyMrsWv8:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=BStAT-iVp5g:EjFKyMrsWv8:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=BStAT-iVp5g:EjFKyMrsWv8:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=BStAT-iVp5g:EjFKyMrsWv8:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=BStAT-iVp5g:EjFKyMrsWv8:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/BStAT-iVp5g" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/393433192689478503/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=393433192689478503" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/393433192689478503?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/393433192689478503?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/08/getting-both-item-and-index-during-c.html" title="Getting both item and index during C# enumerations" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;DkADRXc6eSp7ImA9WxdaF04.&quot;"><id>tag:blogger.com,1999:blog-7624394686148711990.post-3858633285652586875</id><published>2008-08-26T16:56:00.003+10:00</published><updated>2008-08-26T17:12:54.911+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-08-26T17:12:54.911+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="nhibernate" /><title>Modifying the SQL generated by NHibernate</title><content type="html">&lt;p&gt;Is it possible to modify the SQL generated by NHibernate? Yes:&lt;/p&gt;

&lt;pre&gt;public class BadInterceptor : EmptyInterceptor, IInterceptor {
 SqlString IInterceptor.&lt;b&gt;OnPrepareStatement(SqlString sql)&lt;/b&gt; {
  return doHorribleThingsToSqlString(sql);            
 }
 private SqlString doHorribleThingsToSqlString(SqlString sql) { ... }
}

protected static readonly ISessionFactory SessionFactory = initialiseSessionFactory();
private static ISessionFactory initialiseSessionFactory() {
 var config = new Configuration();
 config.AddAssembly(Assembly.GetExecutingAssembly());
 &lt;b&gt;config.SetInterceptor(new BadInterceptor())&lt;/b&gt;;
 return config.BuildSessionFactory();
}
&lt;/pre&gt;

&lt;p&gt;Now don't! :) Seriously, it's evil.&lt;/p&gt;

&lt;p&gt;If anyone knows a nice way to get NHibernate to add some custom SQL as part of it's SQL generation process, rather than this brute-force approach, then please let me know. I was initially playing around with this code to add some calls to SQL Server's &lt;code&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/ms173784.aspx"&gt;binary_checksum()&lt;/a&gt;&lt;/code&gt; function when loading and saving entities, and I'd be interested if this is possible to do in a reasonably robust way.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7624394686148711990-3858633285652586875?l=www.davesquared.net'/&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=3f3dypMuPGA:TYUSyqVm6HM:4cEx4HpKnUU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=3f3dypMuPGA:TYUSyqVm6HM:4cEx4HpKnUU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=3f3dypMuPGA:TYUSyqVm6HM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=3f3dypMuPGA:TYUSyqVm6HM:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?i=3f3dypMuPGA:TYUSyqVm6HM:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/davesquared?a=3f3dypMuPGA:TYUSyqVm6HM:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/davesquared?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/3f3dypMuPGA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.davesquared.net/feeds/3858633285652586875/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=3858633285652586875" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3858633285652586875?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3858633285652586875?v=2" /><link rel="alternate" type="text/html" href="http://www.davesquared.net/2008/08/modifying-sql-generated-by-nhibernate.html" title="Modifying the SQL generated by NHibernate" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email><gd:extendedProperty name="OpenSocialUserId" value="15069573216606975109" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry></feed>
