<?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;DkYAQHk-fip7ImA9WxBWFUk.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699</id><updated>2010-02-07T23:02:21.756+11:00</updated><title>Paul Batum</title><subtitle type="html">Just another software developer trying to improve his craft.</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.paulbatum.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/" /><link rel="hub" href="http://pubsubhubbub.appspot.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default?start-index=26&amp;max-results=25&amp;redirect=false&amp;v=2" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>61</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/PaulBatum" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="paulbatum" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><entry gd:etag="W/&quot;DkYAQHk9eip7ImA9WxBWFUk.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-916567033647658323</id><published>2010-02-07T23:01:00.000+11:00</published><updated>2010-02-07T23:02:21.762+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-02-07T23:02:21.762+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Messaging" /><category scheme="http://www.blogger.com/atom/ns#" term="SOA" /><title>Advanced Distributed Systems Design with Udi Dahan</title><content type="html">&lt;p&gt;I spent last week in Melbourne for a 5 day training course on distributed systems, run by &lt;a href="http://www.udidahan.com/"&gt;Udi Dahan&lt;/a&gt;. I’ve been a fan of Udi’s work for a while now, so when I discovered that he was on his way to Australia I jumped at the chance to be immersed in his approach to designing scalable and reliable distributed systems. Let me tell you – I was not disappointed. I found Udi’s course to be very challenging – not in terms of difficulty, but rather that it was full of ideas that challenged my &lt;em&gt;preconceptions&lt;/em&gt;. I was also very impressed with Udi’s presentation and communication skills. He really knows the material and has an amazing ability to give helpful, informative answers to really dumb questions :)&lt;/p&gt;  &lt;p&gt;The course was focused on a few key ideas:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Service oriented architecture &lt;/li&gt;    &lt;li&gt;Message based systems &lt;/li&gt;    &lt;li&gt;Command / query responsibility segregation &lt;/li&gt;    &lt;li&gt;Domain models &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;If you’d like a more detailed breakdown of the course content, Udi has provided an &lt;a href="http://www.udidahan.com/training/"&gt;overview&lt;/a&gt; on his website. &lt;/p&gt;  &lt;p&gt;I’ve tried to understand SOA before and struggled with the abstractness of the concept. I guess part of my difficulty has always come from the fact that I still approach the world with a “developer” mindset – I’ve never really bought into the concept of a non-coding architect and sometimes I struggle to understand the meaning and implications of an idea if I can’t see the actual effect on the code we write. &lt;/p&gt;  &lt;p&gt;Thanks to Udi, I now have a basic understanding of what SOA means. I am comfortable with the idea of identifying &lt;em&gt;business capabilities&lt;/em&gt; and describing them as services that consist of business components, which in turn consist of autonomous components that are individually deployable. I’m also comfortable with the idea of these autonomous components communicating with each other via a message bus using a combination of asynchronous request-reply and publish-subscribe. I am not yet sure how well my understanding will map to the existing literature on SOA, as I got the impression from some of the other students that Udi’s version of SOA was somewhat different to the SOA they had read about. My impression of SOA is that it is a slippery subject, where only the most abstract and vague definitions are widely accepted. That said, I can see a great deal of value in the analytical process and technical approach that Udi taught us.&lt;/p&gt;  &lt;p&gt;Having skimmed &lt;a href="http://www.eaipatterns.com/"&gt;Enterprise Integration Patterns&lt;/a&gt;, I was already familiar with the idea of message based systems and the advantages of temporal decoupling before I began the course. But Udi’s coverage of the topic helped fill in large gaps and also gave me a great deal of appreciation for the power and simplicity of his open source .NET based service bus, &lt;a href="http://www.nservicebus.com"&gt;NServiceBus&lt;/a&gt;. My co-worker Malcolm nearly did a backflip when he saw how easy it is to begin using NServiceBus alongside WCF.&lt;/p&gt;  &lt;p&gt;Command / query responsibility segregation (CQRS) is about recognising the difference between queries and commands as part of system architecture, and designing completely different paths for handling the two types of operations. Going into the course, I thought I was comfortable with the idea as I’d watched a number of videos on the topic from &lt;a href="http://codebetter.com/blogs/gregyoung/"&gt;Greg Young&lt;/a&gt;, and had read a number of blog posts. It turned out that Udi had his own take on CQRS that I did not pick up on when reading his posts on the topic. Speaking of Udi’s posts on the topic of CQRS, I highly recommend &lt;a href="http://www.udidahan.com/2009/12/09/clarified-cqrs/"&gt;this one&lt;/a&gt; if you’d like to learn more.&lt;/p&gt;  &lt;p&gt;So how was Udi’s version of CQRS different to what I expected? One example immediately comes to mind. A necessary part of CQRS is some sort of persistent view model to facilitate the queries, and a transactional data model to facilitate the commands. So far, so good. Udi then introduced the idea that there may be some relationships that are only recorded in the persistent view model, and not in the transactional model – if later on you need that data in your transactional store, then backfill it with an ETL from your view model! Boy did that raise some incredulous looks, especially from yours truly! “What happened to my single source of truth?” I cried.&lt;/p&gt;  &lt;p&gt;Udi also had some interesting ideas about domain models. In particular, we went into quite a bit of detail on the idea of aggregates, and how to ensure consistency. Has it ever occurred to you that perhaps there is something wrong with loading a Customer, and then lazily loading their Orders at some later point? What happens if one of the Orders are modified by another process, after the Customer is loaded but before the Orders are lazily loaded? Now the model loaded into memory is inconsistent! Even if your optimistic concurrency will protect you in most of these scenarios, its entirely possible that you’re updating some other object based on logic that has operated on your inconsistent snapshot. This problem seemed obvious once it was pointed out, but it had never occurred to me before.&lt;/p&gt;  &lt;p&gt;There were so many interesting discussions and points of contention over the 5 days, this post has barely begun to skim the surface. It really was an eye opening experience for me, and some serious food for thought. If you ever get the opportunity to attend Udi’s course, don’t hesitate. Its worth it!&lt;/p&gt;  &lt;p&gt;Now that I’ve finally managed to get something written down on the course, I’ll let myself read some of the summaries written &lt;a href="http://www.markharris.net.au/blog/2010/02/04/doing-advanced-distributed-systems-design-a-gift-from-santa"&gt;by&lt;/a&gt; &lt;a href="http://rhysc.blogspot.com/2010/01/udi-dahan-advanced-distributed-systems.html"&gt;other&lt;/a&gt; &lt;a href="http://www.simonsegal.net/blog/2010/02/04/adsd-nservicebus-and-nuclear-armament-the-full-story/"&gt;attendees&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/882821950355432699-916567033647658323?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/916567033647658323/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2010/01/advanced-distributed-systems-design.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/916567033647658323?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/916567033647658323?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2010/01/advanced-distributed-systems-design.html" title="Advanced Distributed Systems Design with Udi Dahan" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;CEcFSH0_fip7ImA9WxNbFUk.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-7306904303302440986</id><published>2009-11-18T22:00:00.001+11:00</published><updated>2009-11-18T22:00:19.346+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-11-18T22:00:19.346+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><title>Reacting to the Reactive Framework: Part 8</title><content type="html">&lt;p&gt;Today I caught wind of some news that was bound to rouse me from my blogging slumber. The Reactive Framework, now known as Reactive Extensions (or Rx for short) has been &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;released&lt;/a&gt; on DevLabs. The good news is that this release includes versions for .NET 3.5, .NET 4 Beta 2 and Silverlight 3, and documentation. The bad news is that at this stage, the documentation is pretty sparse - single sentence summaries and zero examples. Certainly, the summaries will help developer make sense of the impressive range of extension methods available on IObservable. For example, the comment on the rather cryptically named &lt;strong&gt;Amb&lt;/strong&gt; - &lt;em&gt;Returns the observable sequence that reacts first - &lt;/em&gt;makes its purpose quite clear, even if it doesn’t help explain the name. However the same cannot be said for all the cases, such as &lt;strong&gt;Dematerialize - &lt;/strong&gt;&lt;em&gt;Dematerializes the explicit notification values of an observable sequence as implicit notifications&lt;/em&gt;. Perhaps that will make sense once I understand the difference between explicit and implicit notifications, but its unlikely that the documentation (in its current form) will help me understand this. No matter - this intermediate release is certainly welcome and I now look forward to diving back in to Rx with at least some clue of what things are supposed to do :) &lt;/p&gt;  &lt;p&gt;If you are interested in the Reactive Extensions I recommend you check out the &lt;a href="http://blogs.msdn.com/RxTeam/"&gt;team blog&lt;/a&gt;. The &lt;a href="http://blogs.msdn.com/rxteam/archive/2009/11/17/announcing-reactive-extensions-rx-for-net-silverlight.aspx"&gt;announcement post&lt;/a&gt; has plenty of links for you to click and learn more. I also recommend Matt Podwysocki’s &lt;a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2009/10/14/introducing-the-reactive-framework-part-i.aspx"&gt;series&lt;/a&gt; &lt;a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2009/11/03/introduction-to-the-reactive-framework-part-ii.aspx"&gt;of&lt;/a&gt; &lt;a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2009/11/12/introduction-to-the-reactive-framework-part-iii.aspx"&gt;Rx&lt;/a&gt; &lt;a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2009/11/15/introduction-to-the-reactive-framework-part-iv.aspx"&gt;posts&lt;/a&gt;. Also, don’t forget that now Rx is on DevLabs, there’s a dedicated &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/threads"&gt;forum&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/882821950355432699-7306904303302440986?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/7306904303302440986/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/11/reacting-to-reactive-framework-part-8.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/7306904303302440986?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/7306904303302440986?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/11/reacting-to-reactive-framework-part-8.html" title="Reacting to the Reactive Framework: Part 8" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;DUQEQXo_fCp7ImA9WxJaGUo.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-750276189381003775</id><published>2009-08-11T17:55:00.000+10:00</published><updated>2009-08-11T17:55:00.444+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-08-11T17:55:00.444+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Reacting to the Reactive Framework: Part 7</title><content type="html">&lt;p&gt;The demo application for today allows the user to experiment with a couple of the mechanisms that I tried for &lt;a href="http://www.paulbatum.com/2009/08/reacting-to-reactive-framework-part-6.html"&gt;part 6&lt;/a&gt;. As you may recall, I wanted an IObservable&amp;lt;int[]&amp;gt; that would return the three selections made from three groups of radio buttons, and only begin returning values once a selection had been made from all three. The demo app allows you to switch between using SelectMany, ForkJoin and CombineLatest and observe how the behavior changes:&lt;/p&gt; &lt;iframe style="width: 500px; height: 350px" src="http://silverlight.services.live.com/invoke/104983/PB-Rx-Test3/iframe.html" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;  &lt;p&gt;The first approach I tried was SelectMany - I’ll use the query comprehension syntax as it is much more readable than calling the SelectMany extension method directly:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;from &lt;/span&gt;s1 &lt;span style="color: blue"&gt;in &lt;/span&gt;choiceControl1.OptionSelections
&lt;span style="color: blue"&gt;from &lt;/span&gt;s2 &lt;span style="color: blue"&gt;in &lt;/span&gt;choiceControl2.OptionSelections
&lt;span style="color: blue"&gt;from &lt;/span&gt;s3 &lt;span style="color: blue"&gt;in &lt;/span&gt;choiceControl3.OptionSelections
&lt;span style="color: blue"&gt;select new&lt;/span&gt;[] { s1, s2, s3 }&lt;/pre&gt;

&lt;p&gt;This syntax might be readable, but its also a little misleading. It looks very uniform, like it wouldn’t matter which order you wrote those three ‘from’ statements in. But if you are familiar with LINQ statements like this one, you will know that the ordering IS important. To observe this, activate the SelectMany option in the app above, and then make your selections in reverse order i.e. select an option from group 3, then group 2, then group 1. Notice how you don’t get a selection readout? What’s actually happening here is that the selections made in groups 2 and 3 are ignored until a selection is made in group 1. Then the selections made in group 3 are ignored, until a selection is made in group 2. Then finally selections from group 3 will trigger the observable and raise a result. I could go into more detail on what’s happening here, but is there much point? Its obvious that this implementation is not at all close to the desired result. Lets move on.&lt;/p&gt;

&lt;p&gt;When I came across the signature for ForkJoin, I thought I had found what I was looking for:&lt;/p&gt;

&lt;pre&gt;public static &lt;a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://System.Reactive:1.0.0.0:1b331ac6720247d9/System.Collections.Generic.IObservable&amp;lt;&amp;gt;"&gt;IObservable&lt;/a&gt;&amp;lt;&lt;a&gt;TSource&lt;/a&gt;[]&amp;gt; &lt;b&gt;&lt;a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://System.Reactive:1.0.0.0:1b331ac6720247d9/System.Linq.Observable/ForkJoin&amp;lt;&amp;gt;(System.Collections.Generic.IObservable&amp;lt;&amp;lt;!!0&amp;gt;&amp;gt;%5b%5d):System.Collections.Generic.IObservable&amp;lt;&amp;lt;!!0&amp;gt;%5b%5d&amp;gt;"&gt;ForkJoin&lt;/a&gt;&lt;/b&gt;&amp;lt;&lt;b&gt;TSource&lt;/b&gt;&amp;gt;(params &lt;a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://System.Reactive:1.0.0.0:1b331ac6720247d9/System.Collections.Generic.IObservable&amp;lt;&amp;gt;"&gt;IObservable&lt;/a&gt;&amp;lt;&lt;a&gt;TSource&lt;/a&gt;&amp;gt;[] sources); &lt;/pre&gt;

&lt;p&gt;It converts many IObservable&amp;lt;T&amp;gt;’s into one IObservable&amp;lt;T[]&amp;gt;, which is exactly what I want. The bad news is that it only works &lt;strong&gt;once&lt;/strong&gt;. Go ahead and try ForkJoin in the sample app – the status text will update once a selection has been made from all three groups, but it will not update again as the selection continues to change. It did occur to me that perhaps I could use ForkJoin and somehow re-subscribe each time it fires, but I was reluctant to go down that path because it doesn’t feel like a functional (as in functional programming) solution.&lt;/p&gt;

&lt;p&gt;The demo app for today uses CombineLatest in the same way as in my previous post:&lt;/p&gt;

&lt;pre class="code"&gt;choiceControl1.OptionSelections
  .CombineLatest(choiceControl2.OptionSelections, (i, j) =&amp;gt; &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { i, j })
  .CombineLatest(choiceControl3.OptionSelections, (array, k) =&amp;gt; &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { array[0], array[1], k }))&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This works fine, though its not pretty. I’ll keep my eye out for a better solution, but before I finish up today I want to look at the code behind today’s demo app:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;20&amp;quot;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Combining Example&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Center&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;10&amp;quot; /&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;Orientation&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Vertical&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Left&amp;quot;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Select a means of combination:&amp;quot; /&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;RadioButton &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;rbSelectMany&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Content&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Use SelectMany&amp;quot; /&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;RadioButton &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;rbForkJoin&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Content&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Use ForkJoin&amp;quot; /&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;RadioButton &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;rbCombineLatest&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Content&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Use CombineLatest&amp;quot; /&amp;gt;                               
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Select an option from each group below, and then experiment with changing your selections.&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;TextWrapping&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Wrap&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;0,10,0,0&amp;quot;  /&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;            
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;Orientation&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Horizontal&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Center&amp;quot; &amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;SilverlightApp&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ChoiceControl &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;choiceControl1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Heading&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Group 1&amp;quot;/&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;SilverlightApp&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ChoiceControl &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;choiceControl2&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Heading&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Group 2&amp;quot;/&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;SilverlightApp&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ChoiceControl &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;choiceControl3&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Heading&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Group 3&amp;quot;/&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;statusText&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Status Text&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;TextAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Center&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;MainPage()
{
    InitializeComponent();

    &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;[]&amp;gt;&amp;gt; observerSelections = &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.Merge(
        &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(rbSelectMany, &lt;span style="color: #a31515"&gt;&amp;quot;Checked&amp;quot;&lt;/span&gt;)
            .Select(_ =&amp;gt; &lt;span style="color: blue"&gt;from &lt;/span&gt;s1 &lt;span style="color: blue"&gt;in &lt;/span&gt;choiceControl1.OptionSelections
                         &lt;span style="color: blue"&gt;from &lt;/span&gt;s2 &lt;span style="color: blue"&gt;in &lt;/span&gt;choiceControl2.OptionSelections
                         &lt;span style="color: blue"&gt;from &lt;/span&gt;s3 &lt;span style="color: blue"&gt;in &lt;/span&gt;choiceControl3.OptionSelections
                         &lt;span style="color: blue"&gt;select new&lt;/span&gt;[] { s1, s2, s3 }),
        &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(rbForkJoin, &lt;span style="color: #a31515"&gt;&amp;quot;Checked&amp;quot;&lt;/span&gt;)
            .Select(_ =&amp;gt; &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.ForkJoin(choiceControl1.OptionSelections, choiceControl2.OptionSelections, choiceControl3.OptionSelections)),
        &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(rbCombineLatest, &lt;span style="color: #a31515"&gt;&amp;quot;Checked&amp;quot;&lt;/span&gt;)
            .Select(_ =&amp;gt; choiceControl1.OptionSelections
                            .CombineLatest(choiceControl2.OptionSelections, (i, j) =&amp;gt; &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { i, j })
                            .CombineLatest(choiceControl3.OptionSelections, (array, k) =&amp;gt; &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { array[0], array[1], k }))
        );

    &lt;span style="color: #2b91af"&gt;IDisposable &lt;/span&gt;subscription = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
    observerSelections.Subscribe(observer =&amp;gt;
                                 {
                                     &lt;span style="color: blue"&gt;if &lt;/span&gt;(subscription != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                                         subscription.Dispose();

                                     choiceControl1.ClearAll();
                                     choiceControl2.ClearAll();
                                     choiceControl3.ClearAll();
                                     statusText.Text = &lt;span style="color: blue"&gt;string&lt;/span&gt;.Empty;

                                     subscription = observer.Subscribe(UpdateSelectedOptions);                                                                               
                                 });
}

&lt;span style="color: blue"&gt;private void &lt;/span&gt;UpdateSelectedOptions(&lt;span style="color: blue"&gt;int&lt;/span&gt;[] values)
{
    statusText.Text = &lt;span style="color: blue"&gt;string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;Option {0}, Option {1}, Option {2}&amp;quot;&lt;/span&gt;,
                                    values[0], values[1], values[2]);
}&lt;/pre&gt;

&lt;p&gt;If you recall in the previous post, I was using the Observable.Merge method to glue three separate events together into one observable, and today I’m using the same technique on the radio buttons that let you swap between the different implementations. The difference in this case is that instead of simply returning an integer, I’m returning an IObservable&amp;lt;int[]&amp;gt;, so the result is an IObservable&amp;lt;IObservable&amp;lt;int[]&amp;gt;&amp;gt;. I then subscribe to this so that each time the selected implementation changes, the existing subscription is disposed, the selections are cleared and a new subscription is instated.&lt;/p&gt;

&lt;p&gt;What do you think? Am I being too clever for my own good here? Is an IObservable&amp;lt;IObservable&amp;lt;T&amp;gt;&amp;gt; taking it too far? Let me know in the comments!&lt;/p&gt;

&lt;p&gt;The code for this post has been &lt;a href="http://github.com/paulbatum/Rx-sandpit/tree/Combination-Ex2"&gt;tagged&lt;/a&gt; in my github repository.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-750276189381003775?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/750276189381003775/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/08/reacting-to-reactive-framework-part-7.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/750276189381003775?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/750276189381003775?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/08/reacting-to-reactive-framework-part-7.html" title="Reacting to the Reactive Framework: Part 7" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;A08FSXo9eCp7ImA9WxJaF0k.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-5065621844609161257</id><published>2009-08-09T02:42:00.000+10:00</published><updated>2009-08-09T02:43:38.460+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-08-09T02:43:38.460+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Reacting to the Reactive Framework: Part 6</title><content type="html">&lt;p&gt;Before I dive into today’s code, there are two things worth mentioning:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;If you haven’t already, make haste to &lt;a href="http://themechanicalbride.blogspot.com/"&gt;Jafar Husain’s blog&lt;/a&gt;. Jafar is posting &lt;a href="http://themechanicalbride.blogspot.com/2009/07/developing-with-rx-part-1-extension.html"&gt;truly&lt;/a&gt; &lt;a href="http://themechanicalbride.blogspot.com/2009/07/developing-with-rx-part-2-converting.html"&gt;interesting&lt;/a&gt; &lt;a href="http://themechanicalbride.blogspot.com/2009/08/joy-of-rx-building-asynchronous-service.html"&gt;examples&lt;/a&gt; of using the Reactive Framework - none of the ‘hello world’ fare I’m peddling here. &lt;/li&gt;    &lt;li&gt;I mentioned in my previous post that I was having trouble using System.Reactive.dll with non-silverlight projects. Jb Evain has &lt;a href="http://evain.net/blog/articles/2009/07/30/rebasing-system-reactive-to-the-net-clr"&gt;the goods&lt;/a&gt; on how you might get around this if you were so inclined. For now I’ll stick with Silverlight as its well suited for including interactive demonstrations in my blog posts. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Today I want to look at combining events using the Reactive Framework (Rx). Here is the demo app for today: &lt;em&gt;(Once again I will remind readers using RSS readers to view this post in a proper browser window so you can see the embedded Silverlight app.)&lt;/em&gt;&lt;/p&gt; &lt;iframe style="width: 600px; height: 300px" src="http://silverlight.services.live.com/invoke/104983/PB-Rx-Test2/iframe.html" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;  &lt;p&gt;The idea behind this example is that I am not interested in the selections until an option has been selected from all three groups. From then on, I’d like to be informed whenever the selection changes. This application consists of three instances of a user control, one for each group. Here is the relevant markup and code for the user control:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;20&amp;quot;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Heading&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;5&amp;quot; /&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;RadioButton &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;optionButton1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Content&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Option 1&amp;quot; /&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;RadioButton &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;optionButton2&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Content&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Option 2&amp;quot; /&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;RadioButton &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;optionButton3&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Content&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Option 3&amp;quot; /&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;ChoiceControl()
{
    InitializeComponent();

    OptionSelections = &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.Merge(
        &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(optionButton1, &lt;span style="color: #a31515"&gt;&amp;quot;Checked&amp;quot;&lt;/span&gt;).Select(_ =&amp;gt; 1),
        &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(optionButton2, &lt;span style="color: #a31515"&gt;&amp;quot;Checked&amp;quot;&lt;/span&gt;).Select(_ =&amp;gt; 2),
        &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(optionButton3, &lt;span style="color: #a31515"&gt;&amp;quot;Checked&amp;quot;&lt;/span&gt;).Select(_ =&amp;gt; 3)
        );
}

&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; OptionSelections { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;As you can see, I am creating IObservables from the Checked events of the radio buttons. I’m using the Select method to make observables that simply return the index, and I’m merging those together into one IObservable&amp;lt;int&amp;gt;. So if the user checked option 1, then option 2, then option 3, the OptionSelections would call OnNext on its subscribed observers with values 1, 2 and 3 respectively. &lt;/p&gt;

&lt;p&gt;As I mentioned before, this app has 3 instances of this user control:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;LayoutRoot&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;50&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Background&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Azure&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Width&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;400&amp;quot;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;Orientation&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Horizontal&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Center&amp;quot; &amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;SilverlightApp&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ChoiceControl &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;choiceControl1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Heading&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Choice 1&amp;quot;/&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;SilverlightApp&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ChoiceControl &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;choiceControl2&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Heading&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Choice 2&amp;quot;/&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;SilverlightApp&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ChoiceControl &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;choiceControl3&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Heading&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Choice 3&amp;quot;/&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;statusText&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;TextAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Center&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now somehow I want to subscribe to the OptionSelections from each control, in such a way that I don’t see any results raised until an option from all three groups have been selected. After a few failed attempts, I stumbled upon this solution:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;MainPage()
{
    InitializeComponent();

    &lt;span style="color: blue"&gt;string &lt;/span&gt;formatString = &lt;span style="color: #a31515"&gt;&amp;quot;Option {0}, Option {1}, Option {2}&amp;quot;&lt;/span&gt;;

    &lt;span style="color: blue"&gt;var &lt;/span&gt;selections = choiceControl1.OptionSelections
        .CombineLatest(choiceControl2.OptionSelections, (i, j) =&amp;gt; &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { i, j })
        .CombineLatest(choiceControl3.OptionSelections, (array, k) =&amp;gt; &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { array[0], array[1], k });

    selections.Subscribe(values =&amp;gt; statusText.Text = &lt;span style="color: blue"&gt;string&lt;/span&gt;.Format(formatString, values[0], values[1], values[2]));            

}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I’m using the CombineLatest extension method, but it will only combine two IObservables so I have to use it twice. The first call returns an IObservable&amp;lt;int[]&amp;gt;, where the array contains two elements. I then combine that with the option selections from choiceControl3, again returning an IObservable&amp;lt;int[]&amp;gt;, this time with all 3 selections. The final step is simply to subscribe to the resulting observable and display the message. &lt;/p&gt;

&lt;p&gt;This solution of combining once into an array of two elements and then combining again into an array of three doesn’t seem particularly elegant, but so far I haven’t managed to find anything better. Perhaps I could write a version of CombineLatest that takes more than two observables and hides this ugliness? Its probably not necessary – there’s a good chance that the perfect method already exists, and I’ve just missed it. &lt;/p&gt;

&lt;p&gt;In my next post, I’d like to demonstrate some of the failed attempts I made before I found CombineLatest. This demo will give me a chance to create my first IObservable&amp;lt;IObservable&amp;lt;T&amp;gt;&amp;gt;, which I’ve been itching to do :)&lt;/p&gt;

&lt;p&gt;Today’s code has been &lt;a href="http://github.com/paulbatum/Rx-sandpit/tree/Combination-Ex1"&gt;tagged&lt;/a&gt; in my github repository.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-5065621844609161257?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/5065621844609161257/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/08/reacting-to-reactive-framework-part-6.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/5065621844609161257?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/5065621844609161257?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/08/reacting-to-reactive-framework-part-6.html" title="Reacting to the Reactive Framework: Part 6" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;DkYMRH0zcSp7ImA9WxJbFUQ.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-8695096937230654019</id><published>2009-07-26T17:34:00.000+10:00</published><updated>2009-07-26T17:43:05.389+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-26T17:43:05.389+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Reacting to the Reactive Framework: Part 5</title><content type="html">&lt;p&gt;It appears to have gone mostly under the radar, but the Reactive Framework is now out in the wild. The latest release of the &lt;a href="http://www.codeplex.com/Silverlight"&gt;Silverlight Toolkit&lt;/a&gt; includes System.Reactive.dll, mostly to facilitate the testing of the controls found within the toolkit. Jafar Husain broke the news earlier this week with &lt;a href="http://themechanicalbride.blogspot.com/2009/07/introducing-rx-linq-to-events.html"&gt;this excellent post&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Today I want to do a demo that is very similar to the previous demos I’ve done, but of course this time I’ll be using the &lt;strong&gt;real Reactive Framework&lt;/strong&gt; rather than my crappy attempt at implementing it that I’ve inflicted upon you in earlier posts. So far my experiments with using System.Reactive.dll with windows forms have not compiled properly so I’ll switch to using Silverlight for my examples. For now I will continue to focus on exposing button click events as an IObservable. Here is the code:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Event&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;&amp;gt; clicks = &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(button1, &lt;span style="color: #a31515"&gt;&amp;quot;Click&amp;quot;&lt;/span&gt;);

&lt;span style="color: blue"&gt;int &lt;/span&gt;count = 0;
clicks.Subscribe(() =&amp;gt; count++);

&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; messages = &lt;span style="color: blue"&gt;from &lt;/span&gt;c &lt;span style="color: blue"&gt;in &lt;/span&gt;clicks
                               &lt;span style="color: blue"&gt;select string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;Clicked {0} time{1}&amp;quot;&lt;/span&gt;, count, count &amp;gt; 1 ? &lt;span style="color: #a31515"&gt;&amp;quot;s&amp;quot; &lt;/span&gt;: &lt;span style="color: #a31515"&gt;&amp;quot;&amp;quot;&lt;/span&gt;);
messages.Subscribe(s =&amp;gt; button1.Content = s);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And here is the application:&lt;/p&gt;
&lt;iframe style="width: 200px; height: 200px" src="http://silverlight.services.live.com/invoke/104983/PB-Rx-Test1/iframe.html" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;

&lt;p&gt;If you are in a RSS reader, you probably won’t be able to see the embedded Silverlight app above. Pop this post out into its own browser tab so that you can revel in the glory of a button that tells you how many times its been clicked! &lt;/p&gt;

&lt;p&gt;Lets take a look at what this code is doing. The first step is to convert from an Event to an IObservable:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Event&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;&amp;gt; clicks = &lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;(button1, &lt;span style="color: #a31515"&gt;&amp;quot;Click&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;p&gt;The Observable class defines a large swath of extension methods for creating and manipulating IObservables. This overload of the FromEvent method is simple to use, but unfortunately it makes use of a magic string (“click”). There is another overload for FromEvent that allows us to do the same thing with compile-time safety, but it is more verbose. I’ve wrapped it in an extension method:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Event&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;&amp;gt; GetClicks(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Button &lt;/span&gt;button)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Observable&lt;/span&gt;.FromEvent((&lt;span style="color: #2b91af"&gt;EventHandler&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt; genericHandler) =&amp;gt; &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;RoutedEventHandler&lt;/span&gt;(genericHandler),
                                routedHandler =&amp;gt; button.Click += routedHandler,
                                routedHandler =&amp;gt; button.Click -= routedHandler);
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This overload takes three functions as arguments. One to convert from a generic event handler (EventHandler&amp;lt;T&amp;gt;) to the specific event handler that the Click event uses (RoutedEventHandler). The conversion is straightforward, because the two event handlers have the same signature. The other two functions add and remove the handler. This extension method can be used like so:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Event&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;&amp;gt; clicks = button1.GetClicks();&lt;/pre&gt;

&lt;p&gt;It would not surprise me if we eventually see extra libraries that define many of these extension methods for us. Ideally they would be unnecessary, and we could simply write:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Event&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;&amp;gt; clicks = button1.GetObservableEvent(b =&amp;gt; b.Click);&lt;/pre&gt;

&lt;p&gt;But unfortunately the dreaded &lt;em&gt;“The event 'System.Windows.Controls.Primitives.ButtonBase.Click' can only appear on the left hand side of += or –=”&lt;/em&gt;&amp;#160; message rears its ugly head. Perhaps in C# 5 the story will be different.&lt;/p&gt;

&lt;p&gt;Moving on, the code initializes a count variable and subscribes an increment function to the clicks:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;int &lt;/span&gt;count = 0;
clicks.Subscribe(() =&amp;gt; count++);&lt;/pre&gt;

&lt;p&gt;You’ll notice that I am simply passing an Action to the Subscribe method, rather than an IObserver. The Reactive Framework won’t force you to use an IObserver if all you want to do is call a function when a new event occurs. &lt;/p&gt;

&lt;p&gt;Finally, the code converts the stream of click events into a stream of messages and subscribes to it:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; messages = &lt;span style="color: blue"&gt;from &lt;/span&gt;c &lt;span style="color: blue"&gt;in &lt;/span&gt;clicks
                               &lt;span style="color: blue"&gt;select string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;Clicked {0} time{1}&amp;quot;&lt;/span&gt;, count, count &amp;gt; 1 ? &lt;span style="color: #a31515"&gt;&amp;quot;s&amp;quot; &lt;/span&gt;: &lt;span style="color: #a31515"&gt;&amp;quot;&amp;quot;&lt;/span&gt;);
messages.Subscribe(s =&amp;gt; button1.Content = s);&lt;/pre&gt;

&lt;p&gt;There are lots of other ways in which to rewrite today’s example code. This version is very short and still quite readable:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;int &lt;/span&gt;count = 0;
button1.GetClicks().Select(x =&amp;gt; ++count)
    .Subscribe(() =&amp;gt; button1.Content = &lt;span style="color: blue"&gt;string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;Clicked {0} time{1}&amp;quot;&lt;/span&gt;, count, count &amp;gt; 1 ? &lt;span style="color: #a31515"&gt;&amp;quot;s&amp;quot; &lt;/span&gt;: &lt;span style="color: #a31515"&gt;&amp;quot;&amp;quot;&lt;/span&gt;));&lt;/pre&gt;

&lt;p&gt;Or I could implement IObserver:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CountingButtonObserver &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IObserver&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Event&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;private int &lt;/span&gt;_count = 0;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Button &lt;/span&gt;Button { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;OnNext(&lt;span style="color: #2b91af"&gt;Event&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RoutedEventArgs&lt;/span&gt;&amp;gt; value)
    {
        _count++;
        Button.Content = &lt;span style="color: blue"&gt;string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;Clicked {0} time{1}&amp;quot;&lt;/span&gt;, _count, _count &amp;gt; 1 ? &lt;span style="color: #a31515"&gt;&amp;quot;s&amp;quot; &lt;/span&gt;: &lt;span style="color: #a31515"&gt;&amp;quot;&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;OnError(&lt;span style="color: #2b91af"&gt;Exception &lt;/span&gt;exception) {}
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;OnCompleted() {}
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And use it like so:&lt;/p&gt;

&lt;pre class="code"&gt;button1.GetClicks().Subscribe(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CountingButtonObserver&lt;/span&gt;{ Button = button1});&lt;/pre&gt;

&lt;p&gt;Well, that’s probably enough for today. I’m going to continue to explore the Reactive Framework and see what interesting things I can find. Oh, and let me know if you come across any documentation for it – so far I haven’t found any and it can be quite a struggle to make sense of the various extension methods that are available.&lt;/p&gt;

&lt;p&gt;I’ll be pushing my experiments with the Reactive Framework to a &lt;a href="http://github.com/paulbatum/Rx-sandpit"&gt;github repo&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/882821950355432699-8695096937230654019?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/8695096937230654019/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/07/reacting-to-reactive-framework-part-5.html#comment-form" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/8695096937230654019?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/8695096937230654019?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/07/reacting-to-reactive-framework-part-5.html" title="Reacting to the Reactive Framework: Part 5" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">9</thr:total></entry><entry gd:etag="W/&quot;D08EQ3w_cCp7ImA9WxJUGUQ.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-6890836007536899815</id><published>2009-07-19T19:29:00.000+10:00</published><updated>2009-07-19T19:30:02.248+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-19T19:30:02.248+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Reacting to the Reactive Framework: Part 4</title><content type="html">&lt;p&gt;&lt;em&gt;This post is part 4 in a &lt;a href="http://www.paulbatum.com/search/label/Reactive%20Framework"&gt;series&lt;/a&gt;. &lt;/em&gt;&lt;/p&gt;  &lt;p&gt;About a week ago &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;another video&lt;/a&gt; on the Reactive Framework went up, this time on Channel 9. It was an enjoyable video, though I found it tricky to follow in parts because my understanding of monad theory is virtually non-existent and the discussion does get abstract/theoretical in places. It did however give me a much better understanding of the basic Reactive Framework interfaces (IObserver&amp;lt;T&amp;gt; and IObservable&amp;lt;T&amp;gt;), which meant I had some work to do get my implementation up to scratch!&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Side note: I think I started this series badly by getting too complicated too fast, so I’m going to use this as an opportunity to start again.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Here are the relevant interface definitions (I haven’t specified any covariance or contravariance for these types because I am still using C# 3.):&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: #2b91af"&gt;IDisposable &lt;/span&gt;Subscribe(&lt;span style="color: #2b91af"&gt;IObserver&lt;/span&gt;&amp;lt;T&amp;gt; observer);
}

&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObserver&lt;/span&gt;&amp;lt;T&amp;gt;
{        
    &lt;span style="color: blue"&gt;void &lt;/span&gt;OnNext(T item);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;OnDone();
    &lt;span style="color: blue"&gt;void &lt;/span&gt;OnError(&lt;span style="color: #2b91af"&gt;Exception &lt;/span&gt;e);
}&lt;/pre&gt;

&lt;p&gt;Hopefully the expected interaction between these two interfaces is relatively self-explanatory. There are a few differences between this pair of interfaces and what I had in the previous posts:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Rather than passing a callback function to the Subscribe method (previously called ‘Attach’) an IObserver is passed. As you would expect, the OnNext(item) method is called on the subscribed observer when the IObservable has a new result. &lt;/li&gt;

  &lt;li&gt;The Subscribe method returns an IDisposable. When it is disposed, the IObserver is unsubscribed. &lt;/li&gt;

  &lt;li&gt;When the IObservable has finished (no more results), each of the IObservers are notified using OnDone(). &lt;/li&gt;

  &lt;li&gt;If the IObservable encounters an error, the IObservers are notified using OnError(e). &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The task today is to capture the stream of MouseDown events on a button as an IObservable&amp;lt;MouseEventArgs&amp;gt;, and then convert that into an IObservable&amp;lt;string&amp;gt; representing messages to be written to a text box. When the MouseDown event occurs, the text box should be updated accordingly. We can start by obtaining a IObservable&amp;lt;MouseEventArgs&amp;gt; like so:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;&amp;gt; mouseEvents = button1.GetMouseDowns();&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;GetMouseDowns() is an extension method – its purpose is to wrap the MouseDown event as an IObservable. Its implementation is very simple:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;&amp;gt; GetMouseDowns(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Button &lt;/span&gt;button)
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;wrapper = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EventWrapper&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;&amp;gt;();
    button.MouseDown += wrapper.Handler;
    &lt;span style="color: blue"&gt;return &lt;/span&gt;wrapper;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The EventWrapper class is wired up to the MouseDown event. It has a collection of observers which it notifies when the MouseDown event occurs:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EventWrapper&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; &lt;span style="color: blue"&gt;where &lt;/span&gt;T : &lt;span style="color: #2b91af"&gt;EventArgs
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ObserverCollection&lt;/span&gt;&amp;lt;T&amp;gt; _observers = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ObserverCollection&lt;/span&gt;&amp;lt;T&amp;gt;();

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Handler(&lt;span style="color: blue"&gt;object &lt;/span&gt;sender, T eventArgs)
    {
        _observers.NotifyNext(eventArgs);
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDisposable &lt;/span&gt;Subscribe(&lt;span style="color: #2b91af"&gt;IObserver&lt;/span&gt;&amp;lt;T&amp;gt; observer)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;_observers.Subscribe(observer);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Lets skip the implementation of the ObserverCollection for now. I’d prefer to move on to converting this IObservable&amp;lt;MouseEventArgs&amp;gt; to an IObservable&amp;lt;string&amp;gt;:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;&amp;gt; mouseEvents = button1.GetMouseDowns();
&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; messages = &lt;span style="color: blue"&gt;from &lt;/span&gt;md &lt;span style="color: blue"&gt;in &lt;/span&gt;mouseEvents
                               &lt;span style="color: blue"&gt;select &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;Mouse down at: &amp;quot; &lt;/span&gt;+ md.X + &lt;span style="color: #a31515"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt;;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This works as long as the “Select” LINQ operator has been implemented for IObservable, because the C# compiler converts the above into:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;&amp;gt; mouseEvents = button1.GetMouseDowns();
&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; messages = mouseEvents.Select( (&lt;span style="color: #2b91af"&gt;MouseEventArgs &lt;/span&gt;md) =&amp;gt; &lt;span style="color: #a31515"&gt;&amp;quot;Mouse down at: &amp;quot; &lt;/span&gt;+ md.X + &lt;span style="color: #a31515"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The following extension method has the appropriate signature:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TResult&amp;gt; Select&amp;lt;T, TResult&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; observable, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, TResult&amp;gt; func)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SelectObservable&lt;/span&gt;&amp;lt;T, TResult&amp;gt;(observable, func);            
}&lt;/pre&gt;

&lt;p&gt;By calling this method, really what we’re saying is that we want a new IObservable that calls its subscribers when the old IObservable did, but first uses the passed function “func” to convert from the old result type to the new result type. In this case, that function is the lambda expression:&lt;/p&gt;

&lt;pre class="code"&gt;(&lt;span style="color: #2b91af"&gt;MouseEventArgs &lt;/span&gt;md) =&amp;gt; &lt;span style="color: #a31515"&gt;&amp;quot;Mouse down at: &amp;quot; &lt;/span&gt;+ md.X + &lt;span style="color: #a31515"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Lets skip the implementation of the SelectObservable, and instead look at consuming the messages. I’ll subscribe an observer that will update the textbox:&lt;/p&gt;

&lt;pre class="code"&gt;messages.Subscribe(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TextBoxUpdater&lt;/span&gt;(textBox1));&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Here is the implementation for the TextBoxUpdater:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TextBoxUpdater &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IObserver&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TextBox &lt;/span&gt;_textBox;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;TextBoxUpdater(&lt;span style="color: #2b91af"&gt;TextBox &lt;/span&gt;textBox)
    {
        _textBox = textBox;
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;AppendText(&lt;span style="color: blue"&gt;string &lt;/span&gt;text)
    {
        &lt;span style="color: #2b91af"&gt;Action &lt;/span&gt;textboxUpdater = () =&amp;gt; _textBox.AppendText(text);
        _textBox.BeginInvoke(textboxUpdater);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;OnNext(&lt;span style="color: blue"&gt;string &lt;/span&gt;s)
    {
        AppendText(s);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;OnDone()
    {
        AppendText(&lt;span style="color: #a31515"&gt;&amp;quot;Done\n&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;OnError(&lt;span style="color: #2b91af"&gt;Exception &lt;/span&gt;e)
    {
        AppendText(&lt;span style="color: #a31515"&gt;&amp;quot;Error: &amp;quot; &lt;/span&gt;+ e.Message);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;As you can see, it implements the OnNext, OnDone and OnError methods by writing some appropriate text, though in this simple example, I’m not really using OnDone or OnError. If I run this program now and click the button a few times, I get this:

&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_AP_-f1YlmB4/SmLnlYCiRGI/AAAAAAAAAO0/ETzF21lZagA/s1600-h/image%5B6%5D.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="302" alt="image" src="http://lh6.ggpht.com/_AP_-f1YlmB4/SmLnmCoj38I/AAAAAAAAAO4/ZXhjj-a1VrI/image_thumb%5B2%5D.png?imgmax=800" width="304" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;That wraps it up for today. The code as of this post is available &lt;a href="http://github.com/paulbatum/Reactive/tree/pt4-example"&gt;here&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/882821950355432699-6890836007536899815?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/6890836007536899815/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/07/reacting-to-reactive-framework-part-4.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6890836007536899815?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6890836007536899815?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/07/reacting-to-reactive-framework-part-4.html" title="Reacting to the Reactive Framework: Part 4" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;CkIDRX08fCp7ImA9WxJVF0o.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-3305622474691991281</id><published>2009-07-05T15:08:00.001+10:00</published><updated>2009-07-05T15:09:34.374+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-05T15:09:34.374+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Reacting to the Reactive Framework: Part 3</title><content type="html">&lt;p&gt;In &lt;a href="http://www.paulbatum.com/2009/05/reacting-to-reactive-framework-part-1.html"&gt;part one&lt;/a&gt; of this series, I introduced the Live Labs Reactive Framework and provided a simple example of what can be achieved when using LINQ for reactive programming. In &lt;a href="http://www.paulbatum.com/2009/05/reacting-to-reactive-framework-part-2.html"&gt;part two&lt;/a&gt; I did my best to explain how my example worked. In today’s post I want to extend the example slightly. Just to reiterate, this series is not about using the Live Labs Reactive Framework as it has not yet been released. I’m exploring the idea of a reactive framework using my own implementation.&lt;/p&gt;  &lt;p&gt;Here is my example from the previous posts:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;MouseEventArgs&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; slowOperation = args =&amp;gt;
{
    System.Threading.&lt;span style="color: rgb(43,145,175)"&gt;Thread&lt;/span&gt;.Sleep(3000);
    &lt;span style="color: blue"&gt;return &lt;/span&gt;args.X;
};

&lt;span style="color: rgb(43,145,175)"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; observable = &lt;span style="color: blue"&gt;from &lt;/span&gt;md &lt;span style="color: blue"&gt;in &lt;/span&gt;button1.GetMouseDowns()
                              &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;slowOperation.AsAsyncObservable(md.EventArgs)
                              &lt;span style="color: blue"&gt;select &lt;/span&gt;x;&lt;/pre&gt;

&lt;p&gt;The idea behind this code is that the IObservable&amp;lt;int&amp;gt; represents a stream of integers that are the result of capturing the mouse down event on a button, doing some “slow processing” (really just a 3 second sleep) asynchronously, and returning the x coordinate from the mouse down event. You can then attach something to that observable like so:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; textboxUpdater = s =&amp;gt; textBox1.AppendText(s);
observable.Attach(x =&amp;gt; textBox1.BeginInvoke(textboxUpdater, &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;Mouse down: &amp;quot; &lt;/span&gt;+ x + &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt;));&lt;/pre&gt;

&lt;p&gt;The attached code updates the textbox as the values bubble up through the IObservable. Unfortunately its a little more complicated than I would like because the update has to be marshalled onto the UI thread – hence the BeginInvoke call. Today I want to modify this example so that the textbox is only updated when the right mouse button was clicked. The MouseEventArgs can tell me which button was clicked, so really this is just a matter of implementing support for &lt;em&gt;where&lt;/em&gt;:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; observable = &lt;span style="color: blue"&gt;from &lt;/span&gt;md &lt;span style="color: blue"&gt;in &lt;/span&gt;button1.GetMouseDowns()
                              &lt;span style="color: blue"&gt;where &lt;/span&gt;md.EventArgs.Button == &lt;span style="color: #2b91af"&gt;MouseButtons&lt;/span&gt;.Right
                              &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;slowOperation.AsAsyncObservable(md.EventArgs)
                              &lt;span style="color: blue"&gt;select &lt;/span&gt;x;&lt;/pre&gt;

&lt;p&gt;Well this is a very natural way to express what I want – and the implementation is not too hard. First I create the appropriate extension method:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt; predicate)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WhereObservable&lt;/span&gt;&amp;lt;T&amp;gt;(source, predicate);
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This extension method is just a wrapper call for a class. In this case, its WhereObservable&amp;lt;T&amp;gt; which takes a source IObservable, and a predicate to apply:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WhereObservable&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt;
 {
     &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; _source;
     &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt; _predicate;

     &lt;span style="color: blue"&gt;public &lt;/span&gt;WhereObservable(&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt; predicate)
     {
         _source = source;
         _predicate = predicate;
     }

     &lt;span style="color: blue"&gt;public void &lt;/span&gt;Attach(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; action)
     {
         _source.Attach(t =&amp;gt; { &lt;span style="color: blue"&gt;if &lt;/span&gt;(_predicate(t)) action(t); });
     }
 }&lt;/pre&gt;

&lt;p&gt;All I’m doing here is wrapping an inner observable so that I can check to see if the predicate applies before I let the observable event bubble up. That’s all there is to it. My example will now only update the textbox if the right mouse button was clicked.&lt;/p&gt;

&lt;p&gt;My work on this project is &lt;a href="http://github.com/paulbatum/Reactive"&gt;available&lt;/a&gt; on github. To get the code as it was at the time this post was written, use this &lt;a href="http://github.com/paulbatum/Reactive/tree/pt3-example"&gt;tag&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/882821950355432699-3305622474691991281?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/3305622474691991281/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/07/reacting-to-reactive-framework-part-3.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3305622474691991281?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3305622474691991281?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/07/reacting-to-reactive-framework-part-3.html" title="Reacting to the Reactive Framework: Part 3" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;CkIDRX08fSp7ImA9WxJVF0o.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-470853175463664427</id><published>2009-05-31T15:42:00.000+10:00</published><updated>2009-07-05T15:09:34.375+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-05T15:09:34.375+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Reacting to the Reactive Framework: Part 2</title><content type="html">&lt;p&gt;&lt;strong&gt;DISCLAIMER: The code in this post was the result of a big hackfest with the single goal of getting a particular use case working. I am telling you right now that I paid no attention to potential concurrency problems and that if you try to reuse any of this stuff you are just asking for trouble.&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;In the &lt;a href="http://www.paulbatum.com/2009/05/reacting-to-reactive-framework-part-1.html"&gt;previous post&lt;/a&gt;, I explained how Eric Meijer’s recent Lang.NET presentation on the LiveLabs Reactive Framework piqued my interest. Wondering how the framework works, I decided to have a go at emulating some of the basic functionality it appears to provide. This code demonstrates the functionality I’ve implemented so far:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; slowOperation = args =&amp;gt;
{
    System.Threading.&lt;span style="color: #2b91af"&gt;Thread&lt;/span&gt;.Sleep(3000);
    &lt;span style="color: blue"&gt;return &lt;/span&gt;args.X;
};

&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; observable = &lt;span style="color: blue"&gt;from &lt;/span&gt;md &lt;span style="color: blue"&gt;in &lt;/span&gt;button1.GetMouseDowns()
                              &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;slowOperation.AsAsyncObservable(md.EventArgs)
                              &lt;span style="color: blue"&gt;select &lt;/span&gt;x;

&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; textboxUpdater = s =&amp;gt; textBox1.AppendText(s);
observable.Attach(x =&amp;gt; textBox1.BeginInvoke(textboxUpdater, &lt;span style="color: #a31515"&gt;&amp;quot;Mouse down: &amp;quot; &lt;/span&gt;+ x + &lt;span style="color: #a31515"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt;));&lt;/pre&gt;

&lt;p&gt;Today I am going to work my way through the query comprehension you can see here and do my best to explain how I got this working. Perhaps a good place to start would be to convert the query comprehension into a method chain in the same way the C# compiler does for us under the covers. Resharper can do this automatically, which is convenient:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; observable = button1.GetMouseDowns().SelectMany(
                    md =&amp;gt; slowOperation.AsAsyncObservable(md.EventArgs), 
                    (md, x) =&amp;gt; x
                    );&lt;/pre&gt;

&lt;p&gt;The first call here is to an extension method called GetMouseDowns:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;EventResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Button&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;&amp;gt;&amp;gt; GetMouseDowns(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Button &lt;/span&gt;b)
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;wrapper = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EventWrapper&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Button&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;&amp;gt;();
    b.MouseDown += wrapper.Handle;
    &lt;span style="color: blue"&gt;return &lt;/span&gt;wrapper;
}&lt;/pre&gt;

&lt;p&gt;So far, this is relatively straightforward. The GetMouseDowns extension method creates an EventWrapper, and wires that EventWrapper up to the MouseDown event on the button. You can see that the wrapper is being returned as an IObservable of an EventResult. Here is the code for these:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;void &lt;/span&gt;Attach(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; action);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EventResult&lt;/span&gt;&amp;lt;TSender, TArgs&amp;gt;
{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;EventResult(TSender sender, TArgs args)
    {
        Sender = sender;
        EventArgs = args;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;TSender Sender { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;TArgs EventArgs { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EventWrapper&lt;/span&gt;&amp;lt;TSender, TArgs&amp;gt; : &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;EventResult&lt;/span&gt;&amp;lt;TSender,TArgs&amp;gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;EventResult&lt;/span&gt;&amp;lt;TSender, TArgs&amp;gt;&amp;gt;&amp;gt; _attached = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;EventResult&lt;/span&gt;&amp;lt;TSender, TArgs&amp;gt;&amp;gt;&amp;gt;();

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Handle(&lt;span style="color: blue"&gt;object &lt;/span&gt;sender, TArgs e)
    {
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;action &lt;span style="color: blue"&gt;in &lt;/span&gt;_attached)
            action(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EventResult&lt;/span&gt;&amp;lt;TSender,TArgs&amp;gt;((TSender)sender, e ));
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Attach(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;EventResult&lt;/span&gt;&amp;lt;TSender, TArgs&amp;gt;&amp;gt; action)
    {
        _attached.Add(action);
    }
}&lt;/pre&gt;

&lt;p&gt;Now there is some really naive code here. What would happen if someone called Attach while we were in the middle of handling the event? It would crash, because the list of actions to be called would be modified while it was being iterated over. In general, the code for the EventWrapper feels bad. I am sure it can be done much better, but it works for now.&lt;/p&gt;

&lt;p&gt;So the result of the GetMouseDowns method is an EventWrapper that will call the attached methods when the mouse down event occurs, and this is exposed as an IObservable. SelectMany is then called on that IObservable. This is another extension method:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TResult&amp;gt; SelectMany&amp;lt;TSource, TCollection, TResult&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TCollection&amp;gt;&amp;gt; collectionSelector, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, TCollection, TResult&amp;gt; resultSelector)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SelectManyObservable&lt;/span&gt;&amp;lt;TSource, TCollection, TResult&amp;gt;(source, collectionSelector, resultSelector);
}&lt;/pre&gt;

&lt;p&gt;So how on earth did I arrive at this method? Its quite simple actually – I stole its signature from the SelectMany extension method implemented on IEnumerable. The interesting thing about LINQ query comprehensions is that they actually don’t have a dependence on IEnumerable or IQueryable. Instead they depend on the existence of particular methods with the appropriate signature such as Select, SelectMany, Where, GroupBy, etc. By writing these extension methods for IObservable, I can then write query comprehensions against IObservables.&lt;/p&gt;

&lt;p&gt;Once its established that my SelectMany borrowed its signature from the appropriate extension method on IEnumerable, there isn’t much more to know about it. You can see that all it simply does is return a SelectManyObservable that wraps the passed arguments. What is the SelectManyObservable exactly? Well, here is the code:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SelectManyObservable&lt;/span&gt;&amp;lt;TSource, TCollection, TResult&amp;gt; : &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TResult&amp;gt;
{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TSource&amp;gt; _source;
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TCollection&amp;gt;&amp;gt; _collectionSelector;
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, TCollection, TResult&amp;gt; _resultSelector;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;SelectManyObservable(&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TCollection&amp;gt;&amp;gt; collectionSelector, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, TCollection, TResult&amp;gt; resultSelector)
    {
        _source = source;
        _collectionSelector = collectionSelector;
        _resultSelector = resultSelector;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Attach(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;TResult&amp;gt; action)
    {
        _source.Attach(
            s =&amp;gt; _collectionSelector(s).Attach(
                c =&amp;gt; action(_resultSelector(s, c))
            )
        );            
    }
}&lt;/pre&gt;

&lt;p&gt;So this class simply wraps an underlying IObservable, and when methods are attached to the SelecyManyObservable, it actually gets attached to the underlying IObservable. The funny thing about this code is that it practically wrote itself. It was basically a matter of just figuring out how the underlying observable, collectionSelector, resultSelector and attached action related to each other and then calling them accordingly. It felt like solving a 4 piece jigsaw puzzle with only 1 solution.&lt;/p&gt;

&lt;p&gt;Before the explanation of the query comprehension is complete, there is one more extension method that requires explanation:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TResult&amp;gt; AsAsyncObservable&amp;lt;TInput, TResult&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TInput,TResult&amp;gt; funcToObserve,TInput input)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AsyncWrapper&lt;/span&gt;&amp;lt;TInput, TResult&amp;gt;(funcToObserve, input);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This pattern should look familiar. Its like the SelectMany in that it simply returns a wrapper object that takes all the method arguments as parameters. The signature however, wasn’t borrowed from the framework. The point of this method is to allow the user to convert an anonymous delegate or lambda expression into an IObservable. Now I hope you packed the goggles I mentioned in my previous post, because AsyncWrapper is really nasty:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AsyncWrapper&lt;/span&gt;&amp;lt;TInput, TResult&amp;gt; : &lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;TResult&amp;gt;
{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; _attached = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt;();

    &lt;span style="color: blue"&gt;public &lt;/span&gt;AsyncWrapper(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TInput, TResult&amp;gt; funcToObserve, TInput input)
    {
        funcToObserve.BeginInvoke(input, CompletedCallback, &lt;span style="color: blue"&gt;null&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Attach(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;TResult&amp;gt; action)
    {
        _attached.Add(action);
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;CompletedCallback(&lt;span style="color: #2b91af"&gt;IAsyncResult &lt;/span&gt;asyncResult)
    {
        TResult calculatedValue = ((&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TInput, TResult&amp;gt;) ((&lt;span style="color: #2b91af"&gt;AsyncResult&lt;/span&gt;) asyncResult).AsyncDelegate).EndInvoke(
            asyncResult);

        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;action &lt;span style="color: blue"&gt;in &lt;/span&gt;_attached)
            action(calculatedValue);
    }
}&lt;/pre&gt;

&lt;p&gt;It might not seem so bad, until you look at what the constructor is doing. When the AsyncWrapper is created, it fires off the function to observe. Now when that function completes, the callback will be invoked, and as a result all the attached actions will also be invoked. The reason why this is all so heinous is that the actions will have to be attached AFTER the function to observe is invoked, but before it completes. As a result, I am fairly sure that if we changed the slow asynchronous operation to be much faster, then this code would stop working. Surely a better solution can be found, and I do hope to attend to this later.&lt;/p&gt;

&lt;p&gt;So that covers all the code that makes my example work. The nice thing about this approach is the composability. It is convenient to be able to work with enumerables using select, where, etc and the same is true for observables. I am really looking forward to getting my hands on the Reactive Framework code. In the mean time, I’ll continue to experiment. In the next post I’ll extend this example, starting with adding support for ‘where’ operations.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-470853175463664427?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/470853175463664427/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/05/reacting-to-reactive-framework-part-2.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/470853175463664427?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/470853175463664427?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/05/reacting-to-reactive-framework-part-2.html" title="Reacting to the Reactive Framework: Part 2" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;CkIDRX08fSp7ImA9WxJVF0o.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-3602139869019237713</id><published>2009-05-26T22:54:00.001+10:00</published><updated>2009-07-05T15:09:34.375+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-05T15:09:34.375+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Reactive Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="LINQ" /><title>Reacting to the Reactive Framework: Part 1</title><content type="html">&lt;p&gt;Last night I managed to get some code working and I was very excited, but it was far too late to start writing a blog post. Here is the code:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MouseEventArgs&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; slowOperation = args =&amp;gt;
{
    System.Threading.&lt;span style="color: #2b91af"&gt;Thread&lt;/span&gt;.Sleep(3000);
    &lt;span style="color: blue"&gt;return &lt;/span&gt;args.X;
};

&lt;span style="color: #2b91af"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; observable = &lt;span style="color: blue"&gt;from &lt;/span&gt;md &lt;span style="color: blue"&gt;in &lt;/span&gt;button1.GetMouseDowns()
                              &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;slowOperation.AsAsyncObservable(md.EventArgs)
                              &lt;span style="color: blue"&gt;select &lt;/span&gt;x;

&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; textboxUpdater = s =&amp;gt; textBox1.AppendText(s);
observable.Attach(x =&amp;gt; textBox1.BeginInvoke(textboxUpdater, &lt;span style="color: #a31515"&gt;&amp;quot;Mouse down: &amp;quot; &lt;/span&gt;+ x + &lt;span style="color: #a31515"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;This code is sitting inside a very simple windows form. The form has a button and a textbox. When the button is clicked, a message is written to the textbox about 3 seconds later, relaying the relative X coordinate of the mouse when the button was clicked. The 3 second delay represents some sort of slow asynchronous operation, currently simulated with a simple Thread.Sleep(). Because the slow operation is done on a different thread, we have to use Control.BeginInvoke() to get the textbox to update on the UI thread. GetMouseDowns() is an extension method on Button that helps set the whole thing up by returning an IObservable that is wired to the MouseDown event.&lt;/p&gt;

&lt;p&gt;So at this point you might be wondering what this is all about. To get the full story, I encourage you to watch Eric Meijer’s video on the LiveLabs Reactive Framework (&lt;a href="http://download.microsoft.com/download/7/6/A/76A69AE5-72B5-4005-BBD9-7EA5F4795014/23-ErikMeijer-LiveLabsReactiveFramework.wmv"&gt;direct wmv link&lt;/a&gt;). In this very enjoyable presentation, Eric gives us a run down the Reactive Framework, which appears to be a set of libraries that unite various types of “reactive” operations under a common pair of interfaces, IObserver&amp;lt;T&amp;gt; and IObservable&amp;lt;T&amp;gt; which are then integrated into LINQ. I found the presentation to be quite a tease. Erik shows just enough to give you an idea of what the Reactive Framework is all about, but he skims over the implementation details quite lightly. I ended up watching the thing a couple of times, trying to wrap my head around the idea of LINQ query comprehensions (e.g. from x in y select x.ID) operating against non enumerable/queryable types. In particular, I started wondering whether I could implement something like the code from this slide:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh3.ggpht.com/_AP_-f1YlmB4/ShvmhNrLXVI/AAAAAAAAAOQ/g0JZE7ls3Qo/s1600-h/image%5B4%5D.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_AP_-f1YlmB4/ShvmiuK3oeI/AAAAAAAAAOU/On8RuQREjGQ/image_thumb%5B2%5D.png?imgmax=800" width="623" height="484" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;As you can see, my code at the top is not too dissimilar from Erik’s code here. Erik’s example is a web page with dictionary suggest on a textbox. When the user enters a character into the textbox, the dictionary suggest runs asynchronously against the input entered so far and when a return value is received it is rendered as html. &lt;/p&gt;

&lt;p&gt;There is certainly quite a lot regarding the Reactive Framework that I don’t understand. I’ve been unable to find any resources beyond Erik’s talk – certainly the code doesn’t seem available anywhere. So far I don’t even understand how IObserver fits in. Can YOU see anything that might implement IObserver in the above slide? But in any case, the idea is intriguing, and trying to figure out how to do this myself is teaching me quite a bit about LINQ. In the next post, I’ll do my best to explain how the implementation works. Don’t forget your goggles, this is some pretty hacky code coming up. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-3602139869019237713?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/3602139869019237713/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/05/reacting-to-reactive-framework-part-1.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3602139869019237713?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3602139869019237713?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/05/reacting-to-reactive-framework-part-1.html" title="Reacting to the Reactive Framework: Part 1" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">5</thr:total></entry><entry gd:etag="W/&quot;CEcBQno7fCp7ImA9WxJTGU4.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-4289874705370640524</id><published>2009-04-29T01:20:00.001+10:00</published><updated>2009-04-29T01:20:53.404+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-29T01:20:53.404+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Fluent NHibernate" /><title>A Fluent NHibernate update</title><content type="html">&lt;p&gt;Since James has &lt;a href="http://www.lostechies.com/blogs/jagregory/archive/2009/04/28/what-s-been-happening-in-fluent-nhibernate-land.aspx"&gt;announced&lt;/a&gt; the latest happenings in the ongoing saga of moving Fluent NHibernate to using a semantic model, I thought a companion post might be appropriate.&lt;/p&gt;  &lt;p&gt;My &lt;a href="http://www.paulbatum.com/2008/12/fluent-nhibernate-rewrite.html"&gt;first post&lt;/a&gt; on the Fluent NHibernate rewrite is as good a place to start as any. In it I explained the limitations of the existing implementation and outlined my strategy for dissolving those limitations. My branch differs from the trunk by separating the fluent interface from the mapping model. The fluent interface manipulates the underlying model, and a family of visitors build a Hbm object graph that represents that underlying model. That object graph is serialized to xml and then passed to NHibernate. This graph consists of classes that are generated from the NHibernate mapping schema, so the serialization step is all automatic and works flawlessly.&lt;/p&gt;  &lt;p&gt;The use of the visitor pattern allows for two things. One, the mapping model is not tied to any particular output format. Sure we pass NHibernate xml today, but tomorrow it would be nice to pass it the Hbm object graph directly so it can skip the xml schema validation step. The day after it would be nice to pass it a prebuilt NHibernate.Mapping graph, which is an idea that &lt;a href="http://tunatoksoz.com/"&gt;Tuna Toksoz&lt;/a&gt; was exploring from within my branch. Secondly, the visitor implementation allowed for powerful manipulations of the mapping model that would otherwise be difficult. I talked more about the visitor implementation &lt;a href="http://www.paulbatum.com/2009/02/fluent-nhibernate-semantic-model_21.html"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Sure, passing NHibernate its mappings in a format other than xml would be nice some day, but there was another reason why I chose to use a Hbm graph instead of directly writing xml. Basically, its much harder to go off the rails when working with the Hbm objects. One example is that the NHibernate schema is finicky about element ordering and you simply don’t have to worry about this when working with Hbm objects.&lt;/p&gt;  &lt;p&gt;As time went on the code base grew, things changed, but slow and steady progress was made. The problem is that slow and steady doesn’t always win the race – specifically in the case where the goalpost is moving as fast or faster than you! This is the classic rewrite problem. I’m sure you are familiar with it – its why all the well respected software professionals tell you that rewriting your app is a fools errand. And don’t get me wrong, I am in agreement here. I approached my work to rewrite Fluent NHibernate as a prototyping exercise - “one possible future” if you will. As the work continued I would discuss our long term goals with James and for a while we found ourselves hoping that we could replace the existing trunk with my branch, if only we could “catch up” to the trunk functionality. Of course this sort of thinking was dangerous, and the consequences are well described in James’s post. My intentions, while good, have lead to a lack of progress on the Fluent NHibernate trunk and this is simply not a healthy place to be.&lt;/p&gt;  &lt;p&gt;James asked me whether I could see a way to merge the two code bases. Basically inject my model into the existing guts of the trunk. I told him I couldn’t see a way how, but I encouraged him to try. The problem, I’m sure you’ve already guessed, is that I was too “caught up” in my code and simply not prepared to make sacrifices. This is why James managed something that I could not – he merged my branch into the trunk code under an “integration”&amp;#160; branch, with all the existing trunk tests passing. Its not pretty, but I suspect that it represents the best direction to work from. We can now do what the experts tell us to do and refactor, rather than rewrite.&lt;/p&gt;  &lt;p&gt;So what were the sacrifices? The main one is the Hbm object graph approach. Fluent NHibernate will only be capable of spitting out xml for the near future. Lets face it, its not a huge loss. Plus I say near future because the visitor implementation survived, so there is no reason why we couldn’t later start retrofitting my Hbm code in. I am yet to take full stock of the “casualties”, but I expect that everything that has been lost in the merge can be regained through a gradual process of refactoring and reintroducing code and ideas from my branch. It will be fun!&lt;/p&gt;  &lt;p&gt;Finally I want to use this post as an opportunity to thank James for all his amazingly hard work on this great project. We don’t always see eye to eye but the thing that I often remind myself is that time and again he has proven to me that he has his finger on the pulse of our users and can see how this project can best fulfil their needs. Please keep it up James.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-4289874705370640524?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/4289874705370640524/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/04/fluent-nhibernate-update.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/4289874705370640524?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/4289874705370640524?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/04/fluent-nhibernate-update.html" title="A Fluent NHibernate update" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;DEQNRHY-eyp7ImA9WxJTGE0.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-1958971108848167934</id><published>2009-04-27T14:26:00.001+10:00</published><updated>2009-04-27T14:26:35.853+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-27T14:26:35.853+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Unit Testing" /><title>Legacy code: a follow up</title><content type="html">&lt;p&gt;A few weeks back I wrote a &lt;a href="http://www.paulbatum.com/2009/04/working-effectively-with-legacy-code.html"&gt;post&lt;/a&gt; on &lt;em&gt;Working Effectively with Legacy Code&lt;/em&gt;, a book by Michael Feathers. At the time I lamented that even though I accepted Michael’s definition of legacy code (code without tests), I wasn’t doing much about it – I hadn’t written any tests at work. Today I wanted to follow up on this because the last two weeks have gone much better – I’ve been writing unit tests. I was given the job of rewriting a particularly hairy module and this was simply too good an opportunity to pass up. I’m not doing TDD yet, and I certainly haven’t written as many tests as I would like, but its a start.&lt;/p&gt;  &lt;p&gt;Rather than using a mocking framework, I’ve been hand rolling stubs. I believe that the other developers will have an easier time understanding the tests if I use manual stubs. Mocking frameworks are certainly convenient but as Michael demonstrates in his book, they are not necessary &lt;em&gt;per se&lt;/em&gt;. So far I haven’t found this particularly painful and I think its a sound approach for introducing automated unit testing. I must admit that the fact that I am working on a .NET 2.0 project made this decision easier. I learned Rhino Mocks using the .NET 3.5 API and I think I would have a hard time going without the sweetness that lambda expressions provide.&lt;/p&gt;  &lt;p&gt;Writing that very first test is a bit of a barrier, but its only a mental one. I was fortunate to have a nice piece of work come along and give me a push. Hopefully it will not be necessary the next time I find myself faced with legacy code – I intend to write that first test without a moment of hesitation. Its all downhill from there.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-1958971108848167934?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/1958971108848167934/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/04/legacy-code-follow-up.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/1958971108848167934?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/1958971108848167934?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/04/legacy-code-follow-up.html" title="Legacy code: a follow up" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;DU8DR3o8eSp7ImA9WxVaFk8.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-4734849722941724737</id><published>2009-04-13T23:04:00.001+10:00</published><updated>2009-04-13T23:04:36.471+10:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-13T23:04:36.471+10:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Books" /><title>Working Effectively with Legacy Code</title><content type="html">&lt;img style="display: inline; margin-left: 0px; margin-right: 0px" border="0" alt="Working Effectively with Legacy Code (Robert C. Martin Series)" align="right" src="http://ecx.images-amazon.com/images/I/51RCXGPXQ8L._SL500_AA240_.jpg" width="240" height="240" /&gt;  &lt;p&gt;Today I finished reading &lt;em&gt;Working Effectively with Legacy Code&lt;/em&gt; by Michael Feathers. If you are not familiar with this book, you might be wondering if I’ve somehow been roped into maintaining some sort of 10 year old VB6 application -fortunately this is not the case. But I am indeed working on a legacy application – at least, it is legacy by Michael’s rather unique definition. Michael defines legacy code as code that is not under test, specifically unit tests. By Michael’s definition, virtually all of the code I have written during my career was legacy from the day it was born, and when I reflect on it, this seems like a fair statement. Here is a short excerpt from the preface:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;Code without tests is bad code. It doesn’t matter how well written it is; it doesn’t matter how pretty or object-oriented or well-encapsulated it is. With tests, we can change the behaviour of our code quickly and verifiably. Without them, we really don’t know if our code is getting better or worse.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;It doesn’t matter how clean and refactored my code was – developers that had to maintain it were forced to do so with uncertainty. It is specifically that element of uncertainty that I associate with the legacy code experience.&lt;/p&gt;  &lt;p&gt;The book uses a FAQ format, with chapter titles such as: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;I need to make a change. What methods should I test?&lt;/li&gt;    &lt;li&gt;I can’t get this class into a test harness.&lt;/li&gt;    &lt;li&gt;This class is too big and I don’t want it to get any bigger.&lt;/li&gt;    &lt;li&gt;I need to make a change but I don’t know what tests to write.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;It does a great job of illustrating refactorings that let you break dependencies so you can get the code under test. These refactorings are designed to be performed safely without tests so you can get the tests written and then move on to more significant refactorings. The book also does a great job of tackling the mechanics of writing the tests themselves. &lt;/p&gt;  &lt;p&gt;I think the book could have been better named. Ayende &lt;a href="http://ayende.com/Blog/archive/2005/08/28/BookReviewWorkingEffectivelyWithLegacyCode.aspx"&gt;says&lt;/a&gt; that it should be mandatory reading for people that write code for a living. I agree with him, but the title does not communicate this. In general I found it very readable and relatively quick to get through, and the lessons the book offers are profound.&lt;/p&gt;  &lt;p&gt;So the obvious question is whether it has changed the way I’ve been writing code. Well unfortunately, I wrote a bunch of legacy code just last week! By night I revel in the freedom that my unit tests give me as I work on Fluent NHibernate, but by day I continue to work in a manner that Uncle Bob would consider &lt;a href="http://www.infoq.com/interviews/coplien-martin-tdd"&gt;unprofessional&lt;/a&gt;. Why?&lt;/p&gt;  &lt;p&gt;Unfortunately the book doesn’t have a chapter called “&lt;em&gt;I’m all alone, nobody else is convinced that writing unit tests is worthwhile. Is it worth starting if its just me doing it?&lt;/em&gt;”. Nor does it have a “&lt;em&gt;This is just a quick fix for someone else’s broken code, I’ll write tests when the –real- work begins&lt;/em&gt;” chapter (its a weak argument but I’ve found it an easy trap to fall into). The closest the book comes is the very last FAQ chapter: “&lt;em&gt;We feel overwhelmed. It isn’t going to get any better&lt;/em&gt;”. But at less than 2 pages, it didn’t quite deliver what I needed to hear.&lt;/p&gt;  &lt;p&gt;I’m finding it difficult to take that first step and add that 55th project to the solution (yeah…) so I can write some tests. Part of it is procrastination, but part of it is fear. I believe these ideas have value and I don’t want to screw it up. But simply “waiting until the time is right” is the refrain of the procrastinator. &lt;/p&gt;  &lt;p&gt;This makes me feel that Working with Legacy Code is a great book, but not an entirely complete package. It gives you the tools and techniques but assumes that the reader can simply read it and run with it. Michael developed these techniques as he worked with teams that heeded his advice and were prepared to follow his lead. A piece of the puzzle is missing because Michael has been the consultant for so long.&lt;/p&gt;  &lt;p&gt;Maybe this criticism is unfair. People can write books full of advice, but its up to the reader to start putting that advice into practice. A new work week begins tomorrow, perhaps I’ll add that 55th project before I do anything else tomorrow morning.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-4734849722941724737?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/4734849722941724737/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/04/working-effectively-with-legacy-code.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/4734849722941724737?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/4734849722941724737?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/04/working-effectively-with-legacy-code.html" title="Working Effectively with Legacy Code" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">5</thr:total></entry><entry gd:etag="W/&quot;DE8GRHYyfyp7ImA9WxVVFUo.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-3067325777306508721</id><published>2009-03-09T16:30:00.000+11:00</published><updated>2009-03-09T16:33:45.897+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-09T16:33:45.897+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Fluent NHibernate" /><title>Supporting multiple NHibernate versions in Fluent NHibernate semantic model</title><content type="html">&lt;p&gt;My &lt;a href="http://fluentnhibernate.org"&gt;Fluent NHibernate&lt;/a&gt; semantic model rewrite is designed to support multiple versions of NHibernate simultaneously. At the moment, I support NH 2.0.1GA and 2.1.0.1001 (this was a trunk snapshot). My goal is to support the latest official release and to keep as up to date with the trunk as possible; time will tell how well this pans out. &lt;/p&gt; &lt;p&gt;The semantic model rewrite makes heavy use of classes that are generated from the NH mapping schema. These classes are all prefixed with Hbm, so I am in the habit of calling them “Hbm*” classes. Here is some example code that builds a HbmKey representation of a KeyMapping:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;ProcessKey(&lt;span style="color: #2b91af"&gt;KeyMapping &lt;/span&gt;keyMapping)
{
    _hbm = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmKey&lt;/span&gt;();

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(keyMapping.Attributes.IsSpecified(x =&amp;gt; x.Column))
        _hbm.column1 = keyMapping.Column;

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(keyMapping.Attributes.IsSpecified(x =&amp;gt; x.ForeignKey))
        _hbm.foreignkey = keyMapping.ForeignKey;

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(keyMapping.Attributes.IsSpecified(x =&amp;gt; x.PropertyReference))
        _hbm.propertyref = keyMapping.PropertyReference;

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(keyMapping.Attributes.IsSpecified(x =&amp;gt; x.CascadeOnDelete))
        _hbm.SetCascadeOnDelete(keyMapping.CascadeOnDelete);
}&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Because the NH mapping schema changes from version to version, the public interface for these classes also changes from version to version. See that “column1” property? Its entirely possible it was called “column” in an earlier version of NH. Obviously, if it were to change back to “column” tomorrow, this code would no longer compile. Given this, how can Fluent NH hope to simultaneously support multiple NH versions? The answer is to put any version specific code in a separate assembly.&lt;/p&gt;
&lt;p&gt;Today I will fix a NH2.1 incompatibility that I introduced a few days ago when adding the ability to specify the column name for a property. Here is the code I wrote while working against NH2.0.1:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;ProcessProperty(&lt;span style="color: #2b91af"&gt;PropertyMapping &lt;/span&gt;propertyMapping)
{
    _hbm = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmProperty&lt;/span&gt;();
    _hbm.name = propertyMapping.Name;

    &lt;span style="color: blue"&gt;if&lt;/span&gt;(propertyMapping.Attributes.IsSpecified(x =&amp;gt; x.IsNotNullable))
        _hbm.SetNotNull(propertyMapping.IsNotNullable);

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(propertyMapping.Attributes.IsSpecified(x =&amp;gt; x.Length))
        _hbm.length = propertyMapping.Length.ToString();

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(propertyMapping.Attributes.IsSpecified(x =&amp;gt; x.ColumnName))
        _hbm.column1 = propertyMapping.ColumnName;
}&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The very last line is the one to watch here. You can see its setting the “column1” property. This worked fine against NH2.0.1 but when I ran my rake script to switch over to NH2.1 today, this code no longer compiled - the property is now called “column”. As I mentioned above, my strategy for dealing with this problem is to use version specific assemblies. Here is the Fluent NH solution:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://lh4.ggpht.com/_AP_-f1YlmB4/SbSqNLSPX5I/AAAAAAAAAOI/C0GAE1IwKYs/s1600-h/image%5B3%5D.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="125" alt="image" src="http://lh6.ggpht.com/_AP_-f1YlmB4/SbSqN8UizVI/AAAAAAAAAOM/4y1gC6Aame8/image_thumb%5B1%5D.png?imgmax=800" width="259" border="0"&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;The two “Versioning” projects are where the version specific code goes – they each reference their own version of NHibernate. Each project contains the same set of extensions methods, each method implemented slightly differently depending on the versioning requirements. The two projects share the same namespace and output an assembly with the same name (FluentNHibernate.Versioning) and to the same location. Neither project is included in the default build configuration, so they have to be built explicitly. The act of building one of these versioning projects will make it “active” because the assembly is output to the same location that the FluentNHibernate project is referencing.&lt;/p&gt;
&lt;p&gt;With the background out of the way, lets fix the problem with with “column1” property on HbmProperty. First I open the Versioning.NH20 project, find the HbmPropertyExtensions and add an extension method:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmPropertyExtensions
&lt;/span&gt;{
    ...&lt;br&gt;
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;SetColumn(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmProperty &lt;/span&gt;hbmProperty, &lt;span style="color: blue"&gt;string &lt;/span&gt;column)
    {
        hbmProperty.column1 = column;
    }
}&lt;/pre&gt;
&lt;p&gt;I then modify the code to call the extension method:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;(propertyMapping.Attributes.IsSpecified(x =&amp;gt; x.ColumnName))
    _hbm.SetColumn(propertyMapping.ColumnName);&lt;/pre&gt;
&lt;p&gt;I compile the Versioning.NH20 project to make sure its active and run my tests. I already have a test that is verifying this implementation – here it is:&lt;/p&gt;&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;Should_write_the_attributes()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;testHelper = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmTestHelper&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;PropertyMapping&lt;/span&gt;&amp;gt;();
    testHelper.Check(x =&amp;gt; x.Name, &lt;span style="color: #a31515"&gt;"test"&lt;/span&gt;).MapsToAttribute(&lt;span style="color: #a31515"&gt;"name"&lt;/span&gt;);
    testHelper.Check(x =&amp;gt; x.Length, 50).MapsToAttribute(&lt;span style="color: #a31515"&gt;"length"&lt;/span&gt;);
    testHelper.Check(x =&amp;gt; x.IsNotNullable, &lt;span style="color: blue"&gt;true&lt;/span&gt;).MapsToAttribute(&lt;span style="color: #a31515"&gt;"not-null"&lt;/span&gt;);
    testHelper.Check(x =&amp;gt; x.ColumnName, &lt;span style="color: #a31515"&gt;"thecolumn"&lt;/span&gt;).MapsToAttribute(&lt;span style="color: #a31515"&gt;"column"&lt;/span&gt;); &lt;font color="#ff0000"&gt;&lt;strong&gt;&amp;lt;--- HERE&lt;/strong&gt;&lt;/font&gt;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;writer = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmPropertyWriter&lt;/span&gt;();
    testHelper.VerifyAll(writer);
}&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Because this test verifies that a certain property is written to the correct xml attribute, it works for both versions of NH. Regardless of what the property is called on the Hbm class, its written to the “column” attribute. &lt;/p&gt;
&lt;p&gt;The tests all pass, so I switch to NH2.1 using my rake script and move to the Versioning.NH21 project. Again, I add an extension method:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmPropertyExtensions
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;...&lt;br&gt;&lt;/span&gt;
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;SetColumn(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmProperty &lt;/span&gt;hbmProperty, &lt;span style="color: blue"&gt;string &lt;/span&gt;column)
    {
        hbmProperty.column = column;            
    }
}&lt;/pre&gt;
&lt;p&gt;This looks almost the same as the code above, but notice that the “1” is gone. I compile the Versioning.NH21 project to make sure its active and run the tests. They all pass!&lt;/p&gt;
&lt;p&gt;So far, all the versioning issues I’ve ran into were easily fixed like the one above. Lets hope they are all this simple!&lt;/p&gt;&lt;pre class="code"&gt;&amp;nbsp;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-3067325777306508721?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/3067325777306508721/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/03/supporting-multiple-nhibernate-versions.html#comment-form" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3067325777306508721?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3067325777306508721?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/03/supporting-multiple-nhibernate-versions.html" title="Supporting multiple NHibernate versions in Fluent NHibernate semantic model" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">4</thr:total></entry><entry gd:etag="W/&quot;DEEERn44fSp7ImA9WxVWEUQ.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-6904253731521241877</id><published>2009-02-21T17:09:00.000+11:00</published><updated>2009-02-21T17:10:07.035+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-02-21T17:10:07.035+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Fluent NHibernate" /><title>Fluent NHibernate semantic model: Visitors</title><content type="html">&lt;p&gt;My work-in-progress semantic model based version of &lt;a href="http://fluentnhibernate.org"&gt;Fluent NHibernate&lt;/a&gt; makes heavy use of the &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;visitor pattern&lt;/a&gt;. Currently, the visitor implementation is there to serve two purposes:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Facilitate the construction of a Hbm* representation of the mapping model. Hbm* refers to the set of classes found in the NHibernate.Cfg.MappingSchema namespace that are generated from the NHibernate mapping schema. My version of Fluent NHibernate communicates with NHibernate by serializing the Hbm* representation to xml. &lt;/li&gt;    &lt;li&gt;Enable powerful, user-defined conventions that walk the mapping model and make changes. The NamingConvention class is a very simple example of this – it takes mapping model instances and sets their Name property based on reflected data such as the System.Type or the PropertyInfo. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Lets begin by looking at the implementation of AcceptVisitor for the root of the mapping model – HibernateMapping:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;AcceptVisitor(&lt;span style="color: #2b91af"&gt;IMappingModelVisitor &lt;/span&gt;visitor)
{
    visitor.ProcessHibernateMapping(&lt;span style="color: blue"&gt;this&lt;/span&gt;);

    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;classMapping &lt;span style="color: blue"&gt;in &lt;/span&gt;Classes)
        visitor.Visit(classMapping);
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This is reasonably straightforward. The HibernateMapping tells the visitor to first process a HibernateMapping instance, and passes itself as the argument. Then it tells the visitor to visit each of the child classes. What the visitor does when its told to visit a ClassMapping is its business, but what it is &lt;em&gt;likely&lt;/em&gt; to do is call AcceptVisitor on the ClassMapping:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;AcceptVisitor(&lt;span style="color: #2b91af"&gt;IMappingModelVisitor &lt;/span&gt;visitor)
{
    visitor.ProcessClass(&lt;span style="color: blue"&gt;this&lt;/span&gt;);            

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(Id != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        visitor.Visit(Id);

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(Discriminator != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        visitor.Visit(Discriminator);

    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;subclass &lt;span style="color: blue"&gt;in &lt;/span&gt;Subclasses)
        visitor.Visit(subclass);

    &lt;span style="color: blue"&gt;base&lt;/span&gt;.AcceptVisitor(visitor);
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This is similar to the previous AcceptVisitor implementation, but its worth noting that at the end, it calls base.AcceptVisitor(visitor). This is necessary because ClassMapping inherits from a common base class (JoinedSubclassMapping and SubclassMapping also inherit from this base class). Here is AcceptVisitor on ClassMappingBase:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;AcceptVisitor(&lt;span style="color: #2b91af"&gt;IMappingModelVisitor &lt;/span&gt;visitor)
{
    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;collection &lt;span style="color: blue"&gt;in &lt;/span&gt;Collections)
        visitor.Visit(collection);

    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;property &lt;span style="color: blue"&gt;in &lt;/span&gt;Properties)
        visitor.Visit(property);

    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;reference &lt;span style="color: blue"&gt;in &lt;/span&gt;References)
        visitor.Visit(reference);
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Of course – all class mappings, regardless of how they fit into an inheritance hierarchy, can have collections, properties and references (many-to-ones). Its probably not necessary to follow this any further. The important point is that as long as the visitor calls AcceptVisitor when it is told to visit something, then it will make its way along the entire mapping model. To make life easier, I’ve implemented a DefaultMappingModelVisitor class that does precisely this. It has a whole bunch of code that all looks very similar to this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;Visit(&lt;span style="color: #2b91af"&gt;PropertyMapping &lt;/span&gt;propertyMapping)
{
    propertyMapping.AcceptVisitor(&lt;span style="color: blue"&gt;this&lt;/span&gt;);
}

&lt;span style="color: blue"&gt;public override void &lt;/span&gt;Visit(&lt;span style="color: #2b91af"&gt;ManyToOneMapping &lt;/span&gt;manyToOneMapping)
{
    manyToOneMapping.AcceptVisitor(&lt;span style="color: blue"&gt;this&lt;/span&gt;);
}

&lt;span style="color: blue"&gt;public override void &lt;/span&gt;Visit(&lt;span style="color: #2b91af"&gt;KeyMapping &lt;/span&gt;keyMapping)
{
    keyMapping.AcceptVisitor(&lt;span style="color: blue"&gt;this&lt;/span&gt;);
}&lt;/pre&gt;

&lt;pre class="code"&gt;.. Many more Visit methods&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Now you might be looking at this and wondering why this is necessary. Why can’t we skip this completely, and just have AcceptVisitor implementations that will call AcceptVisitor directly like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;AcceptVisitor(&lt;span style="color: #2b91af"&gt;IMappingModelVisitor &lt;/span&gt;visitor)
{
    visitor.ProcessHibernateMapping(&lt;span style="color: blue"&gt;this&lt;/span&gt;);

    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;classMapping &lt;span style="color: blue"&gt;in &lt;/span&gt;Classes)
        classMapping.AcceptVisitor(visitor); &lt;font color="#ff0000"&gt;&lt;strong&gt;&amp;lt;--- JUST DO THIS??&lt;/strong&gt;&lt;/font&gt;
}&lt;/pre&gt;

&lt;p&gt;The answer is that the proposed change will work when you want one single visitor instance to visit the entire mapping model. While this works fine for conventions (as you will see in a moment), it does not work so well for building the Hbm representation. I’ll get to that in a second, but lets first take a look at the simpler case of the conventions. Here is a gutted version of the NamingConvention:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;NamingConvention &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;DefaultMappingModelVisitor
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MemberInfo&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; DetermineNameFromMember = info =&amp;gt; info.Name;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; DetermineNameFromType = type =&amp;gt; type.AssemblyQualifiedName;

    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;ProcessOneToMany(&lt;span style="color: #2b91af"&gt;OneToManyMapping &lt;/span&gt;oneToManyMapping)
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(!oneToManyMapping.Attributes.IsSpecified(x =&amp;gt; x.ClassName))
        {
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(oneToManyMapping.ChildType == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ConventionException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Cannot apply the naming convention. No type specified.&amp;quot;&lt;/span&gt;, oneToManyMapping);
            oneToManyMapping.ClassName = DetermineNameFromType(oneToManyMapping.ChildType);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;I’ve removed the majority of its implementation for the sake of brevity. As it currently stands, it will walk the entire mapping model (because it inherits from the aforementioned DefaultMappingModelVisitor), and when it encounters a OneToManyMapping, it will attempt to set its ClassName based on the ChildType property. Its worth noting that the full implementation of the NamingConvention class actually handles naming of many other mappings types, such as ClassMappings, ManyToManyMappings, etc. This means that this visitor completely handles the concern of setting the name of mapping model elements for the &lt;em&gt;entire&lt;/em&gt; mapping model. This point is important, because the next example is different.&amp;#160; As I mentioned before, this visitor implementation would work fine with the previous simplification of having AcceptVisitor directly call AcceptVisitor on the children. Lets now move on to the process of building a Hbm* representation, and examine why the simplification won’t work so well for this case.&lt;/p&gt;

&lt;p&gt;I define an interface for classes that build Hbm:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IHbmWriter&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;object &lt;/span&gt;Write(T mappingModel);        
}    &lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Here is an example implementor, a hbm writer that will handle ColumnMappings:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmColumnWriter &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;NullMappingModelVisitor&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IHbmWriter&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ColumnMapping&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmColumn &lt;/span&gt;_hbm;

    &lt;span style="color: blue"&gt;public object &lt;/span&gt;Write(&lt;span style="color: #2b91af"&gt;ColumnMapping &lt;/span&gt;mappingModel)
    {
        _hbm = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
        mappingModel.AcceptVisitor(&lt;span style="color: blue"&gt;this&lt;/span&gt;);
        &lt;span style="color: blue"&gt;return &lt;/span&gt;_hbm;
    }

    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;ProcessColumn(&lt;span style="color: #2b91af"&gt;ColumnMapping &lt;/span&gt;columnMapping)
    {
        _hbm = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmColumn&lt;/span&gt;();
        _hbm.name = columnMapping.Name;
        
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(columnMapping.Attributes.IsSpecified(x =&amp;gt; x.IsNotNullable))
        {
            _hbm.notnull = columnMapping.IsNotNullable;
            _hbm.notnullSpecified = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
        }

        &lt;span style="color: blue"&gt;if &lt;/span&gt;(columnMapping.Attributes.IsSpecified(x =&amp;gt; x.Length))
            _hbm.length = columnMapping.Length.ToString();
        &lt;br /&gt;        //etc&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&lt;/span&gt;    }
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;You’ll notice that this class inherits from NullMappingModelVisitor, which is basically a blank implementation of IMappingModelVisitor. It has all the methods, but none of them do anything. So this visitor ONLY knows how to handle ColumnMappings - if its passed to any other type of mapping, it will do nothing. This is certainly a difference approach to the NamingConvention, which actually knew how to set the name for Classes, OneToMany’s, ManyToMany’s and many other mapping model elements. So why does this difference exist? Basically, the job of generating all the Hbm that NHibernate requires is too big for one class. Creating separate classes for generating the appropriate HBM helps make the job more manageable. These classes can then be composed, like so:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmIdWriter &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;NullMappingModelVisitor&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IHbmWriter&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IdMapping&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IHbmWriter&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ColumnMapping&lt;/span&gt;&amp;gt; _columnWriter;
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IHbmWriter&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IdGeneratorMapping&lt;/span&gt;&amp;gt; _generatorWriter;

    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmId &lt;/span&gt;_hbm;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;HbmIdWriter(&lt;span style="color: #2b91af"&gt;IHbmWriter&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ColumnMapping&lt;/span&gt;&amp;gt; columnWriter, &lt;span style="color: #2b91af"&gt;IHbmWriter&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IdGeneratorMapping&lt;/span&gt;&amp;gt; generatorWriter)
    {
        _columnWriter = columnWriter;
        _generatorWriter = generatorWriter;
    }

    &lt;span style="color: blue"&gt;public object &lt;/span&gt;Write(&lt;span style="color: #2b91af"&gt;IdMapping &lt;/span&gt;mappingModel)
    {
        _hbm = &lt;span style="color: blue"&gt;null&lt;/span&gt;; 
        mappingModel.AcceptVisitor(&lt;span style="color: blue"&gt;this&lt;/span&gt;);
        &lt;span style="color: blue"&gt;return &lt;/span&gt;_hbm;
    }

    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;ProcessId(&lt;span style="color: #2b91af"&gt;IdMapping &lt;/span&gt;idMapping)
    {
        _hbm = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmId&lt;/span&gt;();

        &lt;span style="color: blue"&gt;if&lt;/span&gt;(idMapping.Attributes.IsSpecified(x =&amp;gt; x.Name))
            _hbm.name = idMapping.Name;
    }

    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;Visit(&lt;span style="color: #2b91af"&gt;ColumnMapping &lt;/span&gt;columnMapping)
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;columnHbm = (&lt;span style="color: #2b91af"&gt;HbmColumn&lt;/span&gt;) _columnWriter.Write(columnMapping);
        columnHbm.AddTo(&lt;span style="color: blue"&gt;ref &lt;/span&gt;_hbm.column);
    }

    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;Visit(&lt;span style="color: #2b91af"&gt;IdGeneratorMapping &lt;/span&gt;generatorMapping)
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;generatorHbm = (&lt;span style="color: #2b91af"&gt;HbmGenerator&lt;/span&gt;) _generatorWriter.Write(generatorMapping);
        _hbm.generator = generatorHbm;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This hbm writer handles IdMappings. IdMappings include one or more columns and a generator, so this writer composes a IHbmWriter&amp;lt;ColumnMapping&amp;gt; and a IHbmWriter&amp;lt;IdGeneratorMapping&amp;gt;. In this way, the task of creating the hbm representation can be managed by a &lt;em&gt;family&lt;/em&gt; of visitors that delegate to each other as required.&lt;/p&gt;

&lt;p&gt;Finally now, I can return to the previous point of why all the AcceptVisitor implementations call visitor.Visit(child) rather than child.AcceptVisitor(visitor). The former allows the current visitor to see that a &lt;strong&gt;different visitor&lt;/strong&gt; is passed in when calling child.AcceptVisitor(). You can see some of this happening above, in the override for Visit(ColumnMapping) – it asks the IHbmWriter&amp;lt;ColumnMapping&amp;gt; to write the column. The implementation of that method will call columnMapping.AcceptVisitor(this). Thus, the Fluent NHibernate semantic model has an implementation of the visitor pattern that supports both single visitors that visit the entire graph themselves, and families of visitors that collaborate to get a large job done.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-6904253731521241877?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/6904253731521241877/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/02/fluent-nhibernate-semantic-model_21.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6904253731521241877?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6904253731521241877?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/02/fluent-nhibernate-semantic-model_21.html" title="Fluent NHibernate semantic model: Visitors" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;CEYDRH49cSp7ImA9WxVXEEo.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-2063340314492527546</id><published>2009-02-08T16:34:00.000+11:00</published><updated>2009-02-08T16:49:35.069+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-02-08T16:49:35.069+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Fluent NHibernate" /><title>Fluent NHibernate semantic model: AttributeStore&lt;T&gt;</title><content type="html">&lt;p&gt;My &lt;a href="http://fluent-nhibernate.googlecode.com/svn/branches/pb-rewrite/"&gt;work&lt;/a&gt; to rewrite &lt;a href="http://fluentnhibernate.org"&gt;Fluent NHibernate&lt;/a&gt; using a semantic model continues at a reasonable pace. I will admit there is some unconventional stuff in the code base, and much of it deserves explanation. Today I would like to explain AttributeStore&amp;lt;T&amp;gt; - what it is for and how it works. Lets start by taking a look at the model class for the contents of a collection with OneToMany semantics:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OneToManyMapping &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;MappingBase&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;ICollectionContentsMapping
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;OneToManyMapping&lt;/span&gt;&amp;gt; _attributes;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;OneToManyMapping()
    {
        _attributes = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;OneToManyMapping&lt;/span&gt;&amp;gt;();
        _attributes.SetDefault(x =&amp;gt; x.ExceptionOnNotFound, &lt;span style="color: blue"&gt;true&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;OneToManyMapping&lt;/span&gt;&amp;gt; Attributes
    {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;_attributes; }
    }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;ClassName
    {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;_attributes.Get(x =&amp;gt; x.ClassName); }
        &lt;span style="color: blue"&gt;set &lt;/span&gt;{ _attributes.Set(x =&amp;gt; x.ClassName, &lt;span style="color: blue"&gt;value&lt;/span&gt;); }
    }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;ExceptionOnNotFound
    {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;_attributes.Get(x =&amp;gt; x.ExceptionOnNotFound); }
        &lt;span style="color: blue"&gt;set &lt;/span&gt;{ _attributes.Set(x =&amp;gt; x.ExceptionOnNotFound, &lt;span style="color: blue"&gt;value&lt;/span&gt;); }
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see, I am doing something unusual in some of the getters and setters. Basically, I am storing the values of certain properties in a dictionary, and these values are keyed on the name of the property you use to access them. Its very easy to add new attributes, I use this Resharper live template:&lt;/p&gt;

&lt;pre class="code"&gt;public $ReturnType$ $PropertyName$
{
    get { return $_attributes$.Get(x =&amp;gt; x.$PropertyName$); }
    set { $_attributes$.Set(x =&amp;gt; x.$PropertyName$, value); }
}&lt;/pre&gt;

&lt;p&gt;This approach allows me to write code that asks questions about properties beyond simply “what is the value?”. Here is an example from the NamingConvention class:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;ProcessOneToMany(&lt;span style="color: #2b91af"&gt;OneToManyMapping &lt;/span&gt;oneToManyMapping)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(!oneToManyMapping.Attributes.IsSpecified(x =&amp;gt; x.ClassName))
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(oneToManyMapping.ChildType == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
            &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ConventionException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Cannot apply the naming convention. No type specified.&amp;quot;&lt;/span&gt;, oneToManyMapping);
        oneToManyMapping.ClassName = DetermineNameFromType(oneToManyMapping.ChildType);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This convention walks the mapping model, naming mappings based on the assigned Type or MemberInfo. In this example, if the ClassName property for the OneToManyMapping hasn’t been specified explicitly, then the NamingConvention uses the ChildType property to set the ClassName. If the user has set the ClassName themselves, then I don’t want the NamingConvention to overwrite that, so I ask the question “Is the ClassName property &lt;strong&gt;specified&lt;/strong&gt;?”. If the ClassName property was just implemented as an autoproperty, I would probably have to check if it was null. But what if the property was a bool? Make it a nullable bool? Then I would have nasty if(blah.HasValue) code in various places. Yuck! 

&lt;p&gt;Here is another example, this time from the class that creates a HbmOneToMany instance based on my OneToManyMapping:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;ProcessOneToMany(&lt;span style="color: #2b91af"&gt;OneToManyMapping &lt;/span&gt;oneToManyMapping)
{
    _hbmOneToMany = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HbmOneToMany&lt;/span&gt;();
    _hbmOneToMany.@class = oneToManyMapping.ClassName;

    &lt;span style="color: blue"&gt;if&lt;/span&gt;(oneToManyMapping.Attributes.IsSpecified(x =&amp;gt; x.ExceptionOnNotFound))
    {
        _hbmOneToMany.SetNotFound(oneToManyMapping.ExceptionOnNotFound);
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This code always sets the @class field on the HbmOneToMany, but it won’t always call SetNotFound. It only calls SetNotFound if the the ExceptionOnNotFound property was &lt;strong&gt;specified&lt;/strong&gt;. The point of this behaviour is to only generate the xml the user desires. It is not mandatory to set the not-found attribute on a one-to-many element, so why write it if the user hasn’t specified it?&lt;/p&gt;

&lt;p&gt;As well as being able to ask questions about the properties, I also wanted a convenient way to copy them. The next code sample is the code for OneToManyPart. This class is part of the fluent interface for FluentNHibernate. It builds up information on the collection being mapped, and builds the appropriate collection when ResolveCollectionMapping() is called (obviously the IsInverse property is the only value copied at the moment, but that will change as the supported functionality grows):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OneToManyPart&lt;/span&gt;&amp;lt;PARENT, CHILD&amp;gt; : &lt;span style="color: #2b91af"&gt;IDeferredCollectionMapping
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PropertyInfo &lt;/span&gt;_info;
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ICollectionMapping&lt;/span&gt;&amp;gt; _attributes;

    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ICollectionMapping&lt;/span&gt;&amp;gt; _collectionBuilder;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;OneToManyPart(&lt;span style="color: #2b91af"&gt;PropertyInfo &lt;/span&gt;info)
    {
        _info = info;
        _attributes = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ICollectionMapping&lt;/span&gt;&amp;gt;();
        AsBag();   
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OneToManyPart&lt;/span&gt;&amp;lt;PARENT, CHILD&amp;gt; AsBag()
    {
        _collectionBuilder = () =&amp;gt; &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BagMapping&lt;/span&gt;();
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OneToManyPart&lt;/span&gt;&amp;lt;PARENT, CHILD&amp;gt; AsSet()
    {
        _collectionBuilder = () =&amp;gt; &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SetMapping&lt;/span&gt;();
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OneToManyPart&lt;/span&gt;&amp;lt;PARENT, CHILD&amp;gt; IsInverse()
    {
        _attributes.Set(x =&amp;gt; x.IsInverse, &lt;span style="color: blue"&gt;true&lt;/span&gt;);
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: #2b91af"&gt;ICollectionMapping IDeferredCollectionMapping&lt;/span&gt;.ResolveCollectionMapping()
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;collection = _collectionBuilder();       
        _attributes.CopyTo(collection.Attributes);

        collection.PropertyInfo = _info;            
        collection.Key = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;KeyMapping&lt;/span&gt;();
        collection.Contents = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OneToManyMapping &lt;/span&gt;{ChildType = &lt;span style="color: blue"&gt;typeof &lt;/span&gt;(CHILD)};

        &lt;span style="color: blue"&gt;return &lt;/span&gt;collection;
    }

}&lt;/pre&gt;

&lt;p&gt;The relevant lines are at the beginning of ResolveCollectionMapping(). Once the collection instance is created, the attributes collected in the _attributes field are copied to the AttributeStore for the new collection instance. &lt;/p&gt;

&lt;p&gt;Well that is probably enough examples of why I am using this pattern. Now I want to run through the implementation. Lets start with AttributeStore&amp;lt;T&amp;gt;:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore &lt;/span&gt;_store;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;AttributeStore()
        : &lt;span style="color: blue"&gt;this&lt;/span&gt;(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;())
    {

    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;AttributeStore(&lt;span style="color: #2b91af"&gt;AttributeStore &lt;/span&gt;store)
    {
        _store = store;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;U Get&amp;lt;U&amp;gt;(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt;&amp;gt; exp)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;(U)(_store[GetKey(exp)] ?? &lt;span style="color: blue"&gt;default&lt;/span&gt;(U));
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Set&amp;lt;U&amp;gt;(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt;&amp;gt; exp, U value)
    {
        _store[GetKey(exp)] = value;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;SetDefault&amp;lt;U&amp;gt;(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt;&amp;gt; exp, U value)
    {
        _store.SetDefault(GetKey(exp), value);
    }   

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;IsSpecified&amp;lt;U&amp;gt;(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt;&amp;gt; exp)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;_store.IsSpecified(GetKey(exp));
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;CopyTo(&lt;span style="color: #2b91af"&gt;AttributeStore&lt;/span&gt;&amp;lt;T&amp;gt; target)
    {
        _store.CopyTo(target._store);
    }

    &lt;span style="color: blue"&gt;private string &lt;/span&gt;GetKey&amp;lt;U&amp;gt;(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt;&amp;gt; exp)
    {
        &lt;span style="color: #2b91af"&gt;PropertyInfo &lt;/span&gt;info = &lt;span style="color: #2b91af"&gt;ReflectionHelper&lt;/span&gt;.GetProperty(exp);
        &lt;span style="color: blue"&gt;return &lt;/span&gt;info.Name;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;As you can see, AttributeStore&amp;lt;T&amp;gt; is a generic wrapper for a non-generic class called AttributeStore. The purpose of AttributeStore&amp;lt;T&amp;gt; is to expose get and set methods that take a lambda, and convert that lambda into a dictionary key, and then delegate to an inner attribute store using that dictionary key. Finally, here is the code for the non-generic attribute store:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AttributeStore
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; _attributes;
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; _defaults;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;AttributeStore()
    {
        _attributes = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;();
        _defaults = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;();
    }

    &lt;span style="color: blue"&gt;public object this&lt;/span&gt;[&lt;span style="color: blue"&gt;string &lt;/span&gt;key]
    {
        &lt;span style="color: blue"&gt;get
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(_attributes.ContainsKey(key))
                &lt;span style="color: blue"&gt;return &lt;/span&gt;_attributes[key];
            
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(_defaults.ContainsKey(key))
                &lt;span style="color: blue"&gt;return &lt;/span&gt;_defaults[key];

            &lt;span style="color: blue"&gt;return null&lt;/span&gt;;
        }
        &lt;span style="color: blue"&gt;set &lt;/span&gt;{ _attributes[key] = &lt;span style="color: blue"&gt;value&lt;/span&gt;; }
    }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;IsSpecified(&lt;span style="color: blue"&gt;string &lt;/span&gt;key)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;_attributes.ContainsKey(key);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;CopyTo(&lt;span style="color: #2b91af"&gt;AttributeStore &lt;/span&gt;store)
    {
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;KeyValuePair&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; pair &lt;span style="color: blue"&gt;in &lt;/span&gt;_attributes)
            store._attributes[pair.Key] = pair.Value;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;SetDefault(&lt;span style="color: blue"&gt;string &lt;/span&gt;key, &lt;span style="color: blue"&gt;object &lt;/span&gt;value)
    {
        _defaults[key] = value;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;AttributeStore is just a wrapper for a couple of dictionaries, one for the values that have been specified, and one for the default values. That’s pretty much all there is to it. &lt;/p&gt;

&lt;p&gt;I see AttributeStore&amp;lt;T&amp;gt; as a superior alternative to the weakly typed bag of attributes approach that Fluent NHibernate currently uses.There are no magic strings, and its all strongly typed. Its more powerful than just using properties with backing fields, and it requires pretty much the same amount of code. Sure, its much slower, but performance is not really a concern for Fluent NHibernate. I can see myself using this pattern on other projects.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-2063340314492527546?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/2063340314492527546/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/02/fluent-nhibernate-semantic-model.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/2063340314492527546?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/2063340314492527546?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/02/fluent-nhibernate-semantic-model.html" title="Fluent NHibernate semantic model: AttributeStore&amp;lt;T&amp;gt;" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;A0YDQno8fyp7ImA9WxVQFU8.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-1664507944367322798</id><published>2009-02-02T09:52:00.000+11:00</published><updated>2009-02-02T09:59:33.477+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-02-02T09:59:33.477+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Git" /><title>I’m starting to Git it</title><content type="html">&lt;p&gt;For the last week I have been experimenting with Git. Git is a relatively new source code management tool that is set apart from the SCM’s you are likely to be familiar with because it is distributed rather than centralised. I’m not going to sit here and harp on about all the reasons why this approach has merit when there are plenty of resources available that will do a much better job:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://au.youtube.com/watch?v=4XpnKHJAok8"&gt;Git’s creator, Linus Torvalds on why Git is better than everything else&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://whygitisbetterthanx.com/"&gt;Why Git is better than X&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Nor am I going to teach you the fundamentals of how git works and how to use it, again for similar reasons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.kernel.org/pub/software/scm/git/docs/user-manual.html"&gt;Git user manual&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://gitready.com/"&gt;Git Ready&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Today I just want to talk about what I had to do to start using Git effectively for my work on &lt;a href="http://code.google.com/p/fluent-nhibernate/"&gt;Fluent NHibernate&lt;/a&gt; (which is hosted in Subversion on Google Code). Basically, I wanted a local repository for Fluent NH. I wanted to be able to commit smaller chunks of work to the local repository and then commit to SVN once I was happy with it. I also wanted to be able to branch, rollback, view history, etc all without touching the SVN repository. Git gave me these capabilities.&lt;/p&gt;  &lt;p&gt;Here are the steps I followed to get up and running with Git and a Google Code hosted project:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Installed &lt;a href="http://code.google.com/p/msysgit/"&gt;msysgit&lt;/a&gt;. I installed &lt;a href="http://msysgit.googlecode.com/files/Git-1.5.5-preview20080413.exe"&gt;version 1.5.5&lt;/a&gt; because I heard that the later versions had problems with git-svn (the tool for bridging Git and Subversion). I have no idea if this is actually the case. When installing, I chose the option that added git to my path environment variable. This allowed me to use Git in the windows command line, but there was a hitch. Every time I ran git from the windows command line, it would close the command line. I followed the fix here &lt;a href="http://osdir.com/ml/version-control.msysgit/2008-04/msg00118.html"&gt;here&lt;/a&gt; to solve it. &lt;/li&gt;    &lt;li&gt;Configure git. I set up a SSH key and my details, as described &lt;a href="http://github.com/guides/using-git-and-github-for-the-windows-for-newbies"&gt;here&lt;/a&gt;. I also set the autocrlf option to false – this seems to minimise problems with line endings. To do so I used the command:       &lt;br /&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;git config –global core.autocrlf false&lt;/font&gt;       &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;Used git-svn to create a local clone. Initially I ran into some difficulty because I pulled the repository down using http – this caused problems later when I tried to commit and could not authenticate properly. Using https when cloning the repository fixed the problem. Another issue to be aware of when using git-svn is that unlike the rest of Git, git-svn is &lt;strong&gt;very&lt;/strong&gt; slow. I had to leave git-svn working away for over 20 minutes when I first pulled down my branch of Fluent NHibernate. Later I learned that you can tell git-svn to clone a revision rather than the entire repository, so I used this functionality when I pulled the second time (using https instead of http). The command I used was:       &lt;br /&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;git svn clone https://fluent-nhibernate.googlecode.com/svn/branches/pb-rewrite --username &amp;quot;paul.batum&amp;quot; –r234&lt;/font&gt;       &lt;br /&gt;      &lt;br /&gt;My Google Code username is “paul.batum”. I was prompted for my password the first time, but then Git seemed to remember it from then on. The –r234 switch specified a particular revision to get. If I was prepared to wait, I would have omitted the flag and pulled the entire history into my local repository, but patience got the better of me. &lt;/li&gt;    &lt;li&gt;Added a .gitignore file to specify which types of files should not be tracked by Git. I grabbed the &lt;a href="http://github.com/machine/machine/blob/b51e9c4c4af4ea75880ef761e90736cc3f691f10/.gitignore"&gt;.gitignore file&lt;/a&gt; from an a .NET project hosted in GitHub called Machine. I then made a few modifications, copied into my new repository and checked it in:       &lt;br /&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;git add .gitignore        &lt;br /&gt;git commit –m “Added ignore file”&lt;/font&gt;       &lt;br /&gt;      &lt;br /&gt;You can view my ignore file &lt;a href="http://code.google.com/p/fluent-nhibernate/source/browse/branches/pb-rewrite/.gitignore?spec=svn235&amp;amp;r=235"&gt;here&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;Worked with the local repository. My git repository was ready to use. I worked on the Fluent NH code for a while, using the git gui (run simply by using the &lt;font face="Courier New"&gt;git gui&lt;/font&gt; command) to make small commits. &lt;/li&gt;    &lt;li&gt;Rebased my local repository against the SVN repository. Before I commit back to the SVN repository, I need to merge any changes that have been made since I cloned the repository. Git offers merge functionality, but it also offers something slightly different called a rebase. In a nutshell, the difference between a merge and a rebase is that a merge will interleave your changes with everyone else’s changes. A rebase will take each of your changes, and apply them all sequentially after everyone else’s changes. You can read a better explanation &lt;a href="http://jbowes.dangerouslyinc.com/2007/01/26/git-rebase-keeping-your-branches-current/"&gt;here&lt;/a&gt;. The rebase command was straightforward:       &lt;br /&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;git svn rebase&lt;/font&gt;       &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;Checked the state of my repository. I wanted to see what my repository looked like after the rebase. A commit viewer called gitk is installed as part of msysgit, to run it with all branches displayed the command is:      &lt;br /&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;gitk –-all        &lt;br /&gt;&amp;#160;&lt;/font&gt; &lt;/li&gt;    &lt;li&gt;Commited my changes to the SVN repository. With the rebase complete, my local commits were ready to be pushed to the main repository on Google Code. To commit my changes back to SVN, I ran the following command:      &lt;br /&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;git svn dcommit –-username paul.batum &lt;/font&gt;      &lt;br /&gt;      &lt;br /&gt;The dcommit command pushes my commits to the SVN repository one at a time. This means that the rich history that was created locally by my small commits is preserved in the SVN history. There are some options for “squashing” all of the local changes so that they are all represented by a single commit, but I am yet to explore those. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;I am still a total Git newbie. But hopefully this guide will save some hair pulling for other windows developers that decide to learn git by using it locally for their SVN hosted projects.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-1664507944367322798?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/1664507944367322798/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/02/im-starting-to-git-it.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/1664507944367322798?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/1664507944367322798?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/02/im-starting-to-git-it.html" title="I’m starting to Git it" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;D04ESHY4cCp7ImA9WxVSF0s.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-5607304750091653875</id><published>2009-01-12T23:55:00.002+11:00</published><updated>2009-01-13T00:11:49.838+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-13T00:11:49.838+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Y Combinator" /><title>Refactoring Towards the Y Combinator: Part 6</title><content type="html">&lt;p&gt;&lt;em&gt;This is a multi-part series. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html"&gt;Part 1&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html"&gt;Part 2&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html"&gt;Part 3&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html"&gt;Part 4&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html"&gt;Part 5&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html"&gt;Part 6&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is the final part of my series on the Y combinator. By the end of part 5, the bulk of the work was done. All I have to do today is generalize it, clean it up and make it look pretty. Here is the code from part 5:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution09 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
        {
            &lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; algorithm = (&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
                {
                    &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
                };
            };

            &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt;&amp;gt; self) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; alg) =&amp;gt;
                {
                    &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
                    {
                        &lt;span style="color: blue"&gt;return &lt;/span&gt;alg(self(self)(alg))(x);
                    };
                };
            };
            &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial)(algorithm);
        }
    }&lt;/pre&gt;

&lt;p&gt;I claimed that the factorial function, as it is defined here, is a version of the Y combinator. Indeed if you take a look at it, you will see that it really doesn’t have anything to do with calculating factorials anymore – that code has long since been moved into the “algorithm” function. But the signature of the function still mentions factorials, specifically the Factorial delegate. To get my definition for the Y combinator into a more usable state, I can replace usages of the Factorial delegate with Func&amp;lt;int,int&amp;gt;. Later on, I’ll be able to define a generic version so it can even be used for functions that take and compute a double, or string, or whatever. However when I make this change, I still need to return a Factorial (because my test harness requires the MakeFactorialFunction method to return a Factorial delegate). To get around this I will use an earlier trick of returning a lambda that can be cast as a Factorial delegate:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;    
/// &lt;/span&gt;&lt;span style="color: green"&gt;Its possible to make a generic version of the Y combinator for application to functions that take 1 argument and return a value of the same type.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;Unfortunately we cannot continue to use the Factorial delegate if we want to make this generic version.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;We rename the functions to better represent their purpose (factorial becomes Y, algorithm becomes factorial).
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;We can't just return Y(Y)(factorial)(x) because that will return a Func&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;int,int&amp;gt; &lt;/span&gt;&lt;span style="color: green"&gt;but this method is supposed to return a Factorial. Although
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;they are basically the same thing, a conversion cannot be made. Therefore I have to return a lambda that calls Y(Y)(factorial)(x).
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution10 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; f) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x*f(x - 1);
            };
        };
        
        &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; Y =
            (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; self) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; alg) =&amp;gt;
                {
                    &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
                    {
                        &lt;span style="color: blue"&gt;return &lt;/span&gt;alg(self(self)(alg))(x);
                    };
                };
            };
        
        &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;Y(Y)(factorial)(x);
        };
    }
}&lt;/pre&gt;

&lt;p&gt;I can now make Y generic by moving it into its own generic class:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Move Y into its own class.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution11 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; f) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
            };
        };

        &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt;
        {                
            &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.Y(&lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.Y)(factorial)(x);
        };
    }

    &lt;span style="color: blue"&gt;private static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;T&amp;gt;
    {
        &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt;&amp;gt;&amp;gt; Y =
            (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt;&amp;gt;&amp;gt; self) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt;&amp;gt; alg) =&amp;gt;
                {
                    &lt;span style="color: blue"&gt;return &lt;/span&gt;(T x) =&amp;gt;
                    {
                        &lt;span style="color: blue"&gt;return &lt;/span&gt;alg(self(self)(alg))(x);
                    };
                };
            };
    }
}&lt;/pre&gt;

&lt;p&gt;There is some ugliness with calling Y on itself now, so I add a “ApplyY” helper to the YCombinator class to make this part easier. I let Resharper help me use a more terse syntax for the lambdas, and this is the result:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;private static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt;&amp;gt;&amp;gt; Y =
        self =&amp;gt; algorithm =&amp;gt; t =&amp;gt; algorithm(self(self)(algorithm))(t);

    &lt;span style="color: blue"&gt;public static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt;&amp;gt; ApplyY = Y(Y);

}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I’ve avoided using the terse lambda syntax up until now because I think it would have made comprehending the individual steps more difficult. I can use ApplyY like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.ApplyY(factorial)(10);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Here is my final implementation for this entire exercise, utilizing the above class:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;This is the final implementation.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;The Y combinator has been moved to a separate file. 
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;The factorial algorithm has been pushed to a static member and condensed.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution12 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; factorial =
                    f =&amp;gt; x =&amp;gt; x &amp;lt; 2 ? 1 : x * f(x - 1);

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; &lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.ApplyY(factorial)(x);
    }

    &lt;span style="color: green"&gt;// Example of using Y without any need for the Factorial delegate:
    &lt;/span&gt;&lt;span style="color: blue"&gt;public int &lt;/span&gt;CalculateFactorialOf10()
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.ApplyY(factorial)(10);            
    }

}&lt;/pre&gt;

&lt;p&gt;Now lets test my implementation of the Y combinator by using it to calculate Fibonacci numbers:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Fibonacci
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; fibonacci =
        f =&amp;gt; x =&amp;gt; x &amp;lt; 3 ? 1 : f(x - 1) + f(x - 2);

    &lt;span style="color: blue"&gt;public static int &lt;/span&gt;Calculate(&lt;span style="color: blue"&gt;int &lt;/span&gt;nthNumber)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;YCombinator&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.ApplyY(fibonacci)(nthNumber);
    }
}&lt;/pre&gt;

&lt;p&gt;Its horribly inefficient, but it works:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #2b91af"&gt;Fibonacci&lt;/span&gt;.Calculate(10));&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&amp;gt;&amp;gt; 55&lt;/p&gt;

&lt;p&gt;So there you have it: the Y combinator implemented in C#, derived via many gradual refactorings. This implementation still has some limitations. For example, it won’t support a recursive algorithm that takes two arguments. You could of course modify the Y combinator class to support this, but because of the strongly typed nature of C#, it seems very difficult to make a definition of Y that could be applied to an algorithm with ANY signature. If you are interested in exploring the code that I provided in this series, you can download it &lt;a href="http://paul.batum.googlepages.com/TheWhyOfY.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I really enjoyed this exercise and I would definitely encourage other programmers that are weak at functional programming to have a go at it. If you really know this stuff and my clumsy explanations made you cringe, please leave a comment! If you were following along with the series and got lost or stuck at some point, again, please comment! Practice makes perfect, but some constructive criticism can really help too. Thanks!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-5607304750091653875?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/5607304750091653875/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/5607304750091653875?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/5607304750091653875?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html" title="Refactoring Towards the Y Combinator: Part 6" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total></entry><entry gd:etag="W/&quot;D08HSX4-eip7ImA9WxVSF0s.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-3011772683183529103</id><published>2009-01-10T21:28:00.001+11:00</published><updated>2009-01-13T00:10:38.052+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-13T00:10:38.052+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Y Combinator" /><title>Refactoring Towards the Y Combinator: Part 5</title><content type="html">&lt;p&gt;&lt;em&gt;This is a multi-part series. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html"&gt;Part 1&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html"&gt;Part 2&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html"&gt;Part 3&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html"&gt;Part 4&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html"&gt;Part 5&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html"&gt;Part 6&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here is the state of affairs at the end of part 4:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial HigherOrderFactorial&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;factorial);

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution07 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{        
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;algorithm = (&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
                {
                    &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
                };
        };

        &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; self) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;algorithm(self(self))(x);
            };
        };

        &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As I mentioned at the end of part 4, the problem with this implementation is that the factorial function creates a closure, capturing the algorithm variable. I fixed a similar problem in step 2 – in this case its fixed by having the factorial function accept ‘algorithm’ as an argument. Unfortunately my first attempt at this will not compile:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;alg, &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; self) =&amp;gt;
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;alg(alg, self(self))(x);
    };
};

&lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(algorithm, factorial);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Its not that simple, because it breaks the signature of the SelfApplicable delegate. So I will have to define a new delegate. To figure out what to call it, lets take a look at its signature:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial SomeDelegate&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;SomeDelegate &lt;/span&gt;self, &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;algorithm);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;So it takes itself, and a HigherOrderFactorial, and its returns a Factorial. Well in that case isn’t it fair to say that it is a “higher order evaluator”? Its also self applying, so lets call it SelfApplyingHigherOrderFactorialEvaluator:&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial SelfApplyingHigherOrderFactorialEvaluator&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;SelfApplyingHigherOrderFactorialEvaluator &lt;/span&gt;self, &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;algorithm);

&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;We can make the algorithm an argument to the factorial function. Unfortunately its not a particularly simple refactoring, because of the
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;self calling nature of the factorial function. We are forced to define a new self applying delegate that accepts the higher order function.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution08 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{        
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;algorithm = (&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
            };
        };

        &lt;span style="color: #2b91af"&gt;SelfApplyingHigherOrderFactorialEvaluator &lt;/span&gt;factorial =
            (&lt;span style="color: #2b91af"&gt;SelfApplyingHigherOrderFactorialEvaluator &lt;/span&gt;self, &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;alg) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {                            
                &lt;span style="color: blue"&gt;return &lt;/span&gt;alg(self(self, alg))(x);
            };
        };

        &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial, algorithm);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Phew! I was excited when this one worked – I could smell blood in the air. The body of that factorial function is starting to look pretty close to the Y combinator. Now I don’t know about you, but that factorial function is looking kind of hungry, so lets give it some &lt;strong&gt;curry!&lt;/strong&gt; By currying it, I will have the opportunity to go back to using the SelfApplicable delegate. This is a tricky step, and I’m not quite sure how to break it down. I can start off by looking at the existing signature:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial SelfApplyingHigherOrderFactorialEvaluator&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;SelfApplyingHigherOrderFactorialEvaluator &lt;/span&gt;self, &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;algorithm);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I called this thing an evaluator, because it takes a HigherOrderFactorial, and it returns a Factorial. Essentially, it evaluates the higher order function which results in a normal order one. I could create a generic delegate to represent an evaluation operation, but to do so I would need to first create a generic delegate for representing a higher order function. Well that should be pretty straightforward:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;T &lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;T&amp;gt;(T function);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The HigherOrderFunction delegate could be used instead of the HigherOrderFactorial delegate. Here is ‘algorithm’ modified to use the HigherOrderFunction delegate:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; algorithm = (&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f) =&amp;gt;
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
    };
};&lt;/pre&gt;

&lt;p&gt;Now that I have a generic delegate for higher order functions, I can also create a generic delegate for their evaluation:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;T &lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;T&amp;gt; higherFunction);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Lets try to get comfortable with this before we move on. Lets say I used it like so:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; evaluator;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Then this is the same as (formatted for clarity):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;br /&gt;    &lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt;, &lt;br /&gt;    &lt;span style="color: #2b91af"&gt;Factorial&lt;br /&gt;    &lt;/span&gt;&amp;gt; evaluator;&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Which is the same as:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt;, 
    &lt;span style="color: #2b91af"&gt;Factorial
    &lt;/span&gt;&amp;gt; evaluator;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I could expand out those Factorial delegates, but I do not think that is necessary. It would just cause an &amp;lt;int&amp;gt; explosion. Now that the HigherOrderEvaluator is defined and explained, I have the necessary tools to discuss how the SelfApplicableHigherOrderFactorialEvaluator is going to be replaced. Again, to make it easier to eyeball the changes, here it is:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial SelfApplyingHigherOrderFactorialEvaluator&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;SelfApplyingHigherOrderFactorialEvaluator &lt;/span&gt;self, &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;algorithm);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This delegate can be retired, because I can use this instead:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt;&amp;gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;BUT! I can only make that replacement if I curry the factorial method, as was discussed before. SelfApplicable only takes one argument, while you can see that the SelfApplyingHigherOrderFactorialEvaluator above takes two. Currying will allow me to reduce it to one argument, so I get to use SelfApplicable. Here is what it looks like:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;T &lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;T&amp;gt;(T function);
&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;T &lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;T&amp;gt; higherFunction);

&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Once again, we curry. This time its the factorial function again.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;Believe it or not, the second function defined here is the Y combinator. Unfortunately, in this form it is specific to the factorial method..
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution09 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; algorithm = (&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
            };
        };


        &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt;&amp;gt; self) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; alg) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
                {
                    &lt;span style="color: blue"&gt;return &lt;/span&gt;alg(self(self)(alg))(x);
                };
            };
        };
        &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial)(algorithm);
    }
}&lt;/pre&gt;

&lt;p&gt;I jumped out of my chair when this worked. I did a lap of my apartment, punching at the air. Yes, I am really that lame. ANYWAY…&lt;/p&gt;

&lt;p&gt;The function that is still called ‘factorial’ is actually a version of the Y combinator specifically typed for being applied to factorials. In the final post for this series I will make it more general, clean it up, demonstrate it being used for Fibonacci and post the full source code.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-3011772683183529103?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/3011772683183529103/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3011772683183529103?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3011772683183529103?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html" title="Refactoring Towards the Y Combinator: Part 5" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;D08FRHk7cCp7ImA9WxVSF0s.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-3283610031878831879</id><published>2009-01-09T20:25:00.001+11:00</published><updated>2009-01-13T00:10:15.708+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-13T00:10:15.708+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Y Combinator" /><title>Refactoring Towards the Y Combinator: Part 4</title><content type="html">&lt;p&gt;&lt;em&gt;This is a multi-part series. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html"&gt;Part 1&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html"&gt;Part 2&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html"&gt;Part 3&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html"&gt;Part 4&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html"&gt;Part 5&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html"&gt;Part 6&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I finished the previous post with the following code:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;T &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;T&amp;gt; self);
&lt;span style="color: gray"&gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution05 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; self) =&amp;gt; 
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * self(self)(x - 1);
            };
        };
        
        &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial);
    }
}&lt;/pre&gt;

&lt;p&gt;The next step, as I mentioned previously, is to attempt to remove the self(self) business from the factorial algorithm. The self calling aspect is really a technical concern, while the algorithm is more like business logic – it makes sense to want to separate the two. To do this, I’m going to apply a variation on the &lt;em&gt;Extract Method&lt;/em&gt; refactoring. I’ll define the factorial algorithm using a new RecursiveFactorial delegate, and let the existing factorial function call it:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate int &lt;/span&gt;&lt;span style="color: #2b91af"&gt;RecursiveFactorial&lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x, &lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f);

&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Lets try to seperate the algorithm definition for factorial from the infrastructure that is applying the recursion.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;I extract the bit that calculates the factorial as a seperate function, and call it &amp;quot;algorithm&amp;quot;. The existing factorial function now calls
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;the algorithm, applying itself to itself as it does.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution06 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{        
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;RecursiveFactorial &lt;/span&gt;algorithm = (&lt;span style="color: blue"&gt;int &lt;/span&gt;x, &lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
        };

        &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; self) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;algorithm(x, self(self));
            };
        };

        &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial);
    }
}&lt;/pre&gt;

&lt;p&gt;If you compare the two versions, you should be able to see that I have replaced the “&lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2…” line of code with a call to “algorithm”, but I left the self(self) part where it was. The two concerns are seperated. But the RecursiveFactorial delegate should look familiar to you. Its sort of like my old friend, the SelfCallingFactorial, except it doesn’t seem to call itself, it just calls the factorial function you pass it. The funny thing is that it IS calling itself. Suprised? Perhaps I can help..&lt;/p&gt;

&lt;p&gt;At the last line of the function, I return the result of evaluating the factorial function, passing in itself as an argument. I will try to expand this out by performing substitutions:&lt;/p&gt;

&lt;pre class="code"&gt;           
            &lt;span style="color: green"&gt;// Redefine factorial to use more compact syntax.
            &lt;/span&gt;factorial = self =&amp;gt; x =&amp;gt; algorithm(self(self))(x);

            &lt;span style="color: green"&gt;// This is the line of code to expand.
            &lt;/span&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial);

            &lt;span style="color: green"&gt;// Substitute the body of factorial in, replacing the self parameter with factorial
            &lt;/span&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; algorithm(factorial(factorial))(x);            

            &lt;span style="color: green"&gt;// If you look inside, you can see that the line we just substituted has another factorial(factorial). Lets substitute that one too.
            // I will have to rename the integer parameter when I do so, to avoid a clash. I'll call it x1.
            &lt;/span&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; algorithm(x1 =&amp;gt; algorithm(factorial(factorial))(x1))(x);

            &lt;span style="color: green"&gt;// Whoops! That pesky factorial(factorial) has appeared again! Substitute, substitute!
            &lt;/span&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; algorithm(x1 =&amp;gt; algorithm(x2 =&amp;gt; algorithm(factorial(factorial))(x2))(x1))(x);

            &lt;span style="color: green"&gt;// Is there no end in sight?
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;font face="Courier New" color="#008000"&gt;&lt;/font&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;No, there is not. Doing it this way, it looks like I am stuck in some sort of infinite loop, but this is because I’ve expanded the code incorrectly. The first few substitutions are fine – its when I attempted to expand this line that I made a mistake:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; algorithm(x1 =&amp;gt; algorithm(factorial(factorial))(x1))(x);&lt;/pre&gt;

&lt;p&gt;The point to notice about this line is that the factorial(factorial) is inside the body of a lambda, being passed as an argument. It will only be evaluated if x is &amp;gt;= 2. If I called the function this line returns with the argument of 1, then that factorial(factorial) part will never be called. I would like to show you the correct expansion of this line but I struggled to get an expansion that compiled properly. Perhaps it would suffice to say that the next step would be to expand the algorithm call, rather than the factorial call.&amp;#160; Hopefully this expansion discussion has illuminated the self calling nature of the solution, but also explained how an infinite loop is avoided.&lt;/p&gt;

&lt;p&gt;Getting back on track, the reason why I pointed out that RecursiveFactorial bares some resemblance to SelfCallingFactorial is because I intend to repeat an operation I performed in part 3; I want to apply the &lt;em&gt;currying&lt;/em&gt; technique to ‘algorithm’. I will define yet another delegate to represent the curried version of algorithm and call it HigherOrderFactorial. Why “higher order”? Because the curried version accepts a Factorial function and returns a Factorial function –&amp;#160; it operates on functions rather than operating on integers:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial HigherOrderFactorial&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;factorial);

&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Apply the currying techinque again, this time to algorithm, we arrive at a higher order function. 
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;Now algorithm takes a factorial function, and returns a factorial function.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution07 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{        
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;HigherOrderFactorial &lt;/span&gt;algorithm = (&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
                {
                    &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * f(x - 1);
                };
        };

        &lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; factorial = (&lt;span style="color: #2b91af"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;&amp;gt; self) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;algorithm(self(self))(x);
            };
        };

        &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(factorial);
    }
}&lt;/pre&gt;

&lt;p&gt;If you take a look at the changes made to ‘algorithm’ in this step, you will see that they are really quite similar to the changes made in Part 3, where the factorial function was curried. Of course, when I modified the signature of ‘algorithm’, I also had to modify the call to it:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh5.ggpht.com/_AP_-f1YlmB4/SWXG4P1rqTI/AAAAAAAAAM4/QpU8I5yrivE/s1600-h/image%5B3%5D.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="95" alt="image" src="http://lh3.ggpht.com/_AP_-f1YlmB4/SWXG4quHGGI/AAAAAAAAAM8/YD_eDB_SX6c/image_thumb%5B1%5D.png?imgmax=800" width="555" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;This should be really familiar. Go back and reread &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html"&gt;part 3&lt;/a&gt; if you are not comfortable with this transformation.&lt;/p&gt;

&lt;p&gt;The next step is to address the fact that ‘algorithm’ is a captured variable inside the factorial closure. It would be better to pass in the algorithm as an argument to the factorial function. I will tackle this in the next post.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-3283610031878831879?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/3283610031878831879/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3283610031878831879?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/3283610031878831879?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html" title="Refactoring Towards the Y Combinator: Part 4" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;D0AHRXs4eCp7ImA9WxVSF0s.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-5345521056476512923</id><published>2009-01-08T12:48:00.003+11:00</published><updated>2009-01-13T00:08:54.530+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-13T00:08:54.530+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Y Combinator" /><title>Refactoring Towards the Y Combinator: Part 3</title><content type="html">&lt;p&gt;&lt;em&gt;This is a multi-part series. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html"&gt;Part 1&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html"&gt;Part 2&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html"&gt;Part 3&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html"&gt;Part 4&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html"&gt;Part 5&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html"&gt;Part 6&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I would like to begin this post with an explanation of a technique called &lt;em&gt;currying&lt;/em&gt;. Currying is a mechanism that allows a function that takes multiple arguments to be converted to a function that takes only a single argument.  I will be using it today, but it would probably be best to look at currying in a simpler context before it is applied to the factorial scenario. I’ve constructed a simple example of currying based on adding two numbers. The inline comments should explain what is going on. Brief disclaimer: currying is another one of those theoretical computer sciency concepts that I’ve understood &lt;strong&gt;just enough&lt;/strong&gt; to get by. If my explanation sucks, please leave a comment so I can fix it.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// The addition function takes two integers, and returns the result of adding them together.
&lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; add = (x, y) =&amp;gt; x + y;
&lt;span style="color:blue;"&gt;int &lt;/span&gt;five = add(2, 3);

&lt;span style="color:green;"&gt;// If you often needed to add two to something, you could explicitly define a function that does so.
// It would only need to take one argument.
&lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; addTwo = x =&amp;gt; add(x, 2);
five = addTwo(3);

&lt;span style="color:green;"&gt;// Perhaps you also need to add four often. Again, you could make a function for it, and it would only take one argument.
&lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; addFour = x =&amp;gt; add(x, 4);
five = addFour(1);

&lt;span style="color:green;"&gt;// Now there is some duplication between addTwo and addFour. What if we could make a function, that makes adders?
&lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; makeAdder = (&lt;span style="color:blue;"&gt;int &lt;/span&gt;valueToAdd) =&amp;gt;
{
   &lt;span style="color:blue;"&gt;return &lt;/span&gt;x =&amp;gt; add(x, valueToAdd);
};

&lt;span style="color:green;"&gt;// Excellent, now we can reconstruct addTwo and addFour using makeAdder
&lt;/span&gt;addTwo = makeAdder(2);
addFour = makeAdder(4);

&lt;span style="color:green;"&gt;// And use them like before
&lt;/span&gt;five = addTwo(3);
five = addFour(1);
          
&lt;span style="color:green;"&gt;// Lets compute 6 + 4, by making an adder that adds 6 to numbers, an then passing 4 to it.
&lt;/span&gt;&lt;span style="color:blue;"&gt;int &lt;/span&gt;ten = makeAdder(6)(4);

&lt;span style="color:green;"&gt;// Well it appears we can now add any two numbers together by using makeAdder. But makeAdder only takes one argument, not two.
// makeAdder is the result of applying currying to the add method.&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Here is another way of stating it: if you have a function that takes arguments A and B and returns C, you can create a function that takes argument A, and returns a &lt;strong&gt;function&lt;/strong&gt; that takes argument B and returns C. By calling this function with A, you then call the resulting function with B, and you get C. That is currying. Lets get back to factorials – here is the code the last post finished up with:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public delegate int &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SelfCallingFactorial&lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;x, &lt;span style="color: rgb(43, 145, 175);"&gt;SelfCallingFactorial &lt;/span&gt;self);

&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Creating the factorial method inside the returned lambda resolves the garbage collection problem.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;This solution does not involve a closure, so its pretty good. But...
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Solution03 &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;ISolution
&lt;/span&gt;{
   &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
   {
       &lt;span style="color:blue;"&gt;return &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;x1) =&amp;gt;
       {
           &lt;span style="color: rgb(43, 145, 175);"&gt;SelfCallingFactorial &lt;/span&gt;factorial = (&lt;span style="color:blue;"&gt;int &lt;/span&gt;x, &lt;span style="color: rgb(43, 145, 175);"&gt;SelfCallingFactorial &lt;/span&gt;self) =&amp;gt;
           {
               &lt;span style="color:blue;"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * self(x - 1, self);
           };

           &lt;span style="color:blue;"&gt;return &lt;/span&gt;factorial(x1, factorial);
       };
   }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Its sort of annoying how I have to do all my work inside a lambda. I’ve had to do this for the last few solutions, ever since I introduced the idea of using self calling function. It would be great if the SelfCallingFactorial could return a Factorial (the delegate). That way I could just return the result directly, and I wouldn’t have to deal with the fact that I have two integer parameters running about (x and x1). This change can be achieved by using currying. Its somewhat tricky so I will do it in two steps. The first step is to perform the currying operation, making as few changes as possible, the second step will clean up, simplify and generalize. Here is the first part:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public delegate &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Factorial SelfCallingFactorial2&lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;SelfCallingFactorial2 &lt;/span&gt;self);

&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Apply a technique called currying. Now the self calling factorial function returns a factorial delegate.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Solution04 &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;ISolution
&lt;/span&gt;{
   &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
   {
       &lt;span style="color:blue;"&gt;return &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;x1) =&amp;gt;
       {
           &lt;span style="color: rgb(43, 145, 175);"&gt;SelfCallingFactorial2 &lt;/span&gt;factorial = (&lt;span style="color: rgb(43, 145, 175);"&gt;SelfCallingFactorial2 &lt;/span&gt;self) =&amp;gt;
           {
               &lt;span style="color:blue;"&gt;return &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;x) =&amp;gt;
               {
                   &lt;span style="color:blue;"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x*self(self)(x-1);
               };
           };

           &lt;span style="color:blue;"&gt;return &lt;/span&gt;factorial(factorial)(x1);
       };
   }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I had to modify the SelfCallingFactorial delegate. It no longer accepts an integer, instead it returns a Func&amp;lt;int,int&amp;gt; which I replaced with the Factorial delegate. You will notice I stuck a 2 on the end of the name, this is just to avoid clashes with previous delegate. This will get cleaned up in a second. Once the delegate was modified, I had to change the factorial function, and then its invocation. A side-by-side comparison might help:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_AP_-f1YlmB4/SWVbVmciOyI/AAAAAAAAAMw/kAw6iUQKQfk/s1600-h/image%5B3%5D.png"&gt;&lt;img title="image" style="border: 0px none ; display: inline;" alt="image" src="http://lh6.ggpht.com/_AP_-f1YlmB4/SWVbW_bdLKI/AAAAAAAAAM0/mDwlWnIUquU/image_thumb%5B1%5D.png?imgmax=800" border="0" width="755" height="201" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Do you see how the sections in the boxes follow the same pattern, where instead of there being two arguments, there is just one argument, and then the result is invoked with the second argument?&lt;/p&gt;

&lt;p&gt;Step two of this change is to take advantage of what I gained in step one. Now that the self calling factorial function returns a Factorial delegate, I don’t need to wrap the entire thing in a lambda – I can just return the result directly. I can also change the SelfCallingFactorial2 delegate to be generic. Ideally I could use it for other recursive algorithms such as Fibonacci. While I’m in cleanup mode, I want to rename the delegate to “SelfApplicable”. By doing this, I’ve changed the terminology somewhat – I’m using “applicable” instead of “calling”. I’ve done this because the delegate doesn’t actually “know” what the function is doing with the self argument. Its &lt;strong&gt;probably&lt;/strong&gt; calling it, but perhaps its just inspecting its members? What the delegate can say is that the function is definitely &lt;strong&gt;applying&lt;/strong&gt; itself to itself, because it takes itself as an argument, after all. This change also gets me closer to the code I’m aiming for in Mads’ post. So here is the result of applying these changes:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public delegate &lt;/span&gt;T &lt;span style="color: rgb(43, 145, 175);"&gt;SelfApplicable&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;SelfApplicable&lt;/span&gt;&amp;lt;T&amp;gt; self);

&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;We can generalize the previous delegate to work with any function, and create SelfApplicable&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;T&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;I wish I could constrain T to be a delegate type but unfortunately it is not supported.
&lt;/span&gt;&lt;span style="color:gray;"&gt;///
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Because we removed the integer argument from the function, we no longer have to nest the entire body in
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;a lambda as we did in the previous step.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Solution05 &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;ISolution
&lt;/span&gt;{
   &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
   {
       &lt;span style="color: rgb(43, 145, 175);"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Factorial&lt;/span&gt;&amp;gt; factorial = (&lt;span style="color: rgb(43, 145, 175);"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Factorial&lt;/span&gt;&amp;gt; self) =&amp;gt;
       {
           &lt;span style="color:blue;"&gt;return &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;x) =&amp;gt;
           {
               &lt;span style="color:blue;"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * self(self)(x - 1);
           };
       };
      
       &lt;span style="color:blue;"&gt;return &lt;/span&gt;factorial(factorial);
   }
}&lt;/pre&gt;

&lt;p&gt;Pretty neat huh! My only complaint with this code is that my factorial algorithm has this yucky self(self) business. Ideally I could refactor this out, so that the factorial algorithm is as readable as possible, and the tricky self calling nonsense is somewhere else. I shall pursue this in the next post.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-5345521056476512923?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/5345521056476512923/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/5345521056476512923?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/5345521056476512923?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html" title="Refactoring Towards the Y Combinator: Part 3" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;D0ABQn86fCp7ImA9WxVSF0s.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-6549933381832752944</id><published>2009-01-06T11:42:00.003+11:00</published><updated>2009-01-13T00:09:13.114+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-13T00:09:13.114+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Y Combinator" /><title>Refactoring Towards the Y Combinator: Part 2</title><content type="html">&lt;p&gt;&lt;em&gt;This is a multi-part series. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html"&gt;Part 1&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html"&gt;Part 2&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html"&gt;Part 3&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html"&gt;Part 4&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html"&gt;Part 5&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html"&gt;Part 6&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Lets get started with discovering the Y combinator. To start off, I came up with the most straightforward recursive implementation of the factorial function I could think of, restricting myself to anonymous methods (or more specifically, lambdas):&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate int &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial&lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x);

&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;This is the cheating way. Define a variable and use a closure on that variable.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;Its cheating because it only works in an impure language.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution01 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {            
        &lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;factorial = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
        factorial = (&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * factorial(x - 1);
        };
        
        &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial;
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I define a delegate for the Factorial function – it takes an int, returns an int. I could have used Func&amp;lt;int,int&amp;gt; but believe me, as this gets more complicated, you’ll be glad I introduced the delegate. I also define a MakeFactorialFunction() method, which is intended to be used as so:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;s1 = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution01&lt;/span&gt;();
&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;f = s1.MakeFactorialFunction();
&lt;span style="color: blue"&gt;int &lt;/span&gt;factorialOf10 = f(10);&lt;/pre&gt;

&lt;p&gt;You can mostly ignore the Solution01 and ISolution stuff, they are just artefacts from the testing harness I set up. Lets focus on the code that matters:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;factorial = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
factorial = (&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * factorial(x - 1);
};

&lt;span style="color: blue"&gt;return &lt;/span&gt;factorial;&lt;/pre&gt;

&lt;p&gt;In this code, I call factorial recursively by utilizing a &lt;em&gt;closure&lt;/em&gt;. The body of the lambda expression refers to a variable that lies &lt;strong&gt;outside&lt;/strong&gt; the scope of the lambda; that variable is ‘factorial’. You might have noticed, my code comment above states that I consider this implementation to be “cheating”. This is because I reassign the value of factorial. First it is null, then it is a lambda expression. Perhaps you are wondering why I bother reassign it? Why not just do it like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;factorial = (&lt;span style="color: blue"&gt;int &lt;/span&gt;x) =&amp;gt;
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * factorial(x - 1);
};&lt;/pre&gt;

&lt;p&gt;I am afraid this won’t work, the compiler identifies this as an error, “use of unassigned local variable ‘factorial’”. This is why I use the extra step of declaring factorial to be null. Now I said before that reassigning the factorial variable is cheating. Why? The Y combinator is much more relevant to the functional programming paradigm than it is to the imperative paradigm – functional programming has a concept called “purity”, which means no side effects, and no variables (no variables with varying values, that is) . For the purposes of this exercise, it will be helpful to limit myself to pure operations. The reassignment of the factorial variable is a impure operation. So how to get rid of it?&lt;/p&gt;

&lt;p&gt;My next attempt:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public delegate int &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SelfCallingFactorial&lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x, &lt;span style="color: #2b91af"&gt;SelfCallingFactorial &lt;/span&gt;self);

&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;We can remove the impurity by having the factorial function accept a reference to itself, so it can call itself.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;We can't just return this implementation because it doesn't match the Factorial signature, so we have to return
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;a lambda that calls it. Unfortunately, doing so will create a closure and as a result, as long as a reference
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;to the result of MakeFactorialFunction method is held, the Solution2 instance will not be garbage collected.
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution02 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: #2b91af"&gt;SelfCallingFactorial &lt;/span&gt;factorial = (&lt;span style="color: blue"&gt;int &lt;/span&gt;x, &lt;span style="color: #2b91af"&gt;SelfCallingFactorial &lt;/span&gt;self) =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * self(x - 1, self);
        };

        &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt;
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(x, factorial);
        };
    }
}&lt;/pre&gt;

&lt;p&gt;Okay, so what has happened? Rather than having the factorial function call itself by utilizing the variable, we could &lt;em&gt;pass a reference to the factorial function as an argument to itself&lt;/em&gt;. I modify the Factorial delegate to accept an instance of itself, and call it a SelfCallingFactorial instead. You can see that delegate definition at the top. I then define ‘factorial’ similarly as before, but this time I have a ‘self’ parameter which I can invoke as the recursive step. When it is invoked, I have to pass &lt;strong&gt;two arguments: &lt;/strong&gt;the value I want to calculate the factorial of, and another self reference. Try to think of the ‘self’ parameter as a manually implemented equivalent of the ‘this’ keyword in normal C#, but for functions. The ‘this’ keyword allows code inside an object to obtain a reference to that object, similarly, my ‘self’ parameter allows code inside a function to call that function!&lt;/p&gt;

&lt;p&gt;The result of this trick is that I have successfully removed the impurity - there is no reassignment in this solution. However we are not finished yet: unfortunately, I cannot simply return ‘factorial’ after it has been defined, because it is a SelfCallingFactorial, and the MakeFactorialFunction method is supposed to return a Factorial. Instead I have to return a lambda that will execute my SelfCallingFactorial. This creates another closure, again, on the ‘factorial’ variable. As mentioned in the code comment, the instance of Solution02 used to create the factorial function will stay in scope as long as the factorial function stays in scope, because the returned factorial function holds a reference to the ‘factorial’ local variable defined in the MakeFactorialFunction() method. Fortunately, this is easy to fix:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Creating the factorial method inside the returned lambda resolves the garbage collection problem. 
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;This solution does not involve a closure, so its pretty good. But...
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Solution03 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISolution
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Factorial &lt;/span&gt;MakeFactorialFunction()
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;x1) =&amp;gt;
        {
            &lt;span style="color: #2b91af"&gt;SelfCallingFactorial &lt;/span&gt;factorial = (&lt;span style="color: blue"&gt;int &lt;/span&gt;x, &lt;span style="color: #2b91af"&gt;SelfCallingFactorial &lt;/span&gt;self) =&amp;gt;
            {
                &lt;span style="color: blue"&gt;return &lt;/span&gt;x &amp;lt; 2 ? 1 : x * self(x - 1, self);
            };

            &lt;span style="color: blue"&gt;return &lt;/span&gt;factorial(x1, factorial);
        };
    }
}&lt;/pre&gt;

&lt;p&gt;Solution03 is just a very minor revision on Solution02. All I had to do was move the code that defines the SelfCallingFactorial inside the returned lambda expression (if you look at the code above, you will see that it was previously outside). Now when a Solution03 instance is used to construct a FactorialFunction, that instance will be free to be garbage collected while the result, the factorial function, can continued to be used. Now please don’t get me wrong, I know that this garbage collection ‘issue’ is quite irrelevant – I am actually just using it as an excuse to get the code closer to my satisfaction. I am not exactly sure &lt;strong&gt;why&lt;/strong&gt; I want it this way – it just seems neater.&lt;/p&gt;

&lt;p&gt;So, where to go from Solution03? It seems pretty good, and we are still nowhere near the Y combinator. In the next instalment, I will start making the code a little more general, with the eventual goal that the same technique might be applied to other recursive algorithms (such as Fibonacci).&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-6549933381832752944?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/6549933381832752944/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6549933381832752944?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6549933381832752944?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html" title="Refactoring Towards the Y Combinator: Part 2" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total></entry><entry gd:etag="W/&quot;D0ADQXcyfip7ImA9WxVSF0s.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-6084376160604916164</id><published>2009-01-04T12:05:00.002+11:00</published><updated>2009-01-13T00:09:30.996+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-13T00:09:30.996+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Y Combinator" /><title>Refactoring Towards the Y Combinator: Part 1</title><content type="html">&lt;p&gt;&lt;em&gt;This is a multi-part series. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html"&gt;Part 1&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-2.html"&gt;Part 2&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-3.html"&gt;Part 3&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-4.html"&gt;Part 4&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-5.html"&gt;Part 5&lt;/a&gt;. &lt;a href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-6.html"&gt;Part 6&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Sometimes I wish that I had studied computer science rather than software engineering at university. The software engineering degree was much more practical, and as a result there is a bunch of interesting computer science theory out there that I am yet to be exposed to. In an effort to make some tiny progress on this front, this Christmas break I decided to spend a few days exposing myself to a lovely little thing called the Y combinator.&lt;/p&gt;

&lt;p&gt;What is the Y combinator exactly? Basically, its a mechanism that can be used to call functions recursively, even if your programming language does not support recursion, as long as it &lt;strong&gt;does&lt;/strong&gt; have support for first class functions (e.g. you can pass one function to another as an argument). It is extremely unlikely that you will find a use for it in your day to day work as a programmer, but I found learning about the Y combinator to be a worthwhile exercise nonetheless simply because it made my head hurt in a &lt;strong&gt;good way&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;I found three particularly useful resources for learning about the Y combinator. These were:&lt;/p&gt;

&lt;ul&gt;
 &lt;li&gt;&lt;a href="http://blogs.msdn.com/madst/archive/2007/05/11/recursive-lambda-expressions.aspx"&gt;Recursive Lambda Expressions&lt;/a&gt; by Mads Torgersen &lt;/li&gt;

 &lt;li&gt;&lt;a href="http://mvanier.livejournal.com/2700.html"&gt;The Y Combinator&lt;/a&gt; by Mike Vanier &lt;/li&gt;

 &lt;li&gt;&lt;a href="http://www.dreamsongs.com/Files/WhyOfY.pdf"&gt;The Why of Y&lt;/a&gt; [PDF] by Richard Gabriel &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Just reading through them, they all managed to lose me at some point. The Y combinator is really a functional programming concept, so programmers such as myself that were crippled at a young age by being first exposed to an imperative language like Basic will really struggle with it. It was clear that the only way I was really going to understand it was roll up my sleeves and write some code.&lt;/p&gt;

&lt;p&gt;Mads’ post uses C#, and it had enough code to give me a clear goal. I would start with the most basic implementation of a recursive method I could, and try to slowly refactor it towards the final Mads code. This turned out to work very well, but I probably would not have succeeded without the help of the other resources, especially The Why of Y. Both Mike and Richard use Scheme (a dialect of Lisp), but fortunately I have watched enough &lt;a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/"&gt;SICP lectures&lt;/a&gt; to be able to follow it at a basic level. In the Why of Y, Richard provides an example derivation of Y, and I was able to successfully translate each of his steps to the appropriate C#. I promise you, there will be no Lisp code in any of the posts in this series.&lt;/p&gt;

&lt;p&gt;So what does the Y combinator look like? Well here is the definition I ended up with:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SelfApplicable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt;&amp;gt;&amp;gt; Y =
   self =&amp;gt; algorithm =&amp;gt; t =&amp;gt; algorithm(self(self)(algorithm))(t);&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;HigherOrderEvaluator&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt;&amp;gt; ApplyY = Y(Y);&lt;/pre&gt;

&lt;p&gt;Here is my definition for the factorial function:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;HigherOrderFunction&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; factorial =
               f =&amp;gt; x =&amp;gt; x &amp;lt; 2 ? 1 : x * f(x - 1);&lt;/pre&gt;

&lt;p&gt;And here is the usage:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public int &lt;/span&gt;CalculateFactorialOf10()
{
   &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;YCombinator&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.ApplyY(factorial)(10);
}&lt;/pre&gt;

&lt;p&gt;What’s the phrase you’re looking for? How about: “&lt;strong&gt;My eyes! The goggles do nothing!&lt;/strong&gt;”&lt;/p&gt;

&lt;p&gt;Even now when I look at it, I struggle to make sense of it. This is the compressed version, but in my opinion even a far more verbose version is still difficult to comprehend. I understand this code by understanding the steps I followed to arrive at it, and hopefully by the end of this series of posts, so will you.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-6084376160604916164?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/6084376160604916164/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6084376160604916164?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/6084376160604916164?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/01/refactoring-towards-y-combinator-part-1.html" title="Refactoring Towards the Y Combinator: Part 1" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;CUEEQXc4fCp7ImA9WxVSEE8.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-1473056875185413479</id><published>2009-01-04T10:00:00.001+11:00</published><updated>2009-01-04T10:00:00.934+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-04T10:00:00.934+11:00</app:edited><title>One Year</title><content type="html">&lt;p&gt;Its been one year since I started this blog, so I figured a reflective post might be appropriate. &lt;/p&gt;  &lt;p&gt;What went right in 2008:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;I made a dramatic change to my free time habits. I did significantly more reading and programming, and spent much less time playing videogames. &lt;/li&gt;    &lt;li&gt;I read a &lt;a href="http://www.paulbatum.com/2008/03/pragmatic-programmer.html"&gt;bunch&lt;/a&gt; of &lt;a href="http://www.paulbatum.com/2008/04/domain-driven-design-book.html"&gt;software&lt;/a&gt; &lt;a href="http://www.paulbatum.com/2008/05/mythical-man-month.html"&gt;related&lt;/a&gt;&amp;#160;&lt;a href="http://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Technology/dp/0201485672/"&gt;books&lt;/a&gt; &lt;a href="http://www.paulbatum.com/2008/10/c-in-depth.html"&gt;cover-to-cover&lt;/a&gt;. Probably more than in all previous years combined. &lt;/li&gt;    &lt;li&gt;I involved myself in an &lt;a href="http://www.paulbatum.com/2008/08/my-first-open-source-project.html"&gt;open source project&lt;/a&gt;. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;What went wrong:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;I started many things, finished few. I played with lots of stuff but didn’t deliver a whole lot. &lt;/li&gt;    &lt;li&gt;I didn’t learn javascript or ruby. At least, not to the point where I can write idiomatic code in either language. &lt;/li&gt;    &lt;li&gt;I failed to deliver a worthwhile MVC based web application. &lt;/li&gt;    &lt;li&gt;I made very little progress in the area of algorithms and data structures. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Rereading my posts from a year ago, it is quite evident that my year did not proceed quite as I intended. However, I am not disappointed - I learned quite a bit about my own capabilities and study habits. My career goal changed – while Google is very alluring, I recognise that Microsoft would probably be an awesome place for me to work and a better fit. I have concluded that my focus on the Microsoft stack is not a bad thing. From my perspective, there are lots of exciting things in the works for the Microsoft stack:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Microsoft will be, for the first time ever, providing and fully supporting a proper functional programming language: &lt;a href="http://msdn.microsoft.com/en-us/fsharp/default.aspx"&gt;F#&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;The introduction of the &lt;a href="http://www.codeplex.com/dlr"&gt;DLR&lt;/a&gt; promises to foster a healthy ecosystem of dynamic programming languages, with IronPython and IronRuby at the forefront. &lt;/li&gt;    &lt;li&gt;Spec# has been transformed into a &lt;a href="http://research.microsoft.com/en-us/projects/contracts/"&gt;code contract library with compiler support&lt;/a&gt; and will be part of the .NET 4.0 release. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.microsoft.com/azure/windowsazure.mspx"&gt;Windows Azure&lt;/a&gt;, Microsoft’s cloud computing platform, could make a significant impact on the .NET development ecosystem over the next few years. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-au/oslo/default.aspx"&gt;Oslo&lt;/a&gt;, simply because it could help push domain specific languages into the mainstream. I am sceptical about much of what Oslo promises, but I think better tooling and raising awareness of what DSLs can offer is a good thing. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In the next few years I will be able to explore functional languages, dynamically typed languages, code contracts, cloud computing and domain specific languages all within the .NET platform. There is an immense amount for me to learn (this list, obviously, is nowhere near enumerating all of it), so why not go with the path of least resistance and learn what I can within the MS stack?&lt;/p&gt;  &lt;p&gt;I hope to do a better job this year of actually finishing things. My study habits are still a long way off being optimal.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-1473056875185413479?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/1473056875185413479/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2009/01/one-year.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/1473056875185413479?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/1473056875185413479?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2009/01/one-year.html" title="One Year" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;DkAMSH89eyp7ImA9WxRbGE0.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-2458542730904877548</id><published>2008-12-09T17:39:00.000+11:00</published><updated>2008-12-09T17:39:49.163+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-12-09T17:39:49.163+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Fluent NHibernate" /><title>A Fluent NHibernate rewrite</title><content type="html">&lt;p&gt;A little less than 6 months ago I &lt;a href="http://www.paulbatum.com/2008/08/my-first-open-source-project.html"&gt;joined&lt;/a&gt; the &lt;a href="http://code.google.com/p/fluent-nhibernate/"&gt;Fluent NHibernate&lt;/a&gt; open source project. More recently I’ve struggled with fielding feature requests and partial patches, and I believe that the source of my difficulty has been the structure of the Fluent NHibernate codebase. In my opinion, the fundamental problem with the code is a lack of separation of concerns. Lets take a look at some excerpts from the ClassMap class:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public virtual &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IdentityPart &lt;/span&gt;Id(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt; expression, &lt;span style="color: blue"&gt;string &lt;/span&gt;column)
{
    &lt;span style="color: #2b91af"&gt;PropertyInfo &lt;/span&gt;property = &lt;span style="color: #2b91af"&gt;ReflectionHelper&lt;/span&gt;.GetProperty(expression);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;id = column == &lt;span style="color: blue"&gt;null &lt;/span&gt;? &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IdentityPart&lt;/span&gt;(property) : &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IdentityPart&lt;/span&gt;(property, column);
    AddPart(id);
    &lt;span style="color: blue"&gt;return &lt;/span&gt;id;
}&lt;/pre&gt;This Id method is part of the fluent interface. You can see it takes an expression and does some reflection to convert that expression into a format that can be used to configure NHibernate.&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;XmlDocument &lt;/span&gt;CreateMapping(&lt;span style="color: #2b91af"&gt;IMappingVisitor &lt;/span&gt;visitor)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;String&lt;/span&gt;.IsNullOrEmpty(TableName))
        TableName = visitor.Conventions.GetTableName.Invoke(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T));

    visitor.CurrentType = &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T);
    &lt;span style="color: #2b91af"&gt;XmlDocument &lt;/span&gt;document = getBaseDocument();
    setHeaderValues(visitor, document);

    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;import &lt;span style="color: blue"&gt;in &lt;/span&gt;imports)
    {
        import.Write(document.DocumentElement, visitor);
    }

    &lt;span style="color: #2b91af"&gt;XmlElement &lt;/span&gt;classElement = createClassValues(document, document.DocumentElement);
    writeTheParts(classElement, visitor);

    &lt;span style="color: blue"&gt;return &lt;/span&gt;document;
}&lt;/pre&gt;&lt;p&gt;This CreateMapping method generates the eventual output that will be fed to NHibernate: an XmlDocument.&lt;/p&gt;&lt;p&gt;The fact that these two methods exist in the same class is a prime example of why I have found the code base increasingly difficult to work with. There is no seperation between the function of &lt;strong&gt;specifying&lt;/strong&gt; the mapping (by calling into the fluent interface) and &lt;strong&gt;generating&lt;/strong&gt; the mapping (writing an xml document). It becomes difficult to reason about the capability of the library as the public interface consists of a big pile of lambda goo. Thinking more ambitiously, if you wanted to develop an alternative fluent api while continuing to utilize all the existing infrastructure provided by Fluent NHibernate, you would find it very difficult indeed.&lt;/p&gt;&lt;p&gt;So, what to do? Hell, if your a programmer you shouldn’t have to ask that question! The same thing we always want to do when the old code base starts to feel clunky. Throw it all out and start from scratch! Ok, rarely is this actually a good idea but that is the nice thing about doing open source on your own time – you can do whatever the hell you want.&lt;/p&gt;&lt;p&gt;Well what should the code base actually look like? Chad Myers &lt;a href="http://groups.google.com/group/fluent-nhibernate/msg/57f151b4c047eab5?hl=en"&gt;had the answer&lt;/a&gt;, so I rolled up my sleeves and went to work. That was a couple of weeks ago. Today I hit a milestone - I was able to successfully configure NHibernate for a simple 3 entity scenario, using an API that looks just like the existing Fluent NHibernate API but actually utilizes a model that constructs an object graph of Hbm* instances (these are classes provided by NHibernate that are generated from the mapping schema) and then serializes that graph to xml. Hitting this milestone meant that it was time to share my work, so I committed my version as a &lt;a href="http://fluent-nhibernate.googlecode.com/svn/branches/pb-rewrite/"&gt;branch&lt;/a&gt;. I included a decent chunk of notes in the commit message and don’t intend to repeat them all here, so I recommend you &lt;a href="http://code.google.com/p/fluent-nhibernate/source/detail?r=143"&gt;review the log&lt;/a&gt; if you would like to know more.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;So what does this rewrite actually look like?&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;First of all, here is the tiny demonstration domain that I have been using so far:&lt;/p&gt;&lt;p&gt;&amp;#160;&lt;a href="http://lh3.ggpht.com/_AP_-f1YlmB4/ST4PmNRkm0I/AAAAAAAAALo/RRW4rGWaO2Y/s1600-h/image%5B8%5D.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="357" alt="image" src="http://lh6.ggpht.com/_AP_-f1YlmB4/ST4PnzMAV_I/AAAAAAAAALs/c0zlcsDYg1k/image_thumb%5B2%5D.png?imgmax=800" width="727" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;p&gt;Now here is the fluent mapping that I managed to get working today:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;private class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArtistMap &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ClassMap&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Artist&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;ArtistMap()
    {
        Id(x =&amp;gt; x.ID);
        Map(x =&amp;gt; x.Name)
            .WithLengthOf(50)
            .CanNotBeNull();
        HasMany&amp;lt;&lt;span style="color: #2b91af"&gt;Album&lt;/span&gt;&amp;gt;(x =&amp;gt; x.Albums)
            .AsSet()
            .IsInverse();
    }
}

&lt;span style="color: blue"&gt;private class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AlbumMap &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ClassMap&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Album&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;AlbumMap()
    {
        Id(x =&amp;gt; x.ID);
        Map(x =&amp;gt; x.Title)
            .WithLengthOf(50)
            .CanNotBeNull();
        References(x =&amp;gt; x.Artist);
        HasMany&amp;lt;&lt;span style="color: #2b91af"&gt;Track&lt;/span&gt;&amp;gt;(x =&amp;gt; x.Tracks)
            .AsSet()
            .IsInverse();
    }
}

&lt;span style="color: blue"&gt;private class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TrackMap &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ClassMap&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Track&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;TrackMap()
    {
        Id(x =&amp;gt; x.ID);
        Map(x =&amp;gt; x.Name)
            .WithLengthOf(50)
            .CanNotBeNull();
        Map(x =&amp;gt; x.TrackNumber);
        References(x =&amp;gt; x.Album)
            .CanNotBeNull();
    }
}&lt;/pre&gt;&lt;p&gt;Look familiar? It should if you are a Fluent NHibernate user or developer! To demonstrate the flexibility of the rewrite, I implemented a very small subset of the existing fluent interface. That implementation was put in a completely separate assembly, to demonstrate that the core of Fluent NHibernate is not tied to any specific fluent api. If you wanted to, you could map a class unfluently, using the core model like so: (this example only maps Album)&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;root = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HibernateMapping&lt;/span&gt;();

&lt;span style="color: blue"&gt;var &lt;/span&gt;classMapping = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ClassMapping
   &lt;/span&gt;{
       Name = &lt;span style="color: blue"&gt;typeof &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Album&lt;/span&gt;).AssemblyQualifiedName,
       Id = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IdMapping&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;ID&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IdColumnMapping&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;ID&amp;quot;&lt;/span&gt;), &lt;span style="color: #2b91af"&gt;IdGeneratorMapping&lt;/span&gt;.NativeGenerator)
   };
root.AddClass(classMapping);

&lt;span style="color: blue"&gt;var &lt;/span&gt;titleMapping = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PropertyMapping&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Title&amp;quot;&lt;/span&gt;) {Length = 50, AllowNull = &lt;span style="color: blue"&gt;false&lt;/span&gt;};
classMapping.AddProperty(titleMapping);

&lt;span style="color: blue"&gt;var &lt;/span&gt;artistMapping = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ManyToOneMapping&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Artist&amp;quot;&lt;/span&gt;);
classMapping.AddReference(artistMapping);

&lt;span style="color: blue"&gt;var &lt;/span&gt;trackMapping = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SetMapping
   &lt;/span&gt;{
       Name = &lt;span style="color: #a31515"&gt;&amp;quot;Tracks&amp;quot;&lt;/span&gt;,
       Key = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;KeyMapping&lt;/span&gt;(),
       Contents = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OneToManyMapping&lt;/span&gt;(&lt;span style="color: blue"&gt;typeof &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Track&lt;/span&gt;).AssemblyQualifiedName)
   };
classMapping.AddCollection(trackMapping);&lt;/pre&gt;&lt;p&gt;You could then serialize the underlying Hbm graph and this is the result:&lt;/p&gt;&lt;p&gt;&lt;a href="http://lh4.ggpht.com/_AP_-f1YlmB4/ST4PpizfZUI/AAAAAAAAALw/tECnetWNFtQ/s1600-h/image%5B12%5D.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="368" alt="image" src="http://lh6.ggpht.com/_AP_-f1YlmB4/ST4Pr7MYNbI/AAAAAAAAAL0/jBciLxT0Qh4/image_thumb%5B4%5D.png?imgmax=800" width="568" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;p&gt;But of course, doing it that way sucks. This project is called &lt;strong&gt;Fluent&lt;/strong&gt; NHibernate after all!&amp;#160; You don’t even have any strong typing on the properties! I can’t see anyone using the core model directly. Its designed to be a base for fluent api’s to build on.&lt;/p&gt;&lt;p&gt;The core model is still in a rough state. At the moment it has very little functionality other than to wrap the Hbm* classes. However I expect this will change. One of the many issues that need addressing is that of support for conventions – I expect the conventions implementation will require the model to be richer, to accept Type and PropertyInfo instances rather than awful strings. But don’t worry! It won’t get too rich – you won’t see any Expression&amp;lt;Func&amp;lt;T, Object&amp;gt;&amp;gt; hanging off the model – that stuff belongs in the fluent interface.&lt;/p&gt;&lt;p&gt;I am really quite excited about how the seperation between the mapping model and the fluent interface could be leveraged. The DDD fanboi in me would love to see a fluent interface that allows you to describe your aggregate structure in addition to mapping to NHibernate.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-2458542730904877548?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/2458542730904877548/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2008/12/fluent-nhibernate-rewrite.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/2458542730904877548?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/2458542730904877548?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2008/12/fluent-nhibernate-rewrite.html" title="A Fluent NHibernate rewrite" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total></entry><entry gd:etag="W/&quot;A0MNQXo6eip7ImA9WxRWFkk.&quot;"><id>tag:blogger.com,1999:blog-882821950355432699.post-4651732284954721789</id><published>2008-11-03T04:55:00.000+11:00</published><updated>2008-11-03T05:11:30.412+11:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-11-03T05:11:30.412+11:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>No visitors!</title><content type="html">&lt;p&gt;I am sure that most programmers managed to learn some specific design patterns before they even knew what design patterns were. This is certainly true for myself – and while I cannot say what my first design pattern was, I can tell you about the first one I remember learning: the &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;Visitor&lt;/a&gt; pattern. I was midway through a university class on object oriented programming and in my spare time I was writing a turn based puzzle game in C# that involved daggers and goblins and dragons and doors and keys and whatnot. Now to make the thing work, I was doing something that felt very wrong. I was writing lots of switch statements that described the interactions between the different objects. I experimented, looking for better solutions using overloading and overriding, but none of it seemed to work. I asked my lecturer for help, and of course this is where I learned about visitor. Initially I was elated, but in time my opinion changed: visitor is this ugly bloated thing, designed to get around the lack of &lt;a href="http://en.wikipedia.org/wiki/Double_dispatch"&gt;double dispatch&lt;/a&gt; support in most object oriented languages. Its a hack, a workaround. As with arguably all design patterns, its a trick to deal with limitations in the language.&lt;/p&gt; &lt;p&gt;So today I was watching this &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/"&gt;video&lt;/a&gt; that goes into more detail on the new C#4 features and something was said about runtime overload resolution that flicked a switch in my brain and suddenly I realised a fact that I am sure was mindblowingly obvious to people much smarter than I: the C#4 dynamic keyword supports double dispatch. If you are prepared to take the performance hit and just want to get something up and running, you can forget the visitor pattern. Lets look at an example based on the sort of thing I was trying to do years ago with my little game:&lt;/p&gt; &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entity
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Name { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;GetGreeting(&lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;e)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;...&amp;quot;&lt;/span&gt;;
    }
}
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Foo &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;Entity
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;GetGreeting(&lt;span style="color: #2b91af"&gt;Foo &lt;/span&gt;f)
    {
        &lt;span style="color: blue"&gt;return string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;Hi there {0}! Beware, there may be evil Bars nearby!&amp;quot;&lt;/span&gt;, f.Name);
    }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;GetGreeting(&lt;span style="color: #2b91af"&gt;Bar &lt;/span&gt;b)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;Curse you! I hate all Bars!&amp;quot;&lt;/span&gt;;
    }
}
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Bar &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;Entity
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;GetGreeting(&lt;span style="color: #2b91af"&gt;Bar &lt;/span&gt;b)
    {
        &lt;span style="color: blue"&gt;return string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;Greetings {0}! Have you seen any evil Foos lately?&amp;quot;&lt;/span&gt;, b.Name);
    }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;GetGreeting(&lt;span style="color: #2b91af"&gt;Foo &lt;/span&gt;f)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;The Foos are a scourge on this planet! Take this!&amp;quot;&lt;/span&gt;;
    }
}
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StaticIntroducer
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Introduce(&lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;e1, &lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;e2)
    {
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} is introduced to {1} by the StaticIntroducer...&amp;quot;&lt;/span&gt;, e1.Name, e2.Name);
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} says: \&amp;quot;{1}\&amp;quot;&amp;quot;&lt;/span&gt;, e1.Name, e1.GetGreeting(e2));
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} says: \&amp;quot;{1}\&amp;quot;&amp;quot;&lt;/span&gt;, e2.Name, e2.GetGreeting(e1));
    }
}
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;f1 = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Foo &lt;/span&gt;{ Name = &lt;span style="color: #a31515"&gt;&amp;quot;BobFoo&amp;quot; &lt;/span&gt;};
        &lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;f2 = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Foo &lt;/span&gt;{ Name = &lt;span style="color: #a31515"&gt;&amp;quot;JohnFoo&amp;quot; &lt;/span&gt;};
        &lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;b1 = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Bar &lt;/span&gt;{ Name = &lt;span style="color: #a31515"&gt;&amp;quot;JerryBar&amp;quot; &lt;/span&gt;};
        &lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;b2 = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Bar &lt;/span&gt;{ Name = &lt;span style="color: #a31515"&gt;&amp;quot;SamBar&amp;quot; &lt;/span&gt;};

        &lt;span style="color: blue"&gt;var &lt;/span&gt;introducer = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StaticIntroducer&lt;/span&gt;();
        introducer.Introduce(f1, f2);
        introducer.Introduce(f1, b1);
        introducer.Introduce(b1, b2);

        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.ReadLine();
    }
}&lt;/pre&gt;&lt;p&gt;It outputs the following:&lt;/p&gt;&lt;blockquote&gt;
    BobFoo is introduced to JohnFoo by the StaticIntroducer... 
    BobFoo says: &amp;quot;...&amp;quot; 
    JohnFoo says: &amp;quot;...&amp;quot; 
    BobFoo is introduced to JerryBar by the StaticIntroducer... 
    BobFoo says: &amp;quot;...&amp;quot; 
    JerryBar says: &amp;quot;...&amp;quot; 
    JerryBar is introduced to SamBar by the StaticIntroducer... 
    JerryBar says: &amp;quot;...&amp;quot; 
    SamBar says: &amp;quot;...&amp;quot;&lt;/blockquote&gt;&lt;p&gt;Clearly, it does not work as intended. The code I’ve written makes some sort of sense, but its not correct. If you look at the Introduce method, you can see that it takes two entities. As a result, the call to GetGreeting will be resolved at compile time to Entity.GetGreeting(Entity e) and no polymorphism will occur. You cannot fix the problem by simply making the methods virtual and overrides, as the overriden versions take different arguments. Redeclaring the GetGreeting methods using the new operator also does not help. If you are facing this problem with C# 3 or earlier, its time to apply the visitor pattern. I won’t do that here, there are plenty of examples of Visitor on the web.&lt;/p&gt;&lt;p&gt;But if you are using C#4, its time for dynamic to come to the rescue. Here is a slightly different implementation of an Introducer:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DynamicIntroducer
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Introduce(dynamic e1, dynamic e2)
    {
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} is introduced to {1} by the DynamicIntroducer...&amp;quot;&lt;/span&gt;, e1.Name, e2.Name);
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} says: {1}&amp;quot;&lt;/span&gt;, e1.Name, e1.GetGreeting(e2));
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} says: {1}&amp;quot;&lt;/span&gt;, e2.Name, e2.GetGreeting(e1));
    }
}&lt;/pre&gt;&lt;p&gt;The ONLY thing I have changed is the signature. The parameters are now typed as dynamic rather than Entity. I plug this introducer in and this is the output:&lt;/p&gt;&lt;blockquote&gt;
    BobFoo is introduced to JohnFoo by the DynamicIntroducer... 
    BobFoo says: Hi there JohnFoo! Beware, there may be evil Bars nearby! 
    JohnFoo says: Hi there BobFoo! Beware, there may be evil Bars nearby! 
    BobFoo is introduced to JerryBar by the DynamicIntroducer... 
    BobFoo says: Curse you! I hate all Bars! 
    JerryBar says: The Foos are a scourge on this planet! Take this! 
    JerryBar is introduced to SamBar by the DynamicIntroducer... 
    JerryBar says: Greetings SamBar! Have you seen any evil Foos lately? 
    SamBar says: Greetings JerryBar! Have you seen any evil Foos lately?
&lt;/blockquote&gt;&lt;p&gt;It works! How? Well, once you are using the dynamic type, overload resolution occurs at runtime rather than compile time, and is done using the runtime types of the arguments rather than the compile time types. My nice, succinct code that describes the different interactions now works just how I intended. But at what cost? Putting the possible performance problems aside, we have made the code more fragile. If someone passes a non-Entity to the Introduce method, we’ll get a runtime error! Well this is actually a trivial fix that only occurred to me while writing this post:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public void &lt;/span&gt;Introduce(&lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;e1, &lt;span style="color: #2b91af"&gt;Entity &lt;/span&gt;e2)
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} is introduced to {1} by the DynamicIntroducer...&amp;quot;&lt;/span&gt;, e1.Name, e2.Name);
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} says: {1}&amp;quot;&lt;/span&gt;, e1.Name, ((dynamic)e1).GetGreeting(e2));
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0} says: {1}&amp;quot;&lt;/span&gt;, e2.Name, ((dynamic)e2).GetGreeting(e1));
}&lt;/pre&gt;&lt;p&gt;The only method call that actually needs to be dynamic is GetGreeting, so we can change the method signature back to as it was before and just introduce a cast to dynamic for the GetGreeting invocation. Much better. There is one more thing I would like to try to do: hide the need for GetGreeting to be invoked dynamically from the caller. The crude way is to use a static method, but I’m not a fan of that. Tomorrow I will see if there is an elegant way to approach it.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/882821950355432699-4651732284954721789?l=www.paulbatum.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.paulbatum.com/feeds/4651732284954721789/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.paulbatum.com/2008/11/no-visitors.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/4651732284954721789?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/882821950355432699/posts/default/4651732284954721789?v=2" /><link rel="alternate" type="text/html" href="http://www.paulbatum.com/2008/11/no-visitors.html" title="No visitors!" /><author><name>Paul</name><uri>http://www.blogger.com/profile/18224234643439645641</uri><email>paul.batum@gmail.com</email><gd:extendedProperty name="OpenSocialUserId" value="15622167435446684159" /></author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total></entry></feed>
