<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="2.0">
  <channel>
    <title>Removing All Doubt</title>
    <link>http://www.removingalldoubt.com</link>
    <description />
    <copyright>Copyright 2005 Chuck Jazdzewski</copyright>
    <lastBuildDate>Fri, 06 Mar 2009 19:22:46 GMT</lastBuildDate>
    <generator>ChrisAn's BlogX</generator>
    <managingEditor>chuckjaz@hotmail.com</managingEditor>
    <webMaster>chuckjaz@hotmail.com</webMaster>
    <item>
      <title>Simulating INumeric with policies</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/66b75287-2a94-415c-88b1-9778adffb406</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/66b75287-2a94-415c-88b1-9778adffb406</link>
      <pubDate>Fri, 06 Mar 2009 19:22:46 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;After reading &lt;a href="http://blogs.msdn.com/lucabol"&gt;Luca Bolognese&amp;#39;s&lt;/a&gt; 
blog post regarding using
&lt;a href="http://blogs.msdn.com/lucabol/archive/2009/02/05/simulating-inumeric-with-dynamic-in-c-4-0.aspx"&gt;
C# 4.0&amp;#39;s dynamic keyword to simulate INumeric&lt;/a&gt; I immediately thought that must be a way to express 
this with generics instead. Generics, however, do not allow you to abstract over operators (which is what
is is needed to really do &lt;code&gt;INumeric&lt;/code&gt;) but you can simulate it using adapters as described in
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8"&gt;
this post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Say I want to write a general average routine that is generic over what type I am using to store the data.
That is, I want one routine that works equally for &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt; as well as &lt;code&gt;&lt;strong&gt;decimal&lt;/strong&gt;&lt;/code&gt;.
What I want to be able to write is something like,&lt;/p&gt;
&lt;pre class="code"&gt;
        &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; T Average(&lt;strong&gt;params&lt;/strong&gt; T[] values) {
            T total = 0;

            &lt;strong&gt;foreach&lt;/strong&gt; (&lt;strong&gt;var&lt;/strong&gt; v &lt;strong&gt;in&lt;/strong&gt; values) 
                total = total + v;

            &lt;strong&gt;return&lt;/strong&gt; total / values.Length;
        }
&lt;/pre&gt;
&lt;p&gt;where the &lt;code&gt;T&lt;/code&gt; is any type that supports adding and dividing. I can't get this code to
compile exactly but we can get surprisingly close! My final version looks like,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;class&lt;/strong&gt; Math&amp;lt;T, A&amp;gt; : PolicyUser&amp;lt;T, A&amp;gt; &lt;strong&gt;where&lt;/strong&gt; A : &lt;strong&gt;struct&lt;/strong&gt;, IOperatorPolicy&amp;lt;T&amp;gt; {
        &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; T Average(&lt;strong&gt;params&lt;/strong&gt; T[] values) {
            &lt;strong&gt;var&lt;/strong&gt; total = L(0);

            &lt;strong&gt;foreach&lt;/strong&gt; (&lt;strong&gt;var&lt;/strong&gt; v &lt;strong&gt;in&lt;/strong&gt; values) 
                total = total + v;

            &lt;strong&gt;return&lt;/strong&gt; total / values.Length;
        }
    }
&lt;/pre&gt;
&lt;p&gt;which is much closer to the original than I thought originally could get!&lt;/p&gt;
&lt;p&gt;I started by cloning the operator policy and added a &lt;code&gt;FromInt()&lt;/code&gt; I will explain below,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;interface&lt;/strong&gt; IOperatorPolicy&amp;lt;T&amp;gt; {
        T Add(T a, T b);
        T Subtract(T a, T b);
        T Multiply(T a, T b);
        T Divide(T a, T b);
        T FromInt(&lt;strong&gt;int&lt;/strong&gt; value);
    }
&lt;/pre&gt;
&lt;p&gt;Then I cloned the &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt; policy struct and then added a &lt;code&gt;&lt;strong&gt;decimal&lt;/strong&gt;&lt;/code&gt; mainly by cut/paste/search/replace&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;struct&lt;/strong&gt; DoubleOperatorPolicy : IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt; {
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Add(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a + b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Subtract(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a - b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Multiply(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a * b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Divide(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a / b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.FromInt(&lt;strong&gt;int&lt;/strong&gt; value) { &lt;strong&gt;return&lt;/strong&gt; value; }
    }

    &lt;strong&gt;struct&lt;/strong&gt; DecimalOperatorPolicy : IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt; {
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Add(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a + b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Subtract(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a - b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Multiply(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a * b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Divide(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a / b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.FromInt(int value) { &lt;strong&gt;return&lt;/strong&gt; value; }
    }
&lt;/pre&gt;
&lt;p&gt;The cleaver bit is to define a base type that contains a &lt;code&gt;struct&lt;/code&gt; that defines the operators
as overloads. The overloads use a policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; to implement that overloaded operators. This &lt;code&gt;
&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;
also defines implicit conversion operators to hide some (but not all) of the messiness introduced by using this
wrapper type. The &lt;code&gt;PolicyUser&lt;/code&gt; class looks like,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;class&lt;/strong&gt; PolicyUser&amp;lt;T, A&amp;gt; &lt;strong&gt;where&lt;/strong&gt; A: &lt;strong&gt;struct&lt;/strong&gt;, IOperatorPolicy&amp;lt;T&amp;gt; {
        &lt;strong&gt;static&lt;/strong&gt; A Policy = &lt;strong&gt;new&lt;/strong&gt; A();
        
        &lt;strong&gt;protected&lt;/strong&gt; &lt;strong&gt;struct&lt;/strong&gt; Value {
            &lt;strong&gt;public&lt;/strong&gt; T V;

            &lt;strong&gt;public&lt;/strong&gt; Value(T v) { V = v; }

            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; +(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Add(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; -(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Subtract(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; *(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Multiply(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; /(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Divide(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; &lt;strong&gt;implicit&lt;/strong&gt; &lt;strong&gt;operator&lt;/strong&gt; Value(T v) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(v); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; &lt;strong&gt;implicit&lt;/strong&gt; &lt;strong&gt;operator&lt;/strong&gt; Value(&lt;strong&gt;int&lt;/strong&gt; v) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.FromInt(v)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; &lt;strong&gt;implicit&lt;/strong&gt; &lt;strong&gt;operator&lt;/strong&gt; T(Value v) { &lt;strong&gt;return&lt;/strong&gt; v.V; }
        }

        &lt;strong&gt;protected&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value L(&lt;strong&gt;int&lt;/strong&gt; value) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.FromInt(value)); }
    }
&lt;/pre&gt;
&lt;p&gt;What the &lt;code&gt;Value&lt;/code&gt; struct does is allows you to use the type &lt;code&gt;Value&lt;/code&gt; in place of the type &lt;code&gt;T&lt;/code&gt; whenever you want to 
use operators. When operators are used you only need to ensure one sub-expression is promoted to &lt;code&gt;Value&lt;/code&gt; and the implict operator will
take care of the rest.&lt;/p&gt;
&lt;p&gt;One remaining oddness is using literals. Implicit operators have there limits which makes using literal a bit strange. This was also odd in the 
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8"&gt;Policy&lt;/a&gt; post as well and I used the same trick to make it a little less cumbersome. I introduced
a static method &lt;code&gt;L()&lt;/code&gt; that takes an integer and converts it to &lt;code&gt;Value&lt;/code&gt; allowing you to use integer literals by calling &lt;code&gt;FromInt()&lt;/code&gt; I introduced earlier. You can 
extend to this to allow other types by repeating the pattern for, say &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;, allowing you to use &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt; literals as well. I didn't 
because I didn't need it for my example (but probably will if I try to implement something more complicated.
&lt;/p&gt;
&lt;p&gt;To bind the actual data type to provide the data type and the policy. To make this simpler I created two create implementations of &lt;code&gt;Math&lt;/code&gt;.&lt;/p&gt;
&lt;pre class="code"&gt;
  &lt;strong&gt;class&lt;/strong&gt; DoubleMath : Math&amp;lt;&lt;strong&gt;double&lt;/strong&gt;, DoubleOperatorPolicy&amp;gt; { }
  &lt;strong&gt;class&lt;/strong&gt; DecimalMath : Math&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;, DecimalOperatorPolicy&amp;gt; { }
&lt;/pre&gt;
&lt;p&gt;Calling the average method looks like,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;var&lt;/strong&gt; resultDouble = DoubleMath.Average(1, 2, 3, 4, 5);
    &lt;strong&gt;var&lt;/strong&gt; resultDecimal = DecimalMath.Average(1, 2, 3, 4, 5);
&lt;/pre&gt;
&lt;p&gt;It should be straight forward to see how this could be adapted to a &lt;code&gt;Financial&lt;/code&gt; class, as Luca was trying to build, and how the routines could
be made independent of the data type used in the calculations.&lt;/p&gt;
&lt;p&gt;There you have it. Policies can be used to simulate &lt;code&gt;INumeric&lt;/code&gt; without having to resort to using &lt;code&gt;&lt;strong&gt;dynamic&lt;/strong&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Edit: Mar 9, 2009: Fixed HTML formatting error
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/66b75287-2a94-415c-88b1-9778adffb406</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Zero the value is not</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/1d2c1827-9b4d-493e-88ba-10ab27c0dae6</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/1d2c1827-9b4d-493e-88ba-10ab27c0dae6</link>
      <pubDate>Sun, 31 Aug 2008 18:41:05 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;One of my pet-peeves is code written like this,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;if&lt;/strong&gt; (0 != value) { ... }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;This reads backwards to me. I hear echoes of 
&lt;a href="http://en.wikipedia.org/wiki/Frank_Oz"&gt;Frank Oz&lt;/a&gt; in my head, &amp;quot;if zero 
the value is not&amp;quot;. As cute as this dialect is coming from a pointy-eared muppet, 
it still takes a bit to translate back into the more common English phrasing, 
&amp;quot;if the value is not zero&amp;quot;. It seems programmers who insist on writing in this style 
have forgotten that their source should be readable as well as executable. Don&amp;#39;t 
force your readers to have to do grammar gymnastics as well as having to 
decipher your algorithmic gynmastics.&lt;/p&gt;
&lt;p&gt;Once upon a time, this was considered good style in order to avoid accidentally 
writing something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;if&lt;/strong&gt; (value = 0) { ... }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;In C#, this is illegal. In most (all?) modern C and C++ compilers, this will 
generate a warning. (You do compile with warnings reported as errors right?) 
There ceases to be a good reason to write test expressions backwards. Let&amp;#39;s let 
this style rest in peace.&lt;/p&gt;
&lt;p&gt;Even if you think the above form has some redeeming value, let&amp;#39;s all agree 
that any programmer that voluntarily writes something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;if&lt;/strong&gt; (&lt;strong&gt;false&lt;/strong&gt; == value) { ... }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;should have an electric shock sent directly through their keyboard.&lt;/p&gt;
&lt;/body&gt;</description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>One of my pet-peeves is code written like this,</p>
        <blockquote>
          <pre class="code">
            <strong>if</strong> (0 != value) { ... }</pre>
        </blockquote>
        <p>This reads backwards to me. I hear echoes of 
<a href="http://en.wikipedia.org/wiki/Frank_Oz">Frank Oz</a> in my head, "if zero 
the value is not". As cute as this dialect is coming from a pointy-eared muppet, 
it still takes a bit to translate back into the more common English phrasing, 
"if the value is not zero". It seems programmers who insist on writing in this style 
have forgotten that their source should be readable as well as executable. Don't 
force your readers to have to do grammar gymnastics as well as having to 
decipher your algorithmic gynmastics.</p>
        <p>Once upon a time, this was considered good style in order to avoid accidentally 
writing something like,</p>
        <blockquote>
          <pre class="code">
            <strong>if</strong> (value = 0) { ... }</pre>
        </blockquote>
        <p>In C#, this is illegal. In most (all?) modern C and C++ compilers, this will 
generate a warning. (You do compile with warnings reported as errors right?) 
There ceases to be a good reason to write test expressions backwards. Let's let 
this style rest in peace.</p>
        <p>Even if you think the above form has some redeeming value, let's all agree 
that any programmer that voluntarily writes something like,</p>
        <blockquote>
          <pre class="code">
            <strong>if</strong> (<strong>false</strong> == value) { ... }</pre>
        </blockquote>
        <p>should have an electric shock sent directly through their keyboard.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/1d2c1827-9b4d-493e-88ba-10ab27c0dae6</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>BeginInvoke's last parameter: What's in a name?</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/b30e6145-bbfa-4697-992c-61d88f23bf14</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/b30e6145-bbfa-4697-992c-61d88f23bf14</link>
      <pubDate>Mon, 16 Jun 2008 13:21:57 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I have been playing around with asynchronous programming lately and it 
bothers me that the last parameter to the &lt;em&gt;begin invoke&lt;/em&gt; pattern doesn&amp;#39;t 
have a name that everyone agrees on. The &lt;em&gt;begin invoke&lt;/em&gt; pattern is the 
asynchronous calling pattern were the &lt;code&gt;BeginXxxx()&lt;/code&gt;, such as &lt;code&gt;
Stream.BeginRead()&lt;/code&gt;, takes a set of parameters, a callback method, and 
some, well, thing, at the end that is carried along with the asynchronous 
operation that eventually finds it way into the &lt;code&gt;IAsyncResult&lt;/code&gt;. The 
problem is what do we call that thing? In an informal survey of the methods in 
the BCL that implement this pattern I have found a wide variation. Here is a 
partial list in somewhat order of popularity,&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;object&lt;/li&gt;
	&lt;li&gt;stateObject&lt;/li&gt;
	&lt;li&gt;state&lt;/li&gt;
	&lt;li&gt;asyncState&lt;/li&gt;
	&lt;li&gt;extraData&lt;/li&gt;
	&lt;li&gt;data&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There seems to be little agreement about what to call it. We could pick the 
most prevalent but the name &lt;code&gt;
object&lt;/code&gt; occurs the most often because every 
delegate gets a &lt;code&gt;BeginInvoke()&lt;/code&gt; method created for it and in this 
automatically generated code the parameter is called &lt;code&gt;object&lt;/code&gt;. We can&amp;#39;t standardize on &lt;code&gt;object&lt;/code&gt; because it is a reserved word in several languages so either it would be impossible to 
specify or awkward (i.e. &lt;code&gt;@object&lt;/code&gt; in C#). What I would like is a 
name that we can all use and we can all agree on.&lt;/p&gt;
&lt;p&gt;To name the thing, we first must understand why it it is there at all. It 
exists to hold some state on behalf of the caller. Having the state object makes 
programming against the &lt;em&gt;begin invoke&lt;/em&gt; pattern easier in languages that 
do not have anonymous methods that capture local variables. Consider the 
following program (which intentionally ignores errors because it is only an 
example),&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;
&lt;b&gt;const&lt;/b&gt; &lt;b&gt;string&lt;/b&gt; uriFormat = 
    "http://messenger.services.live.com/users/{0}@apps.messenger.live.com/presence";
&lt;b&gt;const&lt;/b&gt; &lt;b&gt;string&lt;/b&gt; responsePattern = 
    @"""statusText""\s*:\s*""(?&amp;lt;status&amp;gt;\w+).*""displayName""\s*:\s*""(?&amp;lt;name&amp;gt;\w+)""";

&lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Main(&lt;b&gt;string&lt;/b&gt;[] args) {
    &lt;b&gt;var&lt;/b&gt; uri = &lt;b&gt;string&lt;/b&gt;.Format(uriFormat, args[0]);
    &lt;b&gt;var&lt;/b&gt; request = WebRequest.Create(uri);
    &lt;b&gt;var&lt;/b&gt; result = request.BeginGetResponse(PresenceCallback, request);

    // Other interesting work....

    result.AsyncWaitHandle.WaitOne();
}

&lt;b&gt;private&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PresenceCallback(IAsyncResult result) {
    &lt;b&gt;var&lt;/b&gt; request = result.AsyncState &lt;b&gt;as&lt;/b&gt; WebRequest;
    &lt;b&gt;var&lt;/b&gt; response = request.EndGetResponse(result);
    &lt;b&gt;var&lt;/b&gt; s = &lt;b&gt;new&lt;/b&gt; StreamReader(response.GetResponseStream()).ReadToEnd();
    &lt;b&gt;var&lt;/b&gt; search = &lt;b&gt;new&lt;/b&gt; Regex(responsePattern);
    &lt;b&gt;var&lt;/b&gt; match = search.Match(s);    
    &lt;b&gt;if&lt;/b&gt; (match.Success)
        Console.WriteLine("{0} is {1}", 
           match.Groups["name"].Captures[0].Value, 
           match.Groups["status"].Captures[0].Value);
    &lt;b&gt;else&lt;/b&gt;
        Console.WriteLine("Unexpected response");
}
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will get the online status of a Windows Live Messanger account given the 
live ID account number. For example, passing 1afa695addc07e5 as an argument to 
the above will tell whether or not I am online. In this case I am using last 
parameter of the &lt;code&gt;BeginGetResponse()&lt;/code&gt; method to pass the request 
itself. This then is cast back to &lt;code&gt;WebRequest&lt;/code&gt; in the &lt;code&gt;
PresenceCallback()&lt;/code&gt; method so I can call &lt;code&gt;EndGetResponse()&lt;/code&gt; to 
retrieve the actual response. As far at the &lt;code&gt;BeginGetResponse()&lt;/code&gt; call 
is concerned, this value is opaque. It ignores it completely and just supplies 
it blindly in the &lt;code&gt;IAsyncResult&lt;/code&gt;. It makes no assumptions about the 
data at all, it is just something the caller just wants carried around. If I was using 
anonymous delegates in C# this would look a lot better as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Main(&lt;b&gt;string&lt;/b&gt;[] args) {
    &lt;b&gt;var&lt;/b&gt; uri = &lt;b&gt;string&lt;/b&gt;.Format(uriFormat, args[0]);
    &lt;b&gt;var&lt;/b&gt; request = WebRequest.Create(uri);
    request.BeginGetResponse(result =&amp;gt; {
        &lt;b&gt;var&lt;/b&gt; response = request.EndGetResponse(result);
        &lt;b&gt;var&lt;/b&gt; s = &lt;b&gt;new&lt;/b&gt; StreamReader(response.GetResponseStream()).ReadToEnd();
        &lt;b&gt;var&lt;/b&gt; search = &lt;b&gt;new&lt;/b&gt; Regex(responsePattern);
        &lt;b&gt;var&lt;/b&gt; match = search.Match(s);    
        &lt;b&gt;if&lt;/b&gt; (match.Success)
            Console.WriteLine("{0} is {1}", 
               match.Groups["name"].Captures[0].Value, 
               match.Groups["status"].Captures[0].Value);
        &lt;b&gt;else&lt;/b&gt;
            Console.WriteLine("Unexpected response");
        }   
    }, &lt;b&gt;null&lt;/b&gt;);

    // Other interesting work....

    result.AsyncWaitHandle.WaitOne();
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Here the request local variable &lt;code&gt;request&lt;/code&gt; is captured 
automatically by the C# compiler and placed into a compiler generated class as a 
field. The compiler generated class also contains the code I supplied in the 
lambda as an instance method. When I refer to response in the lambda the 
reference is automatically translated into a field lookup in the generated 
class. Since &lt;code&gt;request&lt;/code&gt; is already accessible in the lambda I don&amp;#39;t 
need the last parameter to carry anything useful so I pass &lt;code&gt;&lt;strong&gt;null&lt;/strong&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Anonymous methods makes using callbacks much easier but since not all 
languages support anonymous methods or lambdas the BCL standardized on a method 
pattern for &lt;em&gt;begin invoke&lt;/em&gt; that can easily be used by those languages. If the calling pattern did not have a caller state 
object then the work performed automatically by the C# compiler would have to be 
repeated manually by the programmer in these, then, second class languages. The 
.NET team did not want such languages to be second class citizen (especially since neither C# nor VB.NET supported anonymous methods initially) 
so they required the presence of the caller state object parameter.&lt;/p&gt;
&lt;p&gt;Now we know why it is there, what to do we call it? I like &lt;code&gt;state&lt;/code&gt; 
because the parameter represents state the caller want&amp;#39;s to preserve. I don&amp;#39;t 
like &lt;code&gt;object&lt;/code&gt; because it is a common reserved word. I don&amp;#39;t like
&lt;code&gt;stateObject&lt;/code&gt; because a symbol&amp;#39;s type should not be repeated in the 
name, we already know it is an &lt;code&gt;&lt;b&gt;object&lt;/b&gt;&lt;/code&gt; by its type. &lt;code&gt;
asyncState&lt;/code&gt; is acceptable, especially since that is the name it is given 
by &lt;code&gt;IAsyncResult&lt;/code&gt;, but it is a bit redundant, we already know, by 
context, it is asynchronous state. Plus we should avoid abbreviation, like &amp;quot;async&amp;quot;, 
in symbol names (though it is very common, and asynchronous is very very long, 
so not that bad). &lt;code&gt;data&lt;/code&gt; seems fine to me, it is a synonym to state, 
but it is overused. &lt;code&gt;extraData&lt;/code&gt; I cannot, for the life of me, figure 
out. Extra for whom? Extra as opposed to what? Unfortunately, this is the name 
given to the parameter by &lt;code&gt;IHttpAsyncHandler&lt;/code&gt; (see, I told you &amp;quot;async&amp;quot; 
was common).&amp;nbsp; Its name tells me nothing about what I should do with it. It 
is very unclear that this value should be mapped to &lt;code&gt;AsyncState&lt;/code&gt; in &lt;code&gt;IAsyncResult&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I propose we call it &lt;code&gt;state&lt;/code&gt;, with an acceptable variation of
&lt;code&gt;asyncState&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Now, if changing a parameter name was not a breaking change...&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Trivia: &lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;The above uses the &lt;a href="http://live.com"&gt;Live Services&lt;/a&gt; that you 
	can find more about &lt;a href="http://dev.live.com"&gt;here&lt;/a&gt;.&lt;/li&gt;
	&lt;li&gt;The IM presence service returns JSON which I parse using a fancy looking
	&lt;code&gt;Regex&lt;/code&gt; instance. I recommend that production code use &lt;code&gt;
	DataContractJsonSerializer() &lt;/code&gt;instead.&lt;/li&gt;
&lt;/ul&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/b30e6145-bbfa-4697-992c-61d88f23bf14</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>If you are using a loop, you're doing it wrong</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/6080a8a8-bb63-4492-acd2-1398f086fca0</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/6080a8a8-bb63-4492-acd2-1398f086fca0</link>
      <pubDate>Sat, 29 Mar 2008 16:55:39 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;&amp;quot;If you are using a loop, you&amp;#39;re doing it wrong.&amp;quot; &lt;/p&gt;
&lt;p&gt;That is the advice one of my college professors told us when he was teaching us
&lt;a href="http://en.wikipedia.org/wiki/APL_(programming_language)"&gt;APL&lt;/a&gt;. APL 
was designed to perform vector and matrix operations. Programming in APL is an 
exercise in stringing operators together to perform strange and wonderful 
things. Using a loop is just wrong and slows things down.&lt;/p&gt;
&lt;p&gt;It is similar with LINQ, if you are using a loop you are doing it wrong. I 
find myself 
doing a lot of prototyping lately and I am forcing myself to use LINQ; not 
because I don&amp;#39;t like it, far from it, I really like LINQ, but using loops is so 
ingrained into my psyche that I have to stop myself and force myself to think in 
LINQ. Every time I am tempted to write a loop that involves a collection or an 
array I ask myself, could I use LINQ instead? Programmers with more of a 
database background seem to take to LINQ like a duck to water. They think in 
sets and vectors, I don&amp;#39;t, but I am getting there.&lt;/p&gt;
&lt;p&gt;For example sometimes I find myself needing to return an &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; when 
I have a &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; but of a different &lt;code&gt;T&lt;/code&gt;. This often happens when I want to keep 
internal implementation details private. My internal &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; might have the 
actual class but I need to return an enumerable for some interface. Before I 
would simply write a loop using the C# 2.0&amp;#39;s &lt;code&gt;&lt;strong&gt;yield&lt;/strong&gt;&lt;/code&gt; syntax,&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre class="code"&gt;
List&amp;lt;Foo&amp;gt; foos = &lt;strong&gt;new&lt;/strong&gt; List&amp;lt;Foo&amp;gt;();

...

&lt;strong&gt;public&lt;/strong&gt; IEnumerable&amp;lt;IFoo&amp;gt; Foos {
    &lt;strong&gt;get&lt;/strong&gt; {
        &lt;strong&gt;foreach&lt;/strong&gt; (Foo f &lt;strong&gt;in&lt;/strong&gt; foos)
            &lt;strong&gt;yield return&lt;/strong&gt; f;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This loop involves a collection, can I use LINQ? Sure! By using LINQ&amp;#39;s &lt;code&gt;Cast&amp;lt;T&amp;gt;()&lt;/code&gt; method this can be replaced with,&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre class="code"&gt;
&lt;strong&gt;public&lt;/strong&gt; IEnumerable&amp;lt;IFoo&amp;gt; Foos {
    &lt;strong&gt;get&lt;/strong&gt; { &lt;strong&gt;return&lt;/strong&gt; foos.Cast&amp;lt;IFoo&amp;gt;(); }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;If you are trying to find if a list contains an object by some name, you 
could write a loop like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;
&lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Contains(&lt;strong&gt;string&lt;/strong&gt; value) {
    &lt;strong&gt;foreach&lt;/strong&gt; (Foo foo &lt;strong&gt;in&lt;/strong&gt; foos)
        &lt;strong&gt;if&lt;/strong&gt; (foo.Name == value)
            &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;true&lt;/strong&gt;;
    &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;false&lt;/strong&gt;;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Using LINQ this might look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;
&lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Contains(&lt;strong&gt;string&lt;/strong&gt; value) {
    &lt;strong&gt;return&lt;/strong&gt; (&lt;strong&gt;from&lt;/strong&gt; foo &lt;strong&gt;in&lt;/strong&gt; foos &lt;strong&gt;where&lt;/strong&gt; foo.Name == value &lt;strong&gt;select&lt;/strong&gt; foo).Any();
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;A nice thing about LINQ is you can perform complicated queries in pieces. 
With deferred execution of enumerators, this is fairly efficient as well. This 
is really helpful in the debugger. In one chunk of code I was writing I needed to 
coalesce adjacent ranges that are marked with the same text value. Assume you 
have a structure called Range that looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;struct&lt;/strong&gt; Range {
    &lt;strong&gt;public int&lt;/strong&gt; Start;
    &lt;strong&gt;public int&lt;/strong&gt; Length;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;and another &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; that labels the ranges with names,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;struct&lt;/strong&gt; NamedRange {
    &lt;strong&gt;public string&lt;/strong&gt; Name;
    &lt;strong&gt;public&lt;/strong&gt; Range Range;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Now lets have a routine that calculates the range information over some 
stream,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;public&lt;/strong&gt; IEnumerable&amp;lt;NamedRange&amp;gt; GetNamedRanges(Stream stream) {
    ...
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Lets assume that name ranges are some things like &amp;quot;whtespace&amp;quot;, &amp;quot;reserved&amp;quot;, 
&amp;quot;identifier&amp;quot;, &amp;quot;number&amp;quot; &amp;quot;string&amp;quot;, etc. as you might expect to receive from a 
lexical scanner like found in this
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e"&gt;
post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;What I want to do with these ranges is to convert the names into styles such 
as you might find referencing a CSS style sheet. So, in effect, I am mapping 
NameRange values to StyledRange values where StyleRange would look something 
like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;struct&lt;/strong&gt; StyledRange {
    &lt;strong&gt;public&lt;/strong&gt; Style Style;
    &lt;strong&gt;public&lt;/strong&gt; Range Range;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Lets create a dictionary that maps range names to styles such as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre cla="code"&gt;styleMap["number"] = &lt;strong&gt;new&lt;/strong&gt; Style() { Name = "green" };
styleMap["reserved"] = &lt;strong&gt;new&lt;/strong&gt; Style() { Name = "bold" };&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;I only wanted to highlight numbers and reserved words, for everything 
else I will use the default style,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;defaultStyle = &lt;strong&gt;new&lt;/strong&gt; Style { Name = "normal" };&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;We can translate our named ranges directly into styled ranges by using a
LINQ query expression such as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;var&lt;/strong&gt; ranges = GetNamedRanges(stream);
&lt;strong&gt;var&lt;/strong&gt; styledRanges = &lt;strong&gt;from&lt;/strong&gt; range &lt;strong&gt;in&lt;/strong&gt; ranges
                  &lt;strong&gt; select new&lt;/strong&gt; StyledRange() {
                       Style = styleMap.MapOrDefault(range.Name) ?? defaultStyle,
                       Range = range.Range
                   };
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;where &lt;code&gt;MapOrDefault()&lt;/code&gt; is an extension method for &lt;code&gt;
IDictionary&amp;lt;TKey, TValue&amp;gt;&lt;/code&gt; that looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;public static&lt;/strong&gt; TValue MapOrDefault&lt;TKey, TValue&gt;(&lt;strong&gt;this&lt;/strong&gt; IDictionary&lt;TKey, TValue&gt; dictionary, TKey key) {
    TValue result;
    &lt;strong&gt;if&lt;/strong&gt; (dictionary.TryGetValue(key, &lt;strong&gt;out&lt;/strong&gt; result))
        &lt;strong&gt;return&lt;/strong&gt; result;
    &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;default&lt;/strong&gt;(TValue);
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;which is patterned after the existing LINQ methods for &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;,
&lt;code&gt;FirstOrDefault()&lt;/code&gt; and &lt;code&gt;LastOrDefault()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Since many of the ranges that have different names will have the same style, it 
would be nice to coalesce adjacent styles together so no two adjacent ranges 
have the same style. In other words, we only want a new styled range when the 
style changes. The above query expression just produces a one-to-one 
mapping of named range to styled range. What we need is something that will 
merge adjacent ranges. Do do this I will introduce another extension method,
&lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; for &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;public static&lt;/strong&gt; IEnumerable&amp;lt;T&amp;gt; Reduce&amp;lt;T&amp;gt;(&lt;strong&gt;this&lt;/strong&gt; IEnumerable&amp;lt;T&amp;gt; e,
    Func&amp;lt;T, T, &lt;strong&gt;bool&lt;/strong&gt;&amp;gt; match,
    Func&amp;lt;T, T, T&amp;gt; reduce) {
    &lt;strong&gt;var&lt;/strong&gt; en = e.GetEnumerator();
    T last;
    &lt;strong&gt;if&lt;/strong&gt; (en.MoveNext()) {
        last = en.Current;
        &lt;strong&gt;while&lt;/strong&gt; (en.MoveNext()) {
            &lt;strong&gt;if&lt;/strong&gt; (!match(last, en.Current)) {
                &lt;strong&gt;yield return&lt;/strong&gt; last;
                last = en.Current;
            }
            &lt;strong&gt;else&lt;/strong&gt;
                last = reduce(last, en.Current);
        }
        &lt;strong&gt;yield return&lt;/strong&gt; last;
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;What this method does is if two adjacent elements match (as defined by the &lt;code&gt;match&lt;/code&gt; 
delegate returning &lt;code&gt;&lt;strong&gt;true&lt;/strong&gt;&lt;/code&gt;) they will be reduced into one element by calling the &lt;code&gt;reduce&lt;/code&gt; 
delegate. For example, the &lt;code&gt;Sum&amp;lt;T&amp;gt;()&lt;/code &gt;standard extension method could be 
implemented using &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;var&lt;/strong&gt; sum = numbers.Reduce((a, b) =&amp;gt; true, (a, b) =&amp;gt; a + b).First();&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Now that we have &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt;, lets reduce the list of styled 
ranges to coalesce the adjacent ranges with the same style. This can be done by,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;styledRanges = styledRanges.Reduce(
    (r1, r2) =&amp;gt; r1.Style == r2.Style,
    (r1, r2) =&amp;gt; &lt;strong&gt;new&lt;/strong&gt; StyledRange() {
        Style = r1.Style,
        Range = MergeRanges(r1.Range, r2.Range)});&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;code&gt;MergeRanges()&lt;/code&gt; referenced above, is,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;Range MergeRanges(Range r1, Range r2) {
    &lt;strong&gt;return new&lt;/strong&gt; Range() { Start = r1.Start, Length = r2.Start - r1.Start + r2.Length };
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;In my example, this took 18 ranges for a typical line of C# source down to 7 
ranges. Pretty good. But I noticed that some of those ranges were styling 
whitespace as &amp;quot;normal&amp;quot;. This seems like a waste; why switch back from 
green to black text for writing whitespace? Why not combine those with 
adjacent ranges instead? A simple approach to this is to add the following code 
prior to mapping the styles,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;ranges = ranges.Reduce(
    (r1, r2) =&gt; r1.Name == "whitespace" || r2.Name == "whitespace",
    (r1, r2) =&gt; &lt;strong&gt;new&lt;/strong&gt; NamedRange() {
        Name = r1.Name == "whitespace" ? r2.Name : r1.Name,
        Range = MergeRanges(r1.Range, r2.Range)
    });&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This says to merge whitespace ranges with adjacent non-whitespace ranges. 
This reduces the range count from 7 to 4. Not bad from the original 18 and that 
was just for one line of source. This savings adds up quickly over an entire file.&lt;/p&gt;
&lt;p&gt;The complete example, made as a function, looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;IEnumerable&amp;lt;StyledRange&amp;gt; StyleRanges(IEnumerable&amp;lt;NamedRange&amp;gt; ranges) {

    &lt;em&gt;// Merge whitespace ranges with adjacent non-whitespace ranges&lt;/em&gt;
    ranges = ranges.Reduce(
        (r1, r2) =&amp;gt; r1.Name == "whitespace" || r2.Name == "whitespace",
        (r1, r2) =&amp;gt; new NamedRange() {
            Name = r1.Name == "whitespace" ? r2.Name : r1.Name,
            Range = MergeRanges(r1.Range, r2.Range)});

    &lt;em&gt;// Map named ranges to styles.&lt;/em&gt;
    &lt;strong&gt;var&lt;/strong&gt; styledRanges = &lt;strong&gt;from&lt;/strong&gt; range &lt;strong&gt;in&lt;/strong&gt; ranges 
                       &lt;strong&gt;select new&lt;/strong&gt; StyledRange() { 
                           Style = styleMap.MapOrDefault(range.Name) ?? defaultStyle,
                           Range = range.Range };

    &lt;em&gt;// Merge adjacent ranges with the same style.&lt;/em&gt;
    styledRanges = styledRanges.Reduce(
        (r1, r2) =&amp;gt; r1.Style == r2.Style,
        (r1, r2) =&amp;gt; &lt;strong&gt;new&lt;/strong&gt; StyledRange() {
            Style = r1.Style,
            Range = MergeRanges(r1.Range, r2.Range)});

    &lt;strong&gt;return&lt;/strong&gt; styledRanges;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;There are a few nice things about this function. First, it builds up an &lt;code&gt;
IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; but this enumerable doesn&amp;#39;t execute until one of its 
enumerators is enumerated. This is due to the deferred execution of enumerators. 
Second, even though deferred execution makes single step debugging challenging, 
you can get a picture of what the function will do by using &lt;code&gt;ToArray()&lt;/code&gt; 
in the watch windows on the intermediate results. This allows you to inspect the 
intermediate result to see if the mapping or reducing is what you expected. 
Third, this routine has no loops. It operates on each enumerable as a set. Now 
some of you will rightly say there is a loop buried in the &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; 
method. True; &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; is just like many other LINQ extension 
methods, they contain loops implied by the returned enumerator. But LINQ allows me to write code that communicates 
what I am trying to do without it being obscured by the details of how it is done. 
I think of LINQ not so much as a set of features in C# but a way of programming. 
A way of programming that, if you are using loops, you are doing it wrong.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/6080a8a8-bb63-4492-acd2-1398f086fca0</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Scanners (not the movie)</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e</link>
      <pubDate>Sun, 30 Dec 2007 17:01:58 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;In my previous post I introduced a program I wrote to that uses the method 
described in 
&lt;a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;amp;qid=1192783059&amp;amp;sr=11-1"&gt;First-Order Logic&lt;/a&gt; by
&lt;a href="http://en.wikipedia.org/wiki/Raymond_Smullyan"&gt;Raymond M. Smullyan&lt;/a&gt; 
to prove an arbitrary propositional logic expression is a tautology. In this 
program I use some techniques that I want to describe. The first is the scanner. 
When writing scanners I have always hand written the scanner. There are two 
primary reasons for this, first I have never found scanners that difficult to 
write and, second, they are very time critical, often taking more than 20% of 
the overall parsing time, and auto-generated scanners are hard to optimize. 
Tableaux uses a hand-written scanner. The code for the scanner is in Scanner.cs 
in the zip file found
&lt;a href="http://removingalldoubt.com/Examples/Tableaux.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A scanner is a routine that takes text input and classifies it into a stream 
of tokens. Scanners typically give one token at a time. The scanner is the lowest level of the parsing process. Parsers 
are built on top of scanners and use the scanner results to determine the 
meaning of the source using some kind of grammar. The distinction between the 
parser and the scanner is somewhat arbitrary. You could just consider each 
character of the input as a token and build the parser up from there. Doing this 
is typically slower than a traditional scanner, however, so most parsers use a 
scanner. The line between the scanner and the parser is usually drawn at the 
lexical elements such as identifiers, reserved words, numeric and string 
constants, comments, etc. More formally, a lexical element is a string of 
characters that can be matched and classified by a regular expression. Scanner 
generators, such as &lt;a href="http://en.wikipedia.org/wiki/Lex_programming_tool"&gt;
Lex&lt;/a&gt;, use regular expressions to specify the scanner.&lt;/p&gt;
&lt;p&gt;The trick to a fast scanner is to reduce the per-character cost of the 
scanner. One way to do this is to make sure you are executing the fewest number of instructions 
per-character-scanned as possible. A few of tricks I use to reduce the 
per-character cost include,&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Use the switch statement&lt;ul&gt;
		&lt;li&gt;That included switch or case statement typically heavily optimize 
		the result, often generating jump tables.&lt;/li&gt;
	&lt;/ul&gt;
	&lt;/li&gt;
	&lt;li&gt;Pull fields into local variables and only write them at the before 
	returning.&lt;ul&gt;
		&lt;li&gt;Local variables can be mapped to registers during code generation. 
		Fields never will be. Stores to global memory (i.e. a field of a object 
		allocated from the heap) are very hard for code generators to optimize. 
		Local variable are much easier.&lt;/li&gt;
	&lt;/ul&gt;
	&lt;/li&gt;
	&lt;li&gt;Make checking for boundaries (end of file or end of buffer) appear as a 
	character.&lt;ul&gt;
		&lt;li&gt;This merges the end-of-file check with character classification.&lt;/li&gt;
		&lt;li&gt;In this case I use the character value 0 to indicate end of file. If 
		I was willing to use unsafe code I would have taken advantage of the 
		fact that the CLR ensures a 0 value at the end of every string.&lt;/li&gt;
	&lt;/ul&gt;
	&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;One thing that looks slow that isn&amp;#39;t is the GetChar() routine. Normally you 
would see that and think I am paying for a CALL/RET pair but his gets inlined in 
retail. I am paying for the end of buffer check every character but, as noted 
above, this can be removed if I wanted to use unsafe code, definitely overkill 
for a small program like tableaux.&lt;/p&gt;
&lt;p&gt;I went a bit overboard, intentionally, with identifier. It handles C# style 
identifiers, handling Unicode letter and number classifications. To avoid 
calling the Unicode classification routines for every character I hard-coded the 
ASCII part and only call the Unicode classification routines when I encounter a 
non-ASCII potential identifier character. It is not that the classification 
routines are slow, it is that every cycle counts in the scanner and avoiding the 
CALL/RET and character table look is significant for file that contain mostly 
ASCII characters. Note also that I hard-code some non-identifier characters in 
the identifier internal loop. This avoids calling the Unicode classification 
routines for those character, which are the most common characters you might 
find after an identifier, which avoids calling the Unicode classification routines 
at all for most input.&lt;/p&gt;

&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>In my previous post I introduced a program I wrote to that uses the method 
described in 
<a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;qid=1192783059&amp;sr=11-1">First-Order Logic</a> by
<a href="http://en.wikipedia.org/wiki/Raymond_Smullyan">Raymond M. Smullyan</a> 
to prove an arbitrary propositional logic expression is a tautology. In this 
program I use some techniques that I want to describe. The first is the scanner. 
When writing scanners I have always hand written the scanner. There are two 
primary reasons for this, first I have never found scanners that difficult to 
write and, second, they are very time critical, often taking more than 20% of 
the overall parsing time, and auto-generated scanners are hard to optimize. 
Tableaux uses a hand-written scanner. The code for the scanner is in Scanner.cs 
in the zip file found
<a href="http://removingalldoubt.com/Examples/Tableaux.zip">here</a>.</p>
        <p>A scanner is a routine that takes text input and classifies it into a stream 
of tokens. Scanners typically give one token at a time. The scanner is the lowest level of the parsing process. Parsers 
are built on top of scanners and use the scanner results to determine the 
meaning of the source using some kind of grammar. The distinction between the 
parser and the scanner is somewhat arbitrary. You could just consider each 
character of the input as a token and build the parser up from there. Doing this 
is typically slower than a traditional scanner, however, so most parsers use a 
scanner. The line between the scanner and the parser is usually drawn at the 
lexical elements such as identifiers, reserved words, numeric and string 
constants, comments, etc. More formally, a lexical element is a string of 
characters that can be matched and classified by a regular expression. Scanner 
generators, such as <a href="http://en.wikipedia.org/wiki/Lex_programming_tool">
Lex</a>, use regular expressions to specify the scanner.</p>
        <p>The trick to a fast scanner is to reduce the per-character cost of the 
scanner. One way to do this is to make sure you are executing the fewest number of instructions 
per-character-scanned as possible. A few of tricks I use to reduce the 
per-character cost include,</p>
        <ol>
          <li>Use the switch statement<ul><li>That included switch or case statement typically heavily optimize 
		the result, often generating jump tables.</li></ul></li>
          <li>Pull fields into local variables and only write them at the before 
	returning.<ul><li>Local variables can be mapped to registers during code generation. 
		Fields never will be. Stores to global memory (i.e. a field of a object 
		allocated from the heap) are very hard for code generators to optimize. 
		Local variable are much easier.</li></ul></li>
          <li>Make checking for boundaries (end of file or end of buffer) appear as a 
	character.<ul><li>This merges the end-of-file check with character classification.</li><li>In this case I use the character value 0 to indicate end of file. If 
		I was willing to use unsafe code I would have taken advantage of the 
		fact that the CLR ensures a 0 value at the end of every string.</li></ul></li>
        </ol>
        <p>One thing that looks slow that isn't is the GetChar() routine. Normally you 
would see that and think I am paying for a CALL/RET pair but his gets inlined in 
retail. I am paying for the end of buffer check every character but, as noted 
above, this can be removed if I wanted to use unsafe code, definitely overkill 
for a small program like tableaux.</p>
        <p>I went a bit overboard, intentionally, with identifier. It handles C# style 
identifiers, handling Unicode letter and number classifications. To avoid 
calling the Unicode classification routines for every character I hard-coded the 
ASCII part and only call the Unicode classification routines when I encounter a 
non-ASCII potential identifier character. It is not that the classification 
routines are slow, it is that every cycle counts in the scanner and avoiding the 
CALL/RET and character table look is significant for file that contain mostly 
ASCII characters. Note also that I hard-code some non-identifier characters in 
the identifier internal loop. This avoids calling the Unicode classification 
routines for those character, which are the most common characters you might 
find after an identifier, which avoids calling the Unicode classification routines 
at all for most input.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>To b | !b, that is the question</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/1234d0f1-4ecd-424b-b2a0-cf855148f19b</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/1234d0f1-4ecd-424b-b2a0-cf855148f19b</link>
      <pubDate>Wed, 19 Dec 2007 21:10:53 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
   &lt;p&gt;When I was reading 
&lt;a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;amp;qid=1192783059&amp;amp;sr=11-1"&gt;First-Order Logic&lt;/a&gt; by
&lt;a href="http://en.wikipedia.org/wiki/Raymond_Smullyan"&gt;Raymond M. Smullyan&lt;/a&gt; I 
was fascinated by 
the second chapter in which he describes a method for proving a propositional 
logic expression is a tautology. This method is called the Tableau Method. The Tableau Method is a 
rather straight forward way to prove a statement is always going to be true by 
demonstrating that asserting it is false will result in a contradiction. The 
propositional logic expression language Dr. Smullyan uses is rather simple. I 
present a modified version of it here. My version 
contains a not operator (!), a conjunction operator (&amp;amp;), a disjunction operator 
(|) and an implication operator (→).&lt;sup&gt;&lt;a name="note1_1ref" href="#note1_1"&gt;1&lt;/a&gt;&lt;/sup&gt; For example,&lt;/p&gt;
&lt;p style="margin-left: 40px;"&gt;p &amp;amp; q&lt;/p&gt;
&lt;p&gt;is true when both &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;q&lt;/em&gt; are true; &lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;p | q&lt;/p&gt;
&lt;p&gt;is true when either &lt;em&gt;p&lt;/em&gt; is true or &lt;em&gt;q&lt;/em&gt; is true;&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;p &lt;span class="style1"&gt;→ q&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;is true when&lt;em&gt; p &lt;/em&gt;is false or &lt;em&gt;p&lt;/em&gt; is true and &lt;em&gt;q&lt;/em&gt; is also 
true; and finally,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;!p&lt;/p&gt;
&lt;p&gt;is true only when &lt;em&gt;p&lt;/em&gt; is false. This should be very familiar to any 
programmer. A propositional logic expression is a tautology if it will always be 
true regardless of the value of its propositional variables. An example of a 
simple tautology is,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;p | !p&lt;/p&gt;
&lt;p&gt;which will be true if &lt;em&gt;p&lt;/em&gt; is true or false. This statement is always 
true. This can be proven by simply demonstrating that asserting it is false 
results in a contradiction. For example, we assert a statement is false by 
prefixing it with a capital F or true with a capital T. For the above expression 
this would look like,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;F p | !p&lt;/p&gt;
&lt;p&gt;For this to be false both of the sub-expressions would also have to be 
false. This would then look like&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;F p&lt;br/&gt;F !p&lt;/p&gt;
&lt;p&gt;For &lt;em&gt;!p&lt;/em&gt; to be false &lt;em&gt;p&lt;/em&gt; would have to be true, which looks 
like,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;T p&lt;/p&gt;
&lt;p&gt;Now we have a contradiction, according to propositional logic, &lt;em&gt;p&lt;/em&gt; cannot be both true and false so &lt;em&gt;
p | !p&lt;/em&gt; must always be true. Using the Tableau Method this would look like,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;(1) F p | !p&lt;br/&gt;(2) F p (1)&lt;br/&gt;(3) F !p (1)&lt;br/&gt;(4) T p (3)&lt;br/&gt;X&lt;/p&gt;
&lt;p&gt;where the X indicates that the tableau ends in a contradiction (i.e. is 
closed) and the 
numbers to the left label the expressions and the numbers to the right indicate 
which expression the assertion is derived from. To produce a tableau you first 
assert the expression is false then use the following table to add assertions,&lt;/p&gt;
&lt;table style="width: 100%"&gt;
	&lt;tr&gt;
		&lt;td&gt;&lt;strong&gt;Expression of the form&lt;/strong&gt;&lt;/td&gt;
		&lt;td&gt;&lt;strong&gt;Asserts&lt;/strong&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T !p&lt;/td&gt;
		&lt;td&gt;F p&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F !p&lt;/td&gt;
		&lt;td&gt;T p&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T p &amp;amp; q&lt;/td&gt;
		&lt;td&gt;T p and T q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F p &amp;amp; q&lt;/td&gt;
		&lt;td&gt;F p or F q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T p | q&lt;/td&gt;
		&lt;td&gt;T p or T q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F p | q&lt;/td&gt;
		&lt;td&gt;F p and F q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T p → q&lt;/td&gt;
		&lt;td&gt;F p or T q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F p → q&lt;/td&gt;
		&lt;td&gt;T p and F q&lt;/td&gt;
	&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;When two expressions are asserted the table might branch. If the above table 
says &amp;quot;and&amp;quot; then both statement are asserted directly, but if it contains an &amp;quot;or&amp;quot; 
then both assertions must lead to a contradiction independently. For example, 
consider wanting to prove the transitive property of the implication operator, 
that is &lt;em&gt;(p→q &amp;amp; q→r) → (p→r)&lt;/em&gt;, this would start off with adding asserts 
until we are required to branch,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (1) F (p→q &amp;amp; q→r) → (p→r)&lt;br/&gt;
  (2) T p→q &amp;amp; q→r (1)&lt;br/&gt;
  (3) F p→r (1)&lt;br/&gt;
  (4) T p→q (2)&lt;br/&gt;
  (5) T q→r (2)&lt;br/&gt;
  (6) T p (3)&lt;br/&gt;
  (7) F r (3)&lt;br/&gt;
&lt;/p&gt;
&lt;p&gt;We now have to handle (4) and (5) with require us to branch the table. The first branch is 
the &lt;em&gt;F p&lt;/em&gt; branch,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (8) F p (4)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;p&gt;This lead immediately to a contradiction because of (6) so this branch of the tableau is closed. We now need
handle the &lt;em&gt;T q&lt;/em&gt; branch,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (9) T q (4)
&lt;/p&gt;
&lt;p&gt;This doesn't lead to an immediate contradiction so we need to branch again for (5). The first
branch for (5) looks like&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (10) F q (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;p&gt;This again leads to an immediate contradiction, we already asserted
that &lt;em&gt;q&lt;/em&gt; must be true in (9). The second branch for (5) is the &lt;em&gt;T r&lt;/em&gt; branch.&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (11) T r (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;p&gt;This also lead to an immediate contradiction because of (7). Since all 
branches lead to a contradiction the original expression must always be true.&lt;/p&gt;
&lt;p&gt;Putting this altogether we get,&lt;/p&gt;
&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;p&gt;
  (1) F (p→q &amp;amp; q→r) → (p→r)&lt;br/&gt;
  (2) T p→q &amp;amp; q→r (1)&lt;br/&gt;
  (3) F p→r (1)&lt;br/&gt;
  (4) T p→q (2)&lt;br/&gt;
  (5) T q→r (2)&lt;br/&gt;
  (6) T p (3)&lt;br/&gt;
  (7) F r (3)&lt;br/&gt;
&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;table style="text-align: center;"&gt;
&lt;tr&gt;
&lt;td valign="top" style="border-right-color: black; 
	border-right-style:solid; 
	border-right-width:thin; 
	padding-right: 10px"&gt;
&lt;p&gt;
  (8) F p (4)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;/td&gt;
&lt;td style="padding-right:10px;"&gt;
&lt;p&gt;
  (9) T q (4)
&lt;/p&gt;
&lt;table &gt;
&lt;tr&gt;
&lt;td style="border-right-color: black; 
	border-right-style:solid; 
	border-right-width:thin; 
	padding-right: 10px"&gt;
&lt;p &gt;
  (10) F q (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;/td&gt;
&lt;td style="padding-right:10px;"&gt;
&lt;p &gt;
  (11) T r (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;This is a simple and elegant way to demonstrate proof by contradiction. Of 
course I just had to write a program to tell me whether an 
arbitrary propositional logic expression is a tautology and automatically 
generate the tableau.&lt;/p&gt;
&lt;p&gt;You can find the source project that is works with the just released Visual 
Studio 2008 &lt;a href="http://removingalldoubt.com/Examples/Tableaux.zip"&gt;here&lt;/a&gt;. It requires VS 2008 because I am addicted to some of the new 
C# features, especially the &lt;b&gt;&lt;code&gt;var&lt;/code&gt;&lt;/b&gt; keyword.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;a name="note1_1"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; Dr. Sumullyan uses different characters for his operators 
but his characters are not as commonly included in browser fonts and are not as easy to 
type on a standard keyboard (using &lt;span class="style3"&gt;-&amp;gt;&lt;/span&gt; as a synonym 
of →) as the ones I use. &lt;a href="#note1_1ref"&gt;&amp;lt;&amp;lt; back&lt;/a&gt;&lt;/p&gt;

&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>When I was reading 
<a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;qid=1192783059&amp;sr=11-1">First-Order Logic</a> by
<a href="http://en.wikipedia.org/wiki/Raymond_Smullyan">Raymond M. Smullyan</a> I 
was fascinated by 
the second chapter in which he describes a method for proving a propositional 
logic expression is a tautology. This method is called the Tableau Method. The Tableau Method is a 
rather straight forward way to prove a statement is always going to be true by 
demonstrating that asserting it is false will result in a contradiction. The 
propositional logic expression language Dr. Smullyan uses is rather simple. I 
present a modified version of it here. My version 
contains a not operator (!), a conjunction operator (&amp;), a disjunction operator 
(|) and an implication operator (→).<sup><a name="note1_1ref" href="#note1_1">1</a></sup> For example,</p>
        <p style="margin-left: 40px;">p &amp; q</p>
        <p>is true when both <em>p</em> and <em>q</em> are true; </p>
        <p style="margin-left: 40px">p | q</p>
        <p>is true when either <em>p</em> is true or <em>q</em> is true;</p>
        <p style="margin-left: 40px">p <span class="style1">→ q</span></p>
        <p>is true when<em> p </em>is false or <em>p</em> is true and <em>q</em> is also 
true; and finally,</p>
        <p style="margin-left: 40px">!p</p>
        <p>is true only when <em>p</em> is false. This should be very familiar to any 
programmer. A propositional logic expression is a tautology if it will always be 
true regardless of the value of its propositional variables. An example of a 
simple tautology is,</p>
        <p style="margin-left: 40px">p | !p</p>
        <p>which will be true if <em>p</em> is true or false. This statement is always 
true. This can be proven by simply demonstrating that asserting it is false 
results in a contradiction. For example, we assert a statement is false by 
prefixing it with a capital F or true with a capital T. For the above expression 
this would look like,</p>
        <p style="margin-left: 40px">F p | !p</p>
        <p>For this to be false both of the sub-expressions would also have to be 
false. This would then look like</p>
        <p style="margin-left: 40px">F p<br />F !p</p>
        <p>For <em>!p</em> to be false <em>p</em> would have to be true, which looks 
like,</p>
        <p style="margin-left: 40px">T p</p>
        <p>Now we have a contradiction, according to propositional logic, <em>p</em> cannot be both true and false so <em>
p | !p</em> must always be true. Using the Tableau Method this would look like,</p>
        <p style="margin-left: 40px">(1) F p | !p<br />(2) F p (1)<br />(3) F !p (1)<br />(4) T p (3)<br />X</p>
        <p>where the X indicates that the tableau ends in a contradiction (i.e. is 
closed) and the 
numbers to the left label the expressions and the numbers to the right indicate 
which expression the assertion is derived from. To produce a tableau you first 
assert the expression is false then use the following table to add assertions,</p>
        <table style="width: 100%">
          <tr>
            <td>
              <strong>Expression of the form</strong>
            </td>
            <td>
              <strong>Asserts</strong>
            </td>
          </tr>
          <tr>
            <td style="width: 273px">T !p</td>
            <td>F p</td>
          </tr>
          <tr>
            <td style="width: 273px">F !p</td>
            <td>T p</td>
          </tr>
          <tr>
            <td style="width: 273px">T p &amp; q</td>
            <td>T p and T q</td>
          </tr>
          <tr>
            <td style="width: 273px">F p &amp; q</td>
            <td>F p or F q</td>
          </tr>
          <tr>
            <td style="width: 273px">T p | q</td>
            <td>T p or T q</td>
          </tr>
          <tr>
            <td style="width: 273px">F p | q</td>
            <td>F p and F q</td>
          </tr>
          <tr>
            <td style="width: 273px">T p → q</td>
            <td>F p or T q</td>
          </tr>
          <tr>
            <td style="width: 273px">F p → q</td>
            <td>T p and F q</td>
          </tr>
        </table>
        <p>When two expressions are asserted the table might branch. If the above table 
says "and" then both statement are asserted directly, but if it contains an "or" 
then both assertions must lead to a contradiction independently. For example, 
consider wanting to prove the transitive property of the implication operator, 
that is <em>(p→q &amp; q→r) → (p→r)</em>, this would start off with adding asserts 
until we are required to branch,</p>
        <p style="margin-left: 40px">
  (1) F (p→q &amp; q→r) → (p→r)<br />
  (2) T p→q &amp; q→r (1)<br />
  (3) F p→r (1)<br />
  (4) T p→q (2)<br />
  (5) T q→r (2)<br />
  (6) T p (3)<br />
  (7) F r (3)<br /></p>
        <p>We now have to handle (4) and (5) with require us to branch the table. The first branch is 
the <em>F p</em> branch,</p>
        <p style="margin-left: 40px">
  (8) F p (4)<br />
  X
</p>
        <p>This lead immediately to a contradiction because of (6) so this branch of the tableau is closed. We now need
handle the <em>T q</em> branch,</p>
        <p style="margin-left: 40px">
  (9) T q (4)
</p>
        <p>This doesn't lead to an immediate contradiction so we need to branch again for (5). The first
branch for (5) looks like</p>
        <p style="margin-left: 40px">
  (10) F q (5)<br />
  X
</p>
        <p>This again leads to an immediate contradiction, we already asserted
that <em>q</em> must be true in (9). The second branch for (5) is the <em>T r</em> branch.</p>
        <p style="margin-left: 40px">
  (11) T r (5)<br />
  X
</p>
        <p>This also lead to an immediate contradiction because of (7). Since all 
branches lead to a contradiction the original expression must always be true.</p>
        <p>Putting this altogether we get,</p>
        <table>
          <tr>
            <td>
              <p>
  (1) F (p→q &amp; q→r) → (p→r)<br />
  (2) T p→q &amp; q→r (1)<br />
  (3) F p→r (1)<br />
  (4) T p→q (2)<br />
  (5) T q→r (2)<br />
  (6) T p (3)<br />
  (7) F r (3)<br /></p>
            </td>
          </tr>
          <tr>
            <td>
              <table style="text-align: center;">
                <tr>
                  <td valign="top" style="border-right-color: black; &#xA;	border-right-style:solid; &#xA;	border-right-width:thin; &#xA;	padding-right: 10px">
                    <p>
  (8) F p (4)<br />
  X
</p>
                  </td>
                  <td style="padding-right:10px;">
                    <p>
  (9) T q (4)
</p>
                    <table>
                      <tr>
                        <td style="border-right-color: black; &#xA;	border-right-style:solid; &#xA;	border-right-width:thin; &#xA;	padding-right: 10px">
                          <p>
  (10) F q (5)<br />
  X
</p>
                        </td>
                        <td style="padding-right:10px;">
                          <p>
  (11) T r (5)<br />
  X
</p>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
        <p>This is a simple and elegant way to demonstrate proof by contradiction. Of 
course I just had to write a program to tell me whether an 
arbitrary propositional logic expression is a tautology and automatically 
generate the tableau.</p>
        <p>You can find the source project that is works with the just released Visual 
Studio 2008 <a href="http://removingalldoubt.com/Examples/Tableaux.zip">here</a>. It requires VS 2008 because I am addicted to some of the new 
C# features, especially the <b><code>var</code></b> keyword.</p>
        <hr />
        <p>
          <a name="note1_1">
            <sup>1</sup>
          </a> Dr. Sumullyan uses different characters for his operators 
but his characters are not as commonly included in browser fonts and are not as easy to 
type on a standard keyboard (using <span class="style3">-&gt;</span> as a synonym 
of →) as the ones I use. <a href="#note1_1ref">&lt;&lt; back</a></p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/1234d0f1-4ecd-424b-b2a0-cf855148f19b</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Operators, Generics and Policies II: Adapter Policy</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8</link>
      <pubDate>Tue, 31 Jul 2007 22:27:00 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;The mixin technique in my 
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7"&gt;last post&lt;/a&gt; was a bit awkward to use 
with generic 
methods. It is much less awkward to use for classes, however. For example, if 
you want an expression evaluator much like I posted
&lt;a href="http://www.removingalldoubt.com/commentview.aspx/bece3be7-04a1-4130-b1ac-0b88c94e7708"&gt;
here&lt;/a&gt;, but you want to leave the result type open, you can use this technique 
to do it.&lt;/p&gt;
&lt;p&gt;First, I declared a policy interface for the operators I wanted to abstract 
over,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;partial&lt;/b&gt; &lt;b&gt;interface&lt;/b&gt; IOperatorPolicy&amp;lt;T&amp;gt; {
    T Add(T a, T b);
    T Subtract(T a, T b);
    T Multiply(T a, T b);
    T Divide(T a, T b);
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Second, I created the operator policies for &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; 
and &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;. I could have created more, &lt;code&gt;
&lt;strong&gt;decimal&lt;/strong&gt;&lt;/code&gt;, &lt;code&gt;&lt;strong&gt;float&lt;/strong&gt;&lt;/code&gt;, etc. but 
two is sufficient for demonstration.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;partial&lt;/strong&gt; &lt;b&gt;struct&lt;/b&gt; IntOperatorPolicy : IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt; {
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Add(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b; }
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Subtract(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a - b; }
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Multiply(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a * b; }
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Divide(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a / b; }
}

&lt;b&gt;partial struct&lt;/b&gt; DoubleOperatorPolicy : IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt; {
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Add(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b;
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Subtract(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a - b; }
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Multiply(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a * b; }
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Divide(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a / b; }
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Next are the expression nodes themselves. I wrap them in a generic class 
that takes the parameters. This mitigates some of the clutter caused by the 
policy.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expression&amp;lt;T, OperatorPolicy&amp;gt;
    &lt;strong&gt;where&lt;/strong&gt; OperatorPolicy : &lt;b&gt;struct&lt;/b&gt;, IOperatorPolicy&amp;lt;T&amp;gt; {

    &lt;b&gt;static&lt;/b&gt; OperatorPolicy _operatorPolicy = &lt;b&gt;new&lt;/b&gt; OperatorPolicy();

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; T Evaluate();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Literal : Expr {
        &lt;b&gt;private&lt;/b&gt; T _literal;

        &lt;b&gt;public&lt;/b&gt; Literal(T literal) { _literal = literal; }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T Evaluate() {
            &lt;b&gt;return&lt;/b&gt; _literal;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;string&lt;/b&gt; ToString() {
            &lt;b&gt;return&lt;/b&gt; _literal.ToString();
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryOp : Expr {
        &lt;b&gt;private&lt;/b&gt; Expr _left;
        &lt;b&gt;private&lt;/b&gt; Expr _right;

        &lt;b&gt;protected&lt;/b&gt; BinaryOp(Expr left, Expr right) { _left = left; _right = right; }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T Evaluate() {
            &lt;b&gt;return&lt;/b&gt; EvaluateOp(_left.Evaluate(), _right.Evaluate());
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; T EvaluateOp(T left, T right);
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Add(left, right);
        }
    }
    
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Add(left, right);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Subtract : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Subtract(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Subtract(left, right);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Multiply : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Multiply(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Multiply(left, right);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Divide : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Divide(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Divide(left, right);
        }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Here the &lt;code&gt;Expression&lt;/code&gt; class acts as a container of a family of 
classes. Once you have an instance of one of the &lt;code&gt;Expr&lt;/code&gt; derived classes, calling 
&lt;code&gt;Evaluate()&lt;/code&gt; is straight-forward. Unfortunately, constructing one is a bit of a 
challenge. To get a literal of the &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; expression you would need to do,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i1 = &lt;strong&gt;new&lt;/strong&gt; Expression&amp;lt;&lt;strong&gt;int&lt;/strong&gt;, IntOperatorPolicy&amp;gt;.Literal(1);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;You can make this a little better by introducing a &lt;code&gt;&lt;strong&gt;static&lt;/strong&gt;&lt;/code&gt; 
method into &lt;code&gt;Expression&lt;/code&gt; like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr L(T literal) {
    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Literal(literal);
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;then the above becomes,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i1 = Expression&amp;lt;&lt;strong&gt;int&lt;/strong&gt;, IntOperatorPolicy&amp;gt;.L(1);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This still a bit awkward especially when you want to construct a more 
complicated expression,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; e = &lt;strong&gt;new&lt;/strong&gt; Expression&amp;lt;&lt;strong&gt;int&lt;/strong&gt;, IntOperatorPolicy&amp;gt;.Add(i1, i1);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This can be made significantly better by adding operator overloads to &lt;code&gt;Expr&lt;/code&gt; as 
in,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;strong&gt;partial&lt;/strong&gt; &lt;b&gt;class&lt;/b&gt; Expr {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; T Evaluate();
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; +(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Add(a, b);
    }
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; -(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Subtract(a, b);
    }
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; *(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Multiply(a, b);
    }
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; /(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Divide(a, b);
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;now the &lt;code&gt;e&lt;/code&gt; assignment can look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; e = i1 + i1;&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;and finally, to make it look even better you can put the code to create the 
expression in a static method of a class that derives from &lt;code&gt;Expression&lt;/code&gt; and closes the 
type parameters. Here are examples of one for &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; and 
a similar one for &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; TestInt : Expression&amp;lt;&lt;b&gt;int&lt;/b&gt;, IntOperatorPolicy&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Run() {
        &lt;strong&gt;var&lt;/strong&gt; iv = L(1) + L(2) * L(3);
        Console.WriteLine(iv.Evaluate());
    }
}

&lt;b&gt;class&lt;/b&gt; TestDouble : Expression&amp;lt;&lt;b&gt;double&lt;/b&gt;, DoubleOperatorPolicy&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Run() {
        &lt;strong&gt;var&lt;/strong&gt; dv = L(1.2) + L(3.4) * L(5.6);
        Console.WriteLine(dv.Evaluate());
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This shows taking advantage of the C# compiler&amp;#39;s operator overloading to 
produce an expression tree and the use of the &lt;code&gt;L()&lt;/code&gt; method as a sort 
of cast to change a literal of &lt;code&gt;T&lt;/code&gt; into a &lt;code&gt;Literal&amp;lt;T&amp;gt;&lt;/code&gt;. 
The call to &lt;code&gt;Evaluate()&lt;/code&gt; calculates the result of the expression as 
an &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; or &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;. 
The code generated, as discussed
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7"&gt;
last time&lt;/a&gt;, is quite good when JIT&amp;#39;ing outside the debugger and using 
optimized retail bits.&lt;/p&gt;
&lt;p&gt;This use of a policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; is what I refer to 
as an &lt;em&gt;adapter policy&lt;/em&gt;. The &lt;code&gt;Expression&lt;/code&gt; class has an 
abstraction it supports, represented by &lt;code&gt;IOperatorPolicy&amp;lt;T&amp;gt;&lt;/code&gt;, but 
this abstraction is not supported by any of the interesting types you would want 
to pass as &lt;code&gt;Expression&lt;/code&gt;&amp;#39;s &lt;code&gt;T&lt;/code&gt;. This is solved by creating 
an &lt;em&gt;adapter policy&lt;/em&gt; and passing that along with &lt;code&gt;T&lt;/code&gt;. This 
allows a generic type to introduce an abstraction that is unknown to the types 
the generic wants to range over, allow us, as above, to pass &lt;code&gt;int&lt;/code&gt; 
for &lt;code&gt;Expression&lt;/code&gt;&amp;#39;s &lt;code&gt;T&lt;/code&gt; even though &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; 
doesn&amp;#39;t implement &lt;code&gt;IOperatorPolicy&amp;lt;T&amp;gt;&lt;/code&gt; itself.&lt;/p&gt;
&lt;p&gt;Next time I will discuss another application of an &lt;em&gt;adapter policy&lt;/em&gt;.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>The mixin technique in my 
<a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7">last post</a> was a bit awkward to use 
with generic 
methods. It is much less awkward to use for classes, however. For example, if 
you want an expression evaluator much like I posted
<a href="http://www.removingalldoubt.com/commentview.aspx/bece3be7-04a1-4130-b1ac-0b88c94e7708">
here</a>, but you want to leave the result type open, you can use this technique 
to do it.</p>
        <p>First, I declared a policy interface for the operators I wanted to abstract 
over,</p>
        <blockquote>
          <pre>
            <b>partial</b>
            <b>interface</b> IOperatorPolicy&lt;T&gt; {
    T Add(T a, T b);
    T Subtract(T a, T b);
    T Multiply(T a, T b);
    T Divide(T a, T b);
}</pre>
        </blockquote>
        <p>Second, I created the operator policies for <code><strong>int</strong></code> 
and <code><strong>double</strong></code>. I could have created more, <code><strong>decimal</strong></code>, <code><strong>float</strong></code>, etc. but 
two is sufficient for demonstration.</p>
        <blockquote>
          <pre>
            <strong>partial</strong>
            <b>struct</b> IntOperatorPolicy : IOperatorPolicy&lt;<b>int</b>&gt; {
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Add(<b>int</b> a, <b>int</b> b) { <b>return</b> a + b; }
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Subtract(<b>int</b> a, <b>int</b> b) { <b>return</b> a - b; }
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Multiply(<b>int</b> a, <b>int</b> b) { <b>return</b> a * b; }
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Divide(<b>int</b> a, <b>int</b> b) { <b>return</b> a / b; }
}

<b>partial struct</b> DoubleOperatorPolicy : IOperatorPolicy&lt;<b>double</b>&gt; {
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Add(<b>double</b> a, <b>double</b> b) { <b>return</b> a + b;
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Subtract(<b>double</b> a, <b>double</b> b) { <b>return</b> a - b; }
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Multiply(<b>double</b> a, <b>double</b> b) { <b>return</b> a * b; }
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Divide(<b>double</b> a, <b>double</b> b) { <b>return</b> a / b; }
}</pre>
        </blockquote>
        <p>Next are the expression nodes themselves. I wrap them in a generic class 
that takes the parameters. This mitigates some of the clutter caused by the 
policy.</p>
        <blockquote>
          <pre>
            <b>partial</b>
            <b>class</b> Expression&lt;T, OperatorPolicy&gt;
    <strong>where</strong> OperatorPolicy : <b>struct</b>, IOperatorPolicy&lt;T&gt; {

    <b>static</b> OperatorPolicy _operatorPolicy = <b>new</b> OperatorPolicy();

    <b>public</b><b>abstract</b><b>partial</b><b>class</b> Expr {
        <b>public</b><b>abstract</b> T Evaluate();
    }

    <b>public</b><b>partial</b><b>class</b> Literal : Expr {
        <b>private</b> T _literal;

        <b>public</b> Literal(T literal) { _literal = literal; }

        <b>public</b><b>override</b> T Evaluate() {
            <b>return</b> _literal;
        }

        <b>public</b><b>override</b><b>string</b> ToString() {
            <b>return</b> _literal.ToString();
        }
    }

    <b>public</b><b>abstract</b><b>partial</b><b>class</b> BinaryOp : Expr {
        <b>private</b> Expr _left;
        <b>private</b> Expr _right;

        <b>protected</b> BinaryOp(Expr left, Expr right) { _left = left; _right = right; }

        <b>public</b><b>override</b> T Evaluate() {
            <b>return</b> EvaluateOp(_left.Evaluate(), _right.Evaluate());
        }

        <b>protected</b><b>abstract</b> T EvaluateOp(T left, T right);
    }

    <b>public</b><b>partial</b><b>class</b> Add : BinaryOp {
        <b>public</b> Add(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Add(left, right);
        }
    }
    
    <b>public</b><b>partial</b><b>class</b> Add : BinaryOp {
        <b>public</b> Add(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Add(left, right);
        }
    }

    <b>public</b><b>partial</b><b>class</b> Subtract : BinaryOp {
        <b>public</b> Subtract(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Subtract(left, right);
        }
    }

    <b>public</b><b>partial</b><b>class</b> Multiply : BinaryOp {
        <b>public</b> Multiply(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Multiply(left, right);
        }
    }

    <b>public</b><b>partial</b><b>class</b> Divide : BinaryOp {
        <b>public</b> Divide(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Divide(left, right);
        }
    }
}</pre>
        </blockquote>
        <p>Here the <code>Expression</code> class acts as a container of a family of 
classes. Once you have an instance of one of the <code>Expr</code> derived classes, calling 
<code>Evaluate()</code> is straight-forward. Unfortunately, constructing one is a bit of a 
challenge. To get a literal of the <code><strong>int</strong></code> expression you would need to do,</p>
        <blockquote>
          <pre>
            <strong>var</strong> i1 = <strong>new</strong> Expression&lt;<strong>int</strong>, IntOperatorPolicy&gt;.Literal(1);</pre>
        </blockquote>
        <p>You can make this a little better by introducing a <code><strong>static</strong></code> 
method into <code>Expression</code> like,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b> Expr L(T literal) {
    <b>return</b><b>new</b> Literal(literal);
}</pre>
        </blockquote>
        <p>then the above becomes,</p>
        <blockquote>
          <pre>
            <strong>var</strong> i1 = Expression&lt;<strong>int</strong>, IntOperatorPolicy&gt;.L(1);</pre>
        </blockquote>
        <p>This still a bit awkward especially when you want to construct a more 
complicated expression,</p>
        <blockquote>
          <pre>
            <strong>var</strong> e = <strong>new</strong> Expression&lt;<strong>int</strong>, IntOperatorPolicy&gt;.Add(i1, i1);</pre>
        </blockquote>
        <p>This can be made significantly better by adding operator overloads to <code>Expr</code> as 
in,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>abstract</b>
            <strong>partial</strong>
            <b>class</b> Expr {
    <b>public</b><b>abstract</b> T Evaluate();
    <b>public</b><b>static</b> Expr <b>operator</b> +(Expr a, Expr b) {
        <b>return</b><b>new</b> Add(a, b);
    }
    <b>public</b><b>static</b> Expr <b>operator</b> -(Expr a, Expr b) {
        <b>return</b><b>new</b> Subtract(a, b);
    }
    <b>public</b><b>static</b> Expr <b>operator</b> *(Expr a, Expr b) {
        <b>return</b><b>new</b> Multiply(a, b);
    }
    <b>public</b><b>static</b> Expr <b>operator</b> /(Expr a, Expr b) {
        <b>return</b><b>new</b> Divide(a, b);
    }
}</pre>
        </blockquote>
        <p>now the <code>e</code> assignment can look like,</p>
        <blockquote>
          <pre>
            <strong>var</strong> e = i1 + i1;</pre>
        </blockquote>
        <p>and finally, to make it look even better you can put the code to create the 
expression in a static method of a class that derives from <code>Expression</code> and closes the 
type parameters. Here are examples of one for <code><strong>int</strong></code> and 
a similar one for <code><strong>double</strong></code>.</p>
        <blockquote>
          <pre>
            <b>class</b> TestInt : Expression&lt;<b>int</b>, IntOperatorPolicy&gt; {
    <b>public</b><b>static</b><b>void</b> Run() {
        <strong>var</strong> iv = L(1) + L(2) * L(3);
        Console.WriteLine(iv.Evaluate());
    }
}

<b>class</b> TestDouble : Expression&lt;<b>double</b>, DoubleOperatorPolicy&gt; {
    <b>public</b><b>static</b><b>void</b> Run() {
        <strong>var</strong> dv = L(1.2) + L(3.4) * L(5.6);
        Console.WriteLine(dv.Evaluate());
    }
}</pre>
        </blockquote>
        <p>This shows taking advantage of the C# compiler's operator overloading to 
produce an expression tree and the use of the <code>L()</code> method as a sort 
of cast to change a literal of <code>T</code> into a <code>Literal&lt;T&gt;</code>. 
The call to <code>Evaluate()</code> calculates the result of the expression as 
an <code><strong>int</strong></code> or <code><strong>double</strong></code>. 
The code generated, as discussed
<a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7">
last time</a>, is quite good when JIT'ing outside the debugger and using 
optimized retail bits.</p>
        <p>This use of a policy <code><strong>struct</strong></code> is what I refer to 
as an <em>adapter policy</em>. The <code>Expression</code> class has an 
abstraction it supports, represented by <code>IOperatorPolicy&lt;T&gt;</code>, but 
this abstraction is not supported by any of the interesting types you would want 
to pass as <code>Expression</code>'s <code>T</code>. This is solved by creating 
an <em>adapter policy</em> and passing that along with <code>T</code>. This 
allows a generic type to introduce an abstraction that is unknown to the types 
the generic wants to range over, allow us, as above, to pass <code>int</code> 
for <code>Expression</code>'s <code>T</code> even though <code><strong>int</strong></code> 
doesn't implement <code>IOperatorPolicy&lt;T&gt;</code> itself.</p>
        <p>Next time I will discuss another application of an <em>adapter policy</em>.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Operators, Generics and Policies</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7</link>
      <pubDate>Wed, 25 Jul 2007 10:46:57 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;One of the limitations of C# generics is you cannot abstract over operators. 
That is not completely true, you can if the base class used in &lt;code&gt;&lt;strong&gt;where&lt;/strong&gt;&lt;/code&gt; clause has 
operators; but, since operators are more useful, and more common, on value types, 
that is only marginally helpful. Also, this abstraction is provided by the base 
class not by using generics. What I would like to do is declare that my type&amp;nbsp; 
parameter requires the type to implement a particular operator. For example, to create a generic &lt;code&gt;Add()&lt;/code&gt; 
method I would like to specify that the type parameter must implement the &lt;code&gt;
+&lt;/code&gt; operator and then be able to use the &lt;code&gt;+&lt;/code&gt; operator in my code 
such as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;span style="color: blue"&gt;&lt;em&gt;// Invalid C#&lt;/em&gt;&lt;/span&gt;
&lt;strong&gt;static&lt;/strong&gt; T Add&amp;lt;T&amp;gt;(T a, T b) &lt;strong&gt;where&lt;/strong&gt; T: T &lt;strong&gt;operator&lt;/strong&gt; +(T, T) {
    &lt;strong&gt;return&lt;/strong&gt; a + b;
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;C# doesn&amp;#39;t support this but you can get somewhat close by supplying a policy
&lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; like I described in
&lt;a href="http://www.removingalldoubt.com/commentview.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496"&gt;
this post&lt;/a&gt;. The policy &lt;code&gt;&lt;strong&gt;interface&lt;/strong&gt;&lt;/code&gt; and the &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; would 
look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;interface&lt;/b&gt; IAddPolicy&amp;lt;T&amp;gt; {
    T Add(T a, T b);
}

&lt;b&gt;struct&lt;/b&gt; IntAddPolicy : IAddPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; Add(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b; }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This allows you to write the following,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;static&lt;/b&gt; T Add&amp;lt;T, P&amp;gt;(T a, T b) &lt;strong&gt;where&lt;/strong&gt; P: &lt;b&gt;struct&lt;/b&gt;, IAddPolicy&amp;lt;T&amp;gt; {
    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; P().Add(a, b);
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Unfortunately the policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; cannot be 
inferred from the parameters so you have to supply the type parameter 
explicitly,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i = Add&amp;lt;&lt;b&gt;int&lt;/b&gt;, IntAddPolicy&amp;gt;(3, 4);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;which doesn&amp;#39;t look pretty and generates less than efficient code for the &lt;code&gt;Add()&lt;/code&gt; 
method on an i386 architecture,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;00000000  sub         esp,8 
00000003  xor         eax,eax 
00000005  mov         dword ptr [esp],eax 
00000008  mov         dword ptr [esp+4],eax 
0000000c  mov         byte ptr [esp],0 
00000010  movsx       eax,byte ptr [esp] 
00000014  mov         byte ptr [esp+4],al 
00000018  add         ecx,edx 
0000001a  mov         eax,ecx 
0000001c  add         esp,8 
0000001f  ret              &lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This generates code to initialize the policy 
structure we don&amp;#39;t actually use. We can get rid of that by recasting this a bit to save the dummy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; allocation by putting the 
&lt;code&gt;Add()&lt;/code&gt; method in a wrapping class that takes the type parameters. 
The type would allocate the &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; instead of the 
method. This looks 
like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; Adder&amp;lt;T, P&amp;gt;
    &lt;strong&gt;where&lt;/strong&gt; P: &lt;b&gt;struct&lt;/b&gt;, IAddPolicy&amp;lt;T&amp;gt;
{
    &lt;b&gt;static&lt;/b&gt; P AddPolicy = &lt;b&gt;new&lt;/b&gt; P();
    &lt;b&gt;static&lt;/b&gt; &lt;b&gt;public&lt;/b&gt; T Add(T a, T b) { &lt;b&gt;return&lt;/b&gt; AddPolicy.Add(a, b); }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;which generates the following code for &lt;code&gt;Add()&lt;/code&gt;,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;00000000  add         ecx,edx 
00000002  mov         eax,ecx 
00000004  ret              &lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This can be called like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i2 = Adder&amp;lt;&lt;b&gt;int&lt;/b&gt;, IntAddPolicy&amp;gt;.Add(3, 4);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Note that the code in &lt;code&gt;IntAddPolicy&lt;/code&gt; gets inlined into the &lt;code&gt;
Add()&lt;/code&gt; method. Even though this doesn&amp;#39;t get inlined into the caller of
&lt;code&gt;Add(),&lt;/code&gt; it will still be pretty quick with the branch prediction and 
register aliasing of modern processors. This means that you are not paying much 
(and in many cases nothing) in code quality for using an &lt;code&gt;AddPolicy&lt;/code&gt; over writing out the &lt;code&gt;
Add()&lt;/code&gt; method explicitly.&lt;/p&gt;
&lt;p&gt;To use the &lt;code&gt;Add()&lt;/code&gt; method above with another type, such as &lt;code&gt;
&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;, you need to create another 
add policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;. This would look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;struct&lt;/b&gt; DoubleAddPolicy : IAddPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Add(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b; }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Using this &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; to call &lt;code&gt;Add()&lt;/code&gt; 
will produce the following code for the &lt;code&gt;Add()&lt;/code&gt; method,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;00000000  fld         qword ptr [esp+0Ch] 
00000004  fadd        qword ptr [esp+4] 
00000008  ret         10h  &lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This is not quite as good as the code generated for &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; 
because it uses the stack to pass the parameters but it is still pretty fast.&lt;/p&gt;
&lt;p&gt;We now have a method that can add two values of any type &lt;code&gt;T&lt;/code&gt; for 
which an &lt;code&gt;AddPolicy&lt;/code&gt; can be created. This is pretty close to, and 
more general than, what I originally wanted. Unfortunately, even though the code 
generated is good, calling this code is very awkward; we have to call a static 
method of a parameterized class and the policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; 
prevents the compiler from being able to use type inferencing to supply the 
parameters for us. Next time I will describe a more practical application of 
this technique where the awkwardness is not as noticiable.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>C# Mixins - Sort of</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496</link>
      <pubDate>Mon, 02 Jul 2007 23:42:25 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I recently needed to create a set of classes that was the combinatorial 
expansion of several implementation flavors of two independent sets of methods. Why I needed 
combinatorial expansion is not that interesting but the solution is. What I came 
up with is a way of supporting a form of
&lt;a href="http://en.wikipedia.org/wiki/Mixin"&gt;mixin&lt;/a&gt;&amp;#39;s in C#.&lt;/p&gt;
&lt;p&gt;Lets take the methods,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;void&lt;/strong&gt; Lock();
&lt;strong&gt;bool&lt;/strong&gt; Unlock();
&lt;strong&gt;bool&lt;/strong&gt; Locked { &lt;strong&gt;get&lt;/strong&gt;; }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;If you call &lt;code&gt;Lock()&lt;/code&gt;, &lt;code&gt;Locked&lt;/code&gt; 
returns &lt;code&gt;&lt;strong&gt;true&lt;/strong&gt;&lt;/code&gt;, until you call &lt;code&gt;Unlock()&lt;/code&gt;. Also &lt;code&gt;Unlock()&lt;/code&gt; 
returns &lt;code&gt;&lt;strong&gt;true&lt;/strong&gt;&lt;/code&gt; if the object is now unlocked. There are several 
implementations I can think of for these methods, one uses a Boolean value and 
doesn&amp;#39;t support nested calls to &lt;code&gt;Lock()&lt;/code&gt;:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;void&lt;/strong&gt; Lock() {
  _locked = &lt;strong&gt;true&lt;/strong&gt;;
}

&lt;strong&gt;bool&lt;/strong&gt; Unlock() {
  _locked = &lt;strong&gt;false&lt;/strong&gt;;
  &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;true&lt;/strong&gt;;
}

&lt;strong&gt;bool&lt;/strong&gt; Locked {
  &lt;strong&gt;get&lt;/strong&gt; { &lt;strong&gt;return&lt;/strong&gt; _locked; }
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Another uses an integer value to count the number of nested calls to &lt;code&gt;
Lock()&lt;/code&gt; and it remains locked until a matching number of &lt;code&gt;Unlock()&lt;/code&gt; 
calls are made.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;void&lt;/strong&gt; Lock() {
  _count++;
}

&lt;strong&gt;void&lt;/strong&gt; Unlock() {
  _count--;
  &lt;strong&gt;return&lt;/strong&gt; _count == 0;
}

&lt;strong&gt;void&lt;/strong&gt; Locked() {
  &lt;strong&gt;return&lt;/strong&gt; _count &amp;gt; 0;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This isn&amp;#39;t thread safe so we could provide a relatively thread-safe version 
in,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;void&lt;/b&gt; Lock() {
    System.Threading.Interlocked.Increment(&lt;b&gt;ref&lt;/b&gt; _count);
}

&lt;b&gt;bool&lt;/b&gt; Unlock() {
    &lt;b&gt;return&lt;/b&gt; System.Threading.Interlocked.Decrement(&lt;b&gt;ref&lt;/b&gt; _count) == 0;
}

&lt;b&gt;bool&lt;/b&gt; Locked {
    get { &lt;b&gt;return&lt;/b&gt; _count &amp;gt; 0; }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;I am sure you have already thought of at least one more. Now I have four 
possible implementations (including yours), which is the correct one? Unfortunately, that depends 
on how the locking is going to be used. If I know I will never need nested 
locks, only taking space for a Boolean makes sense. If I know I will need to 
support nested locks then the &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; seems like a 
good choice. If it is going to be used in a multi-threaded application I should 
probably use the thread-safe version. I now have two choices, pick one 
implementation or pass it the implementation as a parameter. Picking one 
implementation is easy, just copy of of the above implementation into the class; but how do you efficiently pass an implementation as a 
parameter? &lt;/p&gt;
&lt;p&gt;From now on I will refer to each implementation as a locking policy. What I 
want is an efficient way to pass the locking policy to a set of classes. Most obvious way is to 
write a class for each policy and pass the policy 
as a parameter to each instance. This might look something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;class&lt;/strong&gt; LockingPolicy {
  &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;void&lt;/strong&gt; Lock();
  &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Unlock();
  &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Locked { &lt;strong&gt;get&lt;/strong&gt;; }
}

&lt;strong&gt;class&lt;/strong&gt; LockableObject {
    &lt;strong&gt;private&lt;/strong&gt; LockingPolicy _lockingPolicy;
  
    &lt;strong&gt;public&lt;/strong&gt; LockableObject(LockingPolicy lockingPolicy) {
        _lockingPolicy = lockingPolicy;
    }
  
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Lock() {
        _lockingPolicy.Lock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Unlock() {
        &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Unlock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Locked {
        get { &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Locked; }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;Unfortunately, this has, on average, 36 bytes of overhead per instance on 
a 32 bit machine (more on 64).&amp;nbsp; This seems a bit much for such a policy and picking just one 
implementation, even one too general for the average application, starts 
looking like a better alternative. We must be able to do better than this.&lt;/p&gt;
&lt;p&gt;Since passing the implementation as a parameter to the instances is 
expensive, why not try to pass the implementation to the class instead? In order 
to do that we need use a type parameter. What we want is something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; LockableObject&amp;lt;LockingPolicy&amp;gt; {
    &lt;b&gt;private&lt;/b&gt; LockingPolicy _lockingPolicy = &lt;b&gt;new&lt;/b&gt; LockingPolicy();

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Lock() {
        _lockingPolicy.Lock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Unlock() {
        &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Unlock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Locked {
        get { &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Locked; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;In other words, we need to passing a &lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt; and delegate the implementation to 
that &lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt;. This does not look significantly better than the previous 
implementation, however, because we are new&amp;#39;ing up an instance and assigning it 
to an instance variable which, as before, consumes a minimum of 36 bytes per 
instance. But if &lt;code&gt;LockingPolicy&lt;/code&gt; is a &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; instead 
of a &lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt; then it will only add the size of the
&lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; to the &lt;code&gt;LockableObject&lt;/code&gt; instance 
size. In other words, we would only be taking space for either a &lt;code&gt;&lt;strong&gt;bool&lt;/strong&gt;&lt;/code&gt; 
or an &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt;. The size overhead looks good, now how 
about the delegation? In order to call methods on &lt;code&gt;LockingPolicy&lt;/code&gt; the
&lt;code&gt;LockingPolicy&lt;/code&gt; &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; must implement 
an interface. It cannot be an &lt;code&gt;&lt;strong&gt;abstract&lt;/strong&gt;&lt;/code&gt;
&lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt; because all &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;s 
are sealed and cannot be inherited from. The interface for the locking policy is fairly straight 
forward and looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;interface&lt;/b&gt; ILockingPolicy {
    &lt;b&gt;void&lt;/b&gt; Lock();
    &lt;b&gt;bool&lt;/b&gt; Unlock();
    &lt;b&gt;bool&lt;/b&gt; Locked { get; }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;An implementation of the Boolean locking policy looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;struct&lt;/b&gt; SimpleLockPolicy : ILockingPolicy {
    &lt;b&gt;bool&lt;/b&gt; _locked;

    &lt;b&gt;void&lt;/b&gt; ILockingPolicy.Lock() {
        _locked = &lt;b&gt;true&lt;/b&gt;;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Unlock() {
        _locked = &lt;b&gt;false&lt;/b&gt;;
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;false&lt;/b&gt;;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Locked {
        get { &lt;b&gt;return&lt;/b&gt; _locked; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The counted locking policy looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;struct&lt;/b&gt; CountedLockPolicy : ILockingPolicy {
    &lt;b&gt;private&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; _count;
    &lt;b&gt;void&lt;/b&gt; ILockingPolicy.Lock() {
        _count++;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Unlock() {
        _count--;
        &lt;b&gt;return&lt;/b&gt; _count == 0;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Locked {
        get { &lt;b&gt;return&lt;/b&gt; _count &amp;gt; 0; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;We now need to add a &lt;code&gt;&lt;strong&gt;where&lt;/strong&gt;&lt;/code&gt; clause to the &lt;code&gt;LockableObject&lt;/code&gt; 
class so we can call the methods provided by the &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;&amp;#39;s methods. The modified &lt;code&gt;LockableObject&lt;/code&gt; 
class looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; LockableObject&amp;lt;LockingPolicy&amp;gt;
    &lt;strong&gt;where&lt;/strong&gt; LockingPolicy : &lt;b&gt;struct&lt;/b&gt;, ILockingPolicy 
{
    &lt;b&gt;private&lt;/b&gt; LockingPolicy _lockingPolicy = &lt;b&gt;new&lt;/b&gt; LockingPolicy();

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Lock() {
        _lockingPolicy.Lock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Unlock() {
        &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Unlock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Locked {
        get { &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Locked; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The &lt;code&gt;LockableObject&lt;/code&gt; can now be instantiated like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; lockableObject = &lt;b&gt;new&lt;/b&gt; LockableObject&amp;lt;SimpleLockPolicy&amp;gt;();&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;for a lockable object that uses the Boolean implementation. To use the 
counted locking policy you would construct the object like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; lockableObject = &lt;b&gt;new&lt;/b&gt; LockableObject&amp;lt;CountedLockPolicy&amp;gt;();&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;The space consumption looks good but the delegation looks expensive it call 
through an interface which is a virtual. But since we are using &lt;code&gt;&lt;strong&gt;
struct&lt;/strong&gt;&lt;/code&gt;s, which are &lt;code&gt;&lt;strong&gt;sealed&lt;/strong&gt;&lt;/code&gt;, the 
call through the &lt;code&gt;&lt;strong&gt;interface&lt;/strong&gt;&lt;/code&gt; can be made static
and then be a candidate for inlining. In fact, 
this is what happens in retail builds when not debugging. This is not entirely 
free however since there the runtime doesn&amp;#39;t inline twice. Implementing &lt;code&gt;
Lock()&lt;/code&gt; directly instead of through delegation means the &lt;code&gt;Lock()&lt;/code&gt; 
method can be inlined, removing the call entirely, the delegated version inlines 
the delegation but it still generates a call.&lt;/p&gt;
&lt;p&gt;This mechanism for C# mixins is not as convenient as languages that support 
multiple inheritance, because we have to manually delegate to the policy, but it 
is just as efficient as we will see demonstrated more clearly in some of the 
next entries.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Keyed Binary Search</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/f7e6feff-8257-4efe-ad64-acd1c7a4a1e3</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/f7e6feff-8257-4efe-ad64-acd1c7a4a1e3</link>
      <pubDate>Thu, 24 May 2007 16:44:43 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;One thing that has always frustrated me about typical binary search routines 
found in libraries is they always assume you can easily produce a copy of the 
item you are searching for. What I mean is they typically follow this pattern,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; BinarySearch&amp;lt;T&amp;gt;(IList&amp;lt;T&amp;gt; list, T item);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;which takes a list of some type, left open here, and searches for it in the 
list. This is great if the very next thing you do next is insert &lt;code&gt;item&lt;/code&gt; into 
the list. You already have &lt;code&gt;item&lt;/code&gt; in hand so this signature is 
perfect. But if you 
don&amp;#39;t have a ready &lt;code&gt;item&lt;/code&gt;, and &lt;code&gt;item&lt;/code&gt; is difficult to 
produce, you are stuck. &lt;/p&gt;
&lt;p&gt;This happened to me just recently in my code. I had a 
sorted list of a data structure representing a span of source, similar to a &lt;code&gt;TextPointer&lt;/code&gt; from WPF, called a 
&lt;code&gt;TextRange&lt;/code&gt;. My version can quickly return the 
offset of the beginning of the span but, since &lt;code&gt;TextRange&lt;/code&gt; tracks source changes, 
creating a new &lt;code&gt;TextRange&lt;/code&gt; is expensive. When text in the editor is 
change, I receive the location of 
the change in an event. How do I figure out which one of my &lt;code&gt;TextRange&lt;/code&gt;s was modified? Since 
the list is sorted, the obvious choice is to use a binary search which yields O(Log N) 
performance. Since my &lt;code&gt;TextRange&lt;/code&gt;s are store in a &lt;code&gt;List&amp;lt;TextRange&amp;gt;&lt;/code&gt;, 
obviously I should 
call &lt;code&gt;List&amp;lt;T&amp;gt;.BinarySearch()&lt;/code&gt;. Unfortunately, &lt;code&gt;TextRange&lt;/code&gt;s are expensive to produce; 
too expensive for a per-keystroke operation (I am glossing over some details for 
the sake of brevity; you need to trust me this is true). I have one of two choices, write my 
own &lt;code&gt;BinarySearch()&lt;/code&gt; or create a fake &lt;code&gt;TextRange&lt;/code&gt; that is a special 
&lt;code&gt;TextRange&lt;/code&gt; that 
is less expensive to create and only used for searching. Neither choice is 
pleasant. Hand-rolled binary searches are not hard to right but, for some 
strange reason, I always get them wrong the first time.&lt;/p&gt;
&lt;p&gt;What I needed is prebuilt and tested version of &lt;code&gt;BinarySearch()&lt;/code&gt; that looks more like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; BinarySearch&amp;lt;T, K&amp;gt;(IList&amp;lt;T&amp;gt; list, K key, Converter&amp;lt;T, K&amp;gt; converter);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;What this binary search routine does is find some key value in the list 
given a function that can convert any list item into the key. In my example, I 
would call it like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; location = BinarySearch(textRangeList, location, TextRangeToLocation);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;where &lt;code&gt;TextRangeToLocation&lt;/code&gt; looks something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; TextRangeToLocation(TextRange range) { &lt;strong&gt;return&lt;/strong&gt; range.Location; }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;I don&amp;#39;t need to produce a &lt;code&gt;TextRange&lt;/code&gt;. I have the location I am looking for 
handy, I just need to know what, if any, &lt;code&gt;TextRange&lt;/code&gt; contains the 
location. This method 
would do just that. You can even use a lambda function in C# 3.0 to get this 
all on one line,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; location = BinarySearch(textRangeList, location, (n) =&amp;gt; n.Location);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This is starting to look like a good idea. Let&amp;#39;s code it up. Here is the 
method I ended up with,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(IList&amp;lt;T&amp;gt; list, K value, 
    Converter&amp;lt;T, K&amp;gt; convert, Comparison&amp;lt;K&amp;gt; compare) {
    &lt;b&gt;int&lt;/b&gt; i = 0;
    &lt;b&gt;int&lt;/b&gt; j = list.Count - 1;
    &lt;b&gt;while&lt;/b&gt; (i &amp;lt;= j) {
        &lt;b&gt;int&lt;/b&gt; m = i + (j - i) / 2;
        &lt;b&gt;int&lt;/b&gt; c = compare(convert(list[m]), value);
        &lt;b&gt;if&lt;/b&gt; (c == 0)
            &lt;b&gt;return&lt;/b&gt; m;
        &lt;b&gt;if&lt;/b&gt; (c &amp;lt; 0)
            i = m + 1;
        &lt;b&gt;else&lt;/b&gt;
            j = m - 1;
    }
    &lt;b&gt;return&lt;/b&gt; ~i;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;I added an extra parameter, &lt;code&gt;compare&lt;/code&gt;. This is required because I 
didn&amp;#39;t put any limits on what &lt;code&gt;K&lt;/code&gt; can be and I need a way to compare 
one &lt;code&gt;K&lt;/code&gt; with another. Many types, such as &lt;code&gt;int&lt;/code&gt;, already know how to 
compare values of their own type. Typically types that are comparable, such as
&lt;code&gt;int&lt;/code&gt;,&lt;code&gt; string&lt;/code&gt;, etc., implement
&lt;code&gt;IComparable&amp;lt;T&amp;gt;&lt;/code&gt;. We can accommodate such types by creating an 
overloaded version of &lt;code&gt;BinarySearch()&lt;/code&gt; that looks like, &lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(IList&amp;lt;T&amp;gt; list, K value, 
    Converter&amp;lt;T, K&amp;gt; convert) &lt;strong&gt;where&lt;/strong&gt; K : IComparable&amp;lt;K&amp;gt; {
    &lt;b&gt;return&lt;/b&gt; list.BinarySearch(value, convert, (n, m) =&amp;gt; n.CompareTo(m));
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;which uses a lambda function to create a &lt;code&gt;Comparison&amp;lt;T&amp;gt;&lt;/code&gt;  for any 
type that supports &lt;code&gt;IComparable&amp;lt;T&amp;gt;&lt;/code&gt;. Beware that this doesn&amp;#39;t 
work well with reference types because it doesn&amp;#39;t check for &lt;strong&gt;&lt;code&gt;null&lt;/code&gt;&lt;/strong&gt;. 
You can make it safer by putting &lt;strong&gt;&lt;code&gt;struct&lt;/code&gt;&lt;/strong&gt; in the
&lt;strong&gt;&lt;code&gt;where&lt;/code&gt;&lt;/strong&gt; clause but that seemed overly restrictive to 
me.&lt;/p&gt;
&lt;p&gt;Now that I have a &lt;code&gt;BinarySearch()&lt;/code&gt; that meets my needs better than the built-in
&lt;code&gt;BinarySearch()&lt;/code&gt;, my next thought was I should evangelize the benefits my version 
of &lt;code&gt;BinarySearch()&lt;/code&gt; to the team responsible for maintaining the CLR 
collections and, maybe, someday, I will have it as 
a native part of the CLR; maybe, someday. Then I remember extensions methods. In 
C# 3.0, with a slight modification to the above methods, they can appear as if 
they were already part of the CLR.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; ListExtensionMethods {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list, K value,
        Converter&amp;lt;T, K&amp;gt; convert, Comparison&amp;lt;K&amp;gt; compare) {
        &lt;b&gt;int&lt;/b&gt; i = 0;
        &lt;b&gt;int&lt;/b&gt; j = list.Count - 1;
        &lt;b&gt;while&lt;/b&gt; (i &amp;lt;= j) {
            &lt;b&gt;int&lt;/b&gt; m = i + (j - i) / 2;
            &lt;b&gt;int&lt;/b&gt; c = compare(convert(list[m]), value);
            &lt;b&gt;if&lt;/b&gt; (c == 0)
                &lt;b&gt;return&lt;/b&gt; m;
            &lt;b&gt;if&lt;/b&gt; (c &amp;lt; 0)
                i = m + 1;
            &lt;b&gt;else&lt;/b&gt;
                j = m - 1;
        }
        &lt;b&gt;return&lt;/b&gt; ~i;
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list, K value, 
        Converter&amp;lt;T, K&amp;gt; convert) where K : IComparable&amp;lt;K&amp;gt; {
        &lt;b&gt;return&lt;/b&gt; list.BinarySearch(value, convert, (n, m) =&amp;gt; n.CompareTo(m));
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;My version of &lt;code&gt;BinarySearch()&lt;/code&gt; now 
appears as part of the methods of any type that implements &lt;code&gt;IList&amp;lt;T&amp;gt;&lt;/code&gt;. 
This allows us to write,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; location = textRangeList.BinarySearch(location, (n) =&amp;gt; n.Location);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;just like it was a native part of the CLR. No more hand-rolled &lt;code&gt;
BinarySearch()&lt;/code&gt;s!&lt;/p&gt;
&lt;p&gt;Now that we have a &lt;code&gt;ListExtensionMethods &lt;/code&gt;class, what other missing methods 
could we add? Here are a few that I thought would be useful,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Sort&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; List&amp;lt;T&amp;gt; list, 
    Converter&amp;lt;T, K&amp;gt; coverter, Comparison&amp;lt;K&amp;gt; compare) {
    list.Sort((n, m) =&amp;gt; compare(convert(n), convert(m)));
}

&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Sort&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; List&amp;lt;T&amp;gt; list, 
    Converter&amp;lt;T, K&amp;gt;  converter) &lt;b&gt;where&lt;/b&gt; K : IComparable&amp;lt;K&amp;gt; {
    list.Sort((n, m) =&amp;gt; convert(n).CompareTo(convert(m)));
}

&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Swap&amp;lt;T&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list, &lt;b&gt;int&lt;/b&gt; index1, 
    &lt;b&gt;int&lt;/b&gt; index2) {
    var value = list[index1];
    list[index1] = list[index2];
    list[index2] = value;
}

&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Shuffle&amp;lt;T&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list) {
    &lt;b&gt;int&lt;/b&gt; count = list.Count;
    Random r = &lt;b&gt;new&lt;/b&gt; Random();
    &lt;b&gt;for&lt;/b&gt;(&lt;b&gt;int&lt;/b&gt; i = count - 1; i &amp;gt; 1; i--)
        list.Swap(i, r.Next(i - 1));
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The &lt;code&gt;Sort()&lt;/code&gt; methods above are allow you to extract a key for 
sorting using the same methods as above. These are not strictly necessary since 
constructing the lambda function I use is not that complicated but I believe they 
make the code more readable if you are consistent in how you extract keys from a 
list, so these are convenient wrappers that allow you to use the same methods to 
sort and search. &lt;code&gt;Swap()&lt;/code&gt; and
&lt;code&gt;Shuffle()&lt;/code&gt; are throw-ins. They are really only useful for demo code 
or, in my case, test code. I used them to test the &lt;code&gt;Sort()&lt;/code&gt; method 
which I used to test the &lt;code&gt;BinarySearch()&lt;/code&gt; method.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>One thing that has always frustrated me about typical binary search routines 
found in libraries is they always assume you can easily produce a copy of the 
item you are searching for. What I mean is they typically follow this pattern,</p>
        <blockquote>
          <pre>
            <strong>int</strong> BinarySearch&lt;T&gt;(IList&lt;T&gt; list, T item);</pre>
        </blockquote>
        <p>which takes a list of some type, left open here, and searches for it in the 
list. This is great if the very next thing you do next is insert <code>item</code> into 
the list. You already have <code>item</code> in hand so this signature is 
perfect. But if you 
don't have a ready <code>item</code>, and <code>item</code> is difficult to 
produce, you are stuck. </p>
        <p>This happened to me just recently in my code. I had a 
sorted list of a data structure representing a span of source, similar to a <code>TextPointer</code> from WPF, called a 
<code>TextRange</code>. My version can quickly return the 
offset of the beginning of the span but, since <code>TextRange</code> tracks source changes, 
creating a new <code>TextRange</code> is expensive. When text in the editor is 
change, I receive the location of 
the change in an event. How do I figure out which one of my <code>TextRange</code>s was modified? Since 
the list is sorted, the obvious choice is to use a binary search which yields O(Log N) 
performance. Since my <code>TextRange</code>s are store in a <code>List&lt;TextRange&gt;</code>, 
obviously I should 
call <code>List&lt;T&gt;.BinarySearch()</code>. Unfortunately, <code>TextRange</code>s are expensive to produce; 
too expensive for a per-keystroke operation (I am glossing over some details for 
the sake of brevity; you need to trust me this is true). I have one of two choices, write my 
own <code>BinarySearch()</code> or create a fake <code>TextRange</code> that is a special 
<code>TextRange</code> that 
is less expensive to create and only used for searching. Neither choice is 
pleasant. Hand-rolled binary searches are not hard to right but, for some 
strange reason, I always get them wrong the first time.</p>
        <p>What I needed is prebuilt and tested version of <code>BinarySearch()</code> that looks more like,</p>
        <blockquote>
          <pre>
            <strong>int</strong> BinarySearch&lt;T, K&gt;(IList&lt;T&gt; list, K key, Converter&lt;T, K&gt; converter);</pre>
        </blockquote>
        <p>What this binary search routine does is find some key value in the list 
given a function that can convert any list item into the key. In my example, I 
would call it like,</p>
        <blockquote>
          <pre>
            <strong>int</strong> location = BinarySearch(textRangeList, location, TextRangeToLocation);</pre>
        </blockquote>
        <p>where <code>TextRangeToLocation</code> looks something like,</p>
        <blockquote>
          <pre>
            <strong>int</strong> TextRangeToLocation(TextRange range) { <strong>return</strong> range.Location; }</pre>
        </blockquote>
        <p>I don't need to produce a <code>TextRange</code>. I have the location I am looking for 
handy, I just need to know what, if any, <code>TextRange</code> contains the 
location. This method 
would do just that. You can even use a lambda function in C# 3.0 to get this 
all on one line,</p>
        <blockquote>
          <pre>
            <strong>int</strong> location = BinarySearch(textRangeList, location, (n) =&gt; n.Location);</pre>
        </blockquote>
        <p>This is starting to look like a good idea. Let's code it up. Here is the 
method I ended up with,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>int</b> BinarySearch&lt;T, K&gt;(IList&lt;T&gt; list, K value, 
    Converter&lt;T, K&gt; convert, Comparison&lt;K&gt; compare) {
    <b>int</b> i = 0;
    <b>int</b> j = list.Count - 1;
    <b>while</b> (i &lt;= j) {
        <b>int</b> m = i + (j - i) / 2;
        <b>int</b> c = compare(convert(list[m]), value);
        <b>if</b> (c == 0)
            <b>return</b> m;
        <b>if</b> (c &lt; 0)
            i = m + 1;
        <b>else</b>
            j = m - 1;
    }
    <b>return</b> ~i;
}</pre>
        </blockquote>
        <p>I added an extra parameter, <code>compare</code>. This is required because I 
didn't put any limits on what <code>K</code> can be and I need a way to compare 
one <code>K</code> with another. Many types, such as <code>int</code>, already know how to 
compare values of their own type. Typically types that are comparable, such as
<code>int</code>,<code> string</code>, etc., implement
<code>IComparable&lt;T&gt;</code>. We can accommodate such types by creating an 
overloaded version of <code>BinarySearch()</code> that looks like, </p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>int</b> BinarySearch&lt;T, K&gt;(IList&lt;T&gt; list, K value, 
    Converter&lt;T, K&gt; convert) <strong>where</strong> K : IComparable&lt;K&gt; {
    <b>return</b> list.BinarySearch(value, convert, (n, m) =&gt; n.CompareTo(m));
}</pre>
        </blockquote>
        <p>which uses a lambda function to create a <code>Comparison&lt;T&gt;</code>  for any 
type that supports <code>IComparable&lt;T&gt;</code>. Beware that this doesn't 
work well with reference types because it doesn't check for <strong><code>null</code></strong>. 
You can make it safer by putting <strong><code>struct</code></strong> in the
<strong><code>where</code></strong> clause but that seemed overly restrictive to 
me.</p>
        <p>Now that I have a <code>BinarySearch()</code> that meets my needs better than the built-in
<code>BinarySearch()</code>, my next thought was I should evangelize the benefits my version 
of <code>BinarySearch()</code> to the team responsible for maintaining the CLR 
collections and, maybe, someday, I will have it as 
a native part of the CLR; maybe, someday. Then I remember extensions methods. In 
C# 3.0, with a slight modification to the above methods, they can appear as if 
they were already part of the CLR.</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>class</b> ListExtensionMethods {
    <b>public</b><b>static</b><b>int</b> BinarySearch&lt;T, K&gt;(<b>this</b> IList&lt;T&gt; list, K value,
        Converter&lt;T, K&gt; convert, Comparison&lt;K&gt; compare) {
        <b>int</b> i = 0;
        <b>int</b> j = list.Count - 1;
        <b>while</b> (i &lt;= j) {
            <b>int</b> m = i + (j - i) / 2;
            <b>int</b> c = compare(convert(list[m]), value);
            <b>if</b> (c == 0)
                <b>return</b> m;
            <b>if</b> (c &lt; 0)
                i = m + 1;
            <b>else</b>
                j = m - 1;
        }
        <b>return</b> ~i;
    }

    <b>public</b><b>static</b><b>int</b> BinarySearch&lt;T, K&gt;(<b>this</b> IList&lt;T&gt; list, K value, 
        Converter&lt;T, K&gt; convert) where K : IComparable&lt;K&gt; {
        <b>return</b> list.BinarySearch(value, convert, (n, m) =&gt; n.CompareTo(m));
    }
}</pre>
        </blockquote>
        <p>My version of <code>BinarySearch()</code> now 
appears as part of the methods of any type that implements <code>IList&lt;T&gt;</code>. 
This allows us to write,</p>
        <blockquote>
          <pre>
            <strong>int</strong> location = textRangeList.BinarySearch(location, (n) =&gt; n.Location);</pre>
        </blockquote>
        <p>just like it was a native part of the CLR. No more hand-rolled <code>
BinarySearch()</code>s!</p>
        <p>Now that we have a <code>ListExtensionMethods </code>class, what other missing methods 
could we add? Here are a few that I thought would be useful,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>void</b> Sort&lt;T, K&gt;(<b>this</b> List&lt;T&gt; list, 
    Converter&lt;T, K&gt; coverter, Comparison&lt;K&gt; compare) {
    list.Sort((n, m) =&gt; compare(convert(n), convert(m)));
}

<b>public</b><b>static</b><b>void</b> Sort&lt;T, K&gt;(<b>this</b> List&lt;T&gt; list, 
    Converter&lt;T, K&gt;  converter) <b>where</b> K : IComparable&lt;K&gt; {
    list.Sort((n, m) =&gt; convert(n).CompareTo(convert(m)));
}

<b>public</b><b>static</b><b>void</b> Swap&lt;T&gt;(<b>this</b> IList&lt;T&gt; list, <b>int</b> index1, 
    <b>int</b> index2) {
    var value = list[index1];
    list[index1] = list[index2];
    list[index2] = value;
}

<b>public</b><b>static</b><b>void</b> Shuffle&lt;T&gt;(<b>this</b> IList&lt;T&gt; list) {
    <b>int</b> count = list.Count;
    Random r = <b>new</b> Random();
    <b>for</b>(<b>int</b> i = count - 1; i &gt; 1; i--)
        list.Swap(i, r.Next(i - 1));
}</pre>
        </blockquote>
        <p>The <code>Sort()</code> methods above are allow you to extract a key for 
sorting using the same methods as above. These are not strictly necessary since 
constructing the lambda function I use is not that complicated but I believe they 
make the code more readable if you are consistent in how you extract keys from a 
list, so these are convenient wrappers that allow you to use the same methods to 
sort and search. <code>Swap()</code> and
<code>Shuffle()</code> are throw-ins. They are really only useful for demo code 
or, in my case, test code. I used them to test the <code>Sort()</code> method 
which I used to test the <code>BinarySearch()</code> method.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/f7e6feff-8257-4efe-ad64-acd1c7a4a1e3</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Pick a License</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/a5c0a12b-a05e-45e7-b2a7-3c389a2f4302</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/a5c0a12b-a05e-45e7-b2a7-3c389a2f4302</link>
      <pubDate>Wed, 04 Apr 2007 10:11:03 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Reading &lt;a href="http://www.codinghorror.com/blog/archives/000833.html"&gt;Pick 
a License, Any License&lt;/a&gt; by Jeff Atwood inspired me to pick one for the code I 
post on this blog. I picked
&lt;a href="http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx"&gt;
Ms-PL&lt;/a&gt;. I certainly intended people to use the code I post, this make that 
intent more clear. I have modified the my copyright footer to reflect this 
selection.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Reading <a href="http://www.codinghorror.com/blog/archives/000833.html">Pick 
a License, Any License</a> by Jeff Atwood inspired me to pick one for the code I 
post on this blog. I picked
<a href="http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx">
Ms-PL</a>. I certainly intended people to use the code I post, this make that 
intent more clear. I have modified the my copyright footer to reflect this 
selection.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/a5c0a12b-a05e-45e7-b2a7-3c389a2f4302</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>PolyDictionary IV: By extension</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/3f5c7a8d-2574-43b5-aafc-acfc3cd66b7c</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/3f5c7a8d-2574-43b5-aafc-acfc3cd66b7c</link>
      <pubDate>Sat, 31 Mar 2007 23:06:29 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;The technique we used to build &lt;code&gt;PolyDictionary&lt;/code&gt; can be used in other 
places. For example, you can adapt a non-type-checked store to a 
type-checked store by supplying your own &lt;code&gt;Get() &lt;/code&gt;and &lt;code&gt;Set()&lt;/code&gt; 
methods. One place this might be useful is when you encounter something like 
CodeDom&amp;#39;s &lt;code&gt;UserData&lt;/code&gt;. It is intended to allow users or producers 
of a CodeDom to annotate a 
CodeDom with their own information. Because it uses &lt;code&gt;IDictionary,&lt;/code&gt; 
using &lt;code&gt;UserData&lt;/code&gt; is not type checked at compile 
time. You can introduce type checking by using your own methods to access the 
dictionary like,&lt;/p&gt;
&lt;pre&gt;  &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; T Get&amp;lt;T&amp;gt;(IDictionary dictionary, Key&amp;lt;T&amp;gt; key) {
      &lt;b&gt;return&lt;/b&gt; (T)dictionary[key];
  }

  &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Set&amp;lt;T&amp;gt;(IDictionary dictionary, Key&amp;lt;T&amp;gt; key, T value) {
      dictionary[key] = value;
  }&lt;/pre&gt;
&lt;p&gt;which uses the &lt;code&gt;Key&amp;lt;T&amp;gt;&lt;/code&gt; class from last time. This allows 
the compiler to ensure that the type of the value you get out is the same as you 
put in and vise versa.&lt;/p&gt;
&lt;p&gt;With C# 3.0, however, you can get even more creative. You can create extension 
methods for &lt;code&gt;IDictionary&lt;/code&gt; that makes it appear that all &lt;code&gt;IDictionary&lt;/code&gt;s have a type 
checked &lt;code&gt;Get()&lt;/code&gt; and &lt;code&gt;Set()&lt;/code&gt; like,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;static&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; IDictionaryExtensions {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; T Get&amp;lt;T&amp;gt;(&lt;b&gt;this&lt;/b&gt; IDictionary dictionary, Key&amp;lt;T&amp;gt; key) {
            &lt;b&gt;return&lt;/b&gt; (T)dictionary[key];
        }
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Set&amp;lt;T&amp;gt;(&lt;b&gt;this&lt;/b&gt; IDictionary dictionary, Key&amp;lt;T&amp;gt; key, T value) {
            dictionary[key] = value;
        }
    }&lt;/pre&gt;
&lt;p&gt;This allows you to write code like,&lt;/p&gt;
&lt;pre&gt;    Key&amp;lt;&lt;b&gt;string&lt;/b&gt;&amp;gt; k1 = &lt;b&gt;new&lt;/b&gt; Key&amp;lt;&lt;b&gt;string&lt;/b&gt;&amp;gt;();
    Key&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt; k2 = &lt;b&gt;new&lt;/b&gt; Key&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;();
    Key&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt; k3 = &lt;b&gt;new&lt;/b&gt; Key&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;();

    IDictionary dictionary = &lt;b&gt;new&lt;/b&gt; Hashtable();

    dictionary.Set(k1, "one");
    dictionary.Set(k2, 2);
    dictionary.Set(k3, 3.33);

    &lt;b&gt;string&lt;/b&gt; v1 = dictionary.Get(k1);
    &lt;b&gt;int&lt;/b&gt; v2 = dictionary.Get(k2);
    &lt;b&gt;double&lt;/b&gt; v3 = dictionary.Get(k3);

    Console.WriteLine("v1 = {0}", v1);
    Console.WriteLine("v2 = {0}", v2);
    Console.WriteLine("v3 = {0}", v3);&lt;/pre&gt;
&lt;p&gt;which allows us to use an &lt;code&gt;IDictionary&lt;/code&gt; almost identically to a
&lt;code&gt;PolyDictionary&lt;/code&gt;.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This works great for &lt;code&gt;Get()&lt;/code&gt; and &lt;code&gt;Set()&lt;/code&gt; but this 
doesn&amp;#39;t work for &lt;code&gt;Add()&lt;/code&gt;, unfortunately. 
The compiler accepts it but it doesn&amp;#39;t do what we want. If we use a value 
of an incorrect type for a particular key we want the compiler to generate and 
error. In other words, if we change the &lt;code&gt;Set()&lt;/code&gt; call for &lt;code&gt;k1&lt;/code&gt; above to,&lt;/p&gt;
&lt;pre&gt;  dictionary.&lt;span style="background-color:#FFFF00"&gt;Add&lt;/span&gt;(k1, &lt;span style="background-color:#FFFF00"&gt;1&lt;/span&gt;);&lt;/pre&gt;
&lt;p&gt;we want the compiler to generate an error. This doesn&amp;#39;t happen because of method overloading. The object version of
Add,
&lt;code&gt;Add(&lt;strong&gt;object&lt;/strong&gt; value)&lt;/code&gt; is called if the type is incorrect; this is not what we want. 
We could add an &lt;code&gt;AddSafe()&lt;/code&gt; method to the extension class but then we 
would have to remember to call it instead of &lt;code&gt;Add()&lt;/code&gt;, which defeats 
the purpose in my opinion.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/3f5c7a8d-2574-43b5-aafc-acfc3cd66b7c</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>PolyDictionary III: Cast away</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/d378c798-718d-4fab-b42c-f14da5edb6de</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/d378c798-718d-4fab-b42c-f14da5edb6de</link>
      <pubDate>Mon, 26 Mar 2007 19:02:56 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;The astute among you realized right away that &lt;code&gt;PolyDictionary&lt;/code&gt; 
does not really avoid a cast, it just hides it. The &lt;code&gt;TryGetValue()&lt;/code&gt; 
has a cast in it, highlighted below,&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; TryGetValue&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key, &lt;b&gt;out&lt;/b&gt; V value) {
            &lt;b&gt;object&lt;/b&gt; objValue;
            &lt;b&gt;if&lt;/b&gt; (_table.TryGetValue(key, &lt;b&gt;out&lt;/b&gt; objValue)) {
                value = &lt;span style="background-color:#FFFF00"&gt;(V)objValue&lt;/span&gt;;
                &lt;b&gt;return&lt;/b&gt; &lt;b&gt;true&lt;/b&gt;;
            }
            value = &lt;b&gt;default&lt;/b&gt;(V);
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;false&lt;/b&gt;;
        }&lt;/pre&gt;
&lt;p&gt;So, can we get rid of the this cast? Yes, but the results are not very 
pleasant. One approach is to create one dictionary for each unique value type 
and then find that dictionary by that type and index into it using the key, 
instead of storing all the values in the same dictionary. This sounds similar to the 
original problem! All we need is a &lt;code&gt;PolyDictionary&lt;/code&gt; that maps &lt;code&gt;
T&lt;/code&gt; to &lt;code&gt;Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt;&lt;/code&gt;. We could code this but we 
couldn&amp;#39;t run it because we would be defining &lt;code&gt;PolyDictionary&lt;/code&gt; in 
terms of itself, consuming all of memory in the process. We need something like &lt;code&gt;
PolyDictionary&lt;/code&gt; but isn&amp;#39;t a &lt;code&gt;PolyDictionary&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;OK, things will now get ugly. Have your barf bags on the stand-by! And, for 
the love of God, don&amp;#39;t ever put this in a production application! &lt;/p&gt;
&lt;p&gt;Now that is off my chest, here is one technique to avoid the cast. You can 
create a nested class &lt;code&gt;SubDictionary&lt;/code&gt; that has a static instance 
variable which maps &lt;code&gt;PolyDictionaries&lt;/code&gt; to &lt;code&gt;Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt;&lt;/code&gt;. 
We can then parameterize &lt;code&gt;SubDictionary&lt;/code&gt; by &lt;code&gt;T&lt;/code&gt; which will 
create a unique dictionary for each &lt;code&gt;T&lt;/code&gt; (I warned you it was ugly). 
This is because the CLR treats every instantiation of &lt;code&gt;SubDictionary&amp;lt;T&amp;gt;&lt;/code&gt; as a 
unique type with unique static variables. Essentially we are tricking the CLR 
into producing a dictionary of &lt;code&gt;T&lt;/code&gt; to &lt;code&gt;Dictionary&amp;lt;PolyDictionary,Dictionary&amp;lt;Key&amp;lt;T&amp;gt;,T&amp;gt;&amp;gt;&lt;/code&gt;. 
Since the variable is static we need to find the version that is for the 
instance we are using, hence the key of &lt;code&gt;PolyDictionary&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Here is the example,&lt;/p&gt;
&lt;pre&gt;    /* Never, Never use this code! */
    &lt;b&gt;class&lt;/b&gt; PolyDictionary {
        
        &lt;b&gt;class&lt;/b&gt; SubDictionaries&amp;lt;T&amp;gt; {
            &lt;b&gt;internal&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Dictionary&amp;lt;PolyDictionary, Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt;&amp;gt; Dictionaries = 
                &lt;b&gt;new&lt;/b&gt; Dictionary&amp;lt;PolyDictionary,Dictionary&amp;lt;Key&amp;lt;T&amp;gt;,T&amp;gt;&amp;gt;();
        }

        &lt;b&gt;public&lt;/b&gt; PolyDictionary() { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, T value) {
            Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt; subDictionary = GetDictionary(key);
            subDictionary.Add(key, value);
        }

        &lt;b&gt;public&lt;/b&gt; T Get&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt; subDictionary = FindDictionary(key);
            &lt;b&gt;if&lt;/b&gt; (subDictionary != &lt;b&gt;null&lt;/b&gt;)
                &lt;b&gt;return&lt;/b&gt; subDictionary[key];
            &lt;b&gt;throw&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; KeyNotFoundException();
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; TryGetValue&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, &lt;b&gt;out&lt;/b&gt; T value) {
            Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt; subDictionary = FindDictionary(key);
            &lt;b&gt;if&lt;/b&gt; (subDictionary != &lt;b&gt;null&lt;/b&gt;)
                &lt;b&gt;return&lt;/b&gt; subDictionary.TryGetValue(key, &lt;b&gt;out&lt;/b&gt; value);
            &lt;b&gt;else&lt;/b&gt; {
                value = &lt;b&gt;default&lt;/b&gt;(T);
                &lt;b&gt;return&lt;/b&gt; &lt;b&gt;false&lt;/b&gt;;
            }
        }

        Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt; FindDictionary&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt; subDictionary;
            &lt;b&gt;if&lt;/b&gt; (!SubDictionaries&amp;lt;T&amp;gt;.Dictionaries.TryGetValue(&lt;b&gt;this&lt;/b&gt;, &lt;b&gt;out&lt;/b&gt; subDictionary))
                &lt;b&gt;return&lt;/b&gt; &lt;b&gt;null&lt;/b&gt;;
            &lt;b&gt;return&lt;/b&gt; subDictionary;
        }

        Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt; GetDictionary&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt; subDictionary;
            &lt;b&gt;if&lt;/b&gt; (!SubDictionaries&amp;lt;T&amp;gt;.Dictionaries.TryGetValue(&lt;b&gt;this&lt;/b&gt;, &lt;b&gt;out&lt;/b&gt; subDictionary)) {
                subDictionary = &lt;b&gt;new&lt;/b&gt; Dictionary&amp;lt;Key&amp;lt;T&amp;gt;, T&amp;gt;();
                SubDictionaries&amp;lt;T&amp;gt;.Dictionaries.Add(&lt;b&gt;this&lt;/b&gt;, subDictionary);
            }
            &lt;b&gt;return&lt;/b&gt; subDictionary;
        }
    }&lt;/pre&gt;
    
&lt;p&gt;This code has so many problems I don&amp;#39;t know where to start. For one, it 
never frees memory, the dictionaries are in memory and will never be 
collected. I only include it to show that it can be done. As you can see, 
sometimes it is better to have a cast. There might be better techniques that 
eliminate some of the problems but my feeling is, why bother. The cast is not that 
bad.&lt;/p&gt;
    
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>The astute among you realized right away that <code>PolyDictionary</code> 
does not really avoid a cast, it just hides it. The <code>TryGetValue()</code> 
has a cast in it, highlighted below,</p>
        <pre>
          <b>public</b>
          <b>bool</b> TryGetValue&lt;K, V&gt;(Key&lt;K, V&gt; key, <b>out</b> V value) {
            <b>object</b> objValue;
            <b>if</b> (_table.TryGetValue(key, <b>out</b> objValue)) {
                value = <span style="background-color:#FFFF00">(V)objValue</span>;
                <b>return</b><b>true</b>;
            }
            value = <b>default</b>(V);
            <b>return</b><b>false</b>;
        }</pre>
        <p>So, can we get rid of the this cast? Yes, but the results are not very 
pleasant. One approach is to create one dictionary for each unique value type 
and then find that dictionary by that type and index into it using the key, 
instead of storing all the values in the same dictionary. This sounds similar to the 
original problem! All we need is a <code>PolyDictionary</code> that maps <code>
T</code> to <code>Dictionary&lt;Key&lt;T&gt;, T&gt;</code>. We could code this but we 
couldn't run it because we would be defining <code>PolyDictionary</code> in 
terms of itself, consuming all of memory in the process. We need something like <code>
PolyDictionary</code> but isn't a <code>PolyDictionary</code>.</p>
        <p>OK, things will now get ugly. Have your barf bags on the stand-by! And, for 
the love of God, don't ever put this in a production application! </p>
        <p>Now that is off my chest, here is one technique to avoid the cast. You can 
create a nested class <code>SubDictionary</code> that has a static instance 
variable which maps <code>PolyDictionaries</code> to <code>Dictionary&lt;Key&lt;T&gt;, T&gt;</code>. 
We can then parameterize <code>SubDictionary</code> by <code>T</code> which will 
create a unique dictionary for each <code>T</code> (I warned you it was ugly). 
This is because the CLR treats every instantiation of <code>SubDictionary&lt;T&gt;</code> as a 
unique type with unique static variables. Essentially we are tricking the CLR 
into producing a dictionary of <code>T</code> to <code>Dictionary&lt;PolyDictionary,Dictionary&lt;Key&lt;T&gt;,T&gt;&gt;</code>. 
Since the variable is static we need to find the version that is for the 
instance we are using, hence the key of <code>PolyDictionary</code>.</p>
        <p>Here is the example,</p>
        <pre>    /* Never, Never use this code! */
    <b>class</b> PolyDictionary {
        
        <b>class</b> SubDictionaries&lt;T&gt; {
            <b>internal</b><b>static</b> Dictionary&lt;PolyDictionary, Dictionary&lt;Key&lt;T&gt;, T&gt;&gt; Dictionaries = 
                <b>new</b> Dictionary&lt;PolyDictionary,Dictionary&lt;Key&lt;T&gt;,T&gt;&gt;();
        }

        <b>public</b> PolyDictionary() { }

        <b>public</b><b>void</b> Add&lt;T&gt;(Key&lt;T&gt; key, T value) {
            Dictionary&lt;Key&lt;T&gt;, T&gt; subDictionary = GetDictionary(key);
            subDictionary.Add(key, value);
        }

        <b>public</b> T Get&lt;T&gt;(Key&lt;T&gt; key) {
            Dictionary&lt;Key&lt;T&gt;, T&gt; subDictionary = FindDictionary(key);
            <b>if</b> (subDictionary != <b>null</b>)
                <b>return</b> subDictionary[key];
            <b>throw</b><b>new</b> KeyNotFoundException();
        }

        <b>public</b><b>bool</b> TryGetValue&lt;T&gt;(Key&lt;T&gt; key, <b>out</b> T value) {
            Dictionary&lt;Key&lt;T&gt;, T&gt; subDictionary = FindDictionary(key);
            <b>if</b> (subDictionary != <b>null</b>)
                <b>return</b> subDictionary.TryGetValue(key, <b>out</b> value);
            <b>else</b> {
                value = <b>default</b>(T);
                <b>return</b><b>false</b>;
            }
        }

        Dictionary&lt;Key&lt;T&gt;, T&gt; FindDictionary&lt;T&gt;(Key&lt;T&gt; key) {
            Dictionary&lt;Key&lt;T&gt;, T&gt; subDictionary;
            <b>if</b> (!SubDictionaries&lt;T&gt;.Dictionaries.TryGetValue(<b>this</b>, <b>out</b> subDictionary))
                <b>return</b><b>null</b>;
            <b>return</b> subDictionary;
        }

        Dictionary&lt;Key&lt;T&gt;, T&gt; GetDictionary&lt;T&gt;(Key&lt;T&gt; key) {
            Dictionary&lt;Key&lt;T&gt;, T&gt; subDictionary;
            <b>if</b> (!SubDictionaries&lt;T&gt;.Dictionaries.TryGetValue(<b>this</b>, <b>out</b> subDictionary)) {
                subDictionary = <b>new</b> Dictionary&lt;Key&lt;T&gt;, T&gt;();
                SubDictionaries&lt;T&gt;.Dictionaries.Add(<b>this</b>, subDictionary);
            }
            <b>return</b> subDictionary;
        }
    }</pre>
        <p>This code has so many problems I don't know where to start. For one, it 
never frees memory, the dictionaries are in memory and will never be 
collected. I only include it to show that it can be done. As you can see, 
sometimes it is better to have a cast. There might be better techniques that 
eliminate some of the problems but my feeling is, why bother. The cast is not that 
bad.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/d378c798-718d-4fab-b42c-f14da5edb6de</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>PolyDictionary II: Constructed Keys</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/195f76e3-a734-4502-8fd6-6d2e49f2e4e3</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/195f76e3-a734-4502-8fd6-6d2e49f2e4e3</link>
      <pubDate>Wed, 21 Mar 2007 15:47:41 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;In the last entry we defined a dictionary that can contain a value of any 
type and extra that value out of the dictionary without our code using a cast. 
The dictionary itself used a cast (which I show a &amp;quot;way&amp;quot; to remove it next time) but our code 
didn&amp;#39;t. One problem it had, however, is it used declared keys instead of 
constructed keys. A declared key is a key can only be referenced by knowing the 
variable it is assigned to; a unique object. A constructed key, on the other 
hand, uses object equality instead of object identity for the key. String keys 
are constructed keys; you can read them from a file, calculate them or use a 
literal value. The dictionary will eventually compare the strings 
for equality. In other words, constructed keys can be constructed from data 
where declared keys cannot.&lt;/p&gt;
&lt;p&gt;Can we modify &lt;code&gt;PolyDictionary&lt;/code&gt; to use constructed keys? One way to 
do it is to create a new &lt;code&gt;Key&lt;/code&gt; type that takes the constructed key 
type as a 
parameter. One such type is, &lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;struct&lt;/b&gt; Key&amp;lt;K, V&amp;gt; {
        &lt;b&gt;public&lt;/b&gt; K Value;
        &lt;b&gt;public&lt;/b&gt; Key(K value) {
            &lt;b&gt;this&lt;/b&gt;.Value = value;
        }
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;implicit&lt;/b&gt; &lt;b&gt;operator&lt;/b&gt; Key&amp;lt;K, V&amp;gt;(K value) {
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Key&amp;lt;K, V&amp;gt;(value);
        }
    }&lt;/pre&gt;
&lt;p&gt;This &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; just wraps the key value. I use a
&lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; instead of a &lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt; 
because structs will do a value comparison for equality by default, classes use 
reference equality.&lt;/p&gt;
&lt;p&gt;The existing methods of &lt;code&gt;PolyDictionary&lt;/code&gt; 
do not take this kind of key; but, we can add methods to &lt;code&gt;PolyDictionary&lt;/code&gt; that do. For 
example, we can create an &lt;code&gt;Add()&lt;/code&gt; method that looks like,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key, V value);&lt;/pre&gt;
&lt;p&gt;We can then create a &lt;code&gt;Get()&lt;/code&gt; method that looks like,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;public&lt;/b&gt; V Get&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key);&lt;/pre&gt;
&lt;p&gt;All these methods can be added directly to &lt;code&gt;PolyDictionary&lt;/code&gt; 
because, through method overloading, they don&amp;#39;t interfere with the original, 
declared key versions.&lt;/p&gt;
&lt;p&gt;Using this dictionary looks like,&lt;/p&gt;
&lt;pre&gt;    Key&amp;lt;&lt;b&gt;string&lt;/b&gt;, &lt;b&gt;string&lt;/b&gt;&amp;gt; k1 = "k1";
    Key&amp;lt;&lt;b&gt;string&lt;/b&gt;, &lt;b&gt;int&lt;/b&gt;&amp;gt; k2 = "k2";
    Key&amp;lt;&lt;b&gt;int&lt;/b&gt;, &lt;b&gt;double&lt;/b&gt;&amp;gt; k3 = 3;

    PolyDictionary dictionary = &lt;b&gt;new&lt;/b&gt; PolyDictionary();

    dictionary.Add(k1, "one");
    dictionary.Add(k2, 2);
    dictionary.Add(k3, 3.33);

    &lt;b&gt;string&lt;/b&gt; v1 = dictionary.Get(k1);
    &lt;b&gt;int&lt;/b&gt; v2 = dictionary.Get(k2);
    &lt;b&gt;double&lt;/b&gt; v3 = dictionary.Get(k3);

    Console.WriteLine("v1 = {0}", v1);
    Console.WriteLine("v2 = {0}", v2);
    Console.WriteLine("v3 = {0}", v3);
&lt;/pre&gt;
&lt;p&gt;The complete example of &lt;code&gt;PolyDictionary&lt;/code&gt; follows,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; PolyDictionary {
        &lt;b&gt;private&lt;/b&gt; Dictionary&amp;lt;&lt;b&gt;object&lt;/b&gt;, &lt;b&gt;object&lt;/b&gt;&amp;gt; _table;

        &lt;b&gt;public&lt;/b&gt; PolyDictionary() {
            _table = &lt;b&gt;new&lt;/b&gt; Dictionary&amp;lt;&lt;b&gt;object&lt;/b&gt;, &lt;b&gt;object&lt;/b&gt;&amp;gt;();
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key, V value) {
            _table.Add(key, value);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, T value) {
            _table.Add(key, value);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Contains&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key) {
            &lt;b&gt;return&lt;/b&gt; _table.ContainsKey(key);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Contains&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            &lt;b&gt;return&lt;/b&gt; _table.ContainsKey(key);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Remove&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key) {
            _table.Remove(key);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Remove&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            _table.Remove(key);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; TryGetValue&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key, &lt;b&gt;out&lt;/b&gt; V value) {
            &lt;b&gt;object&lt;/b&gt; objValue;
            &lt;b&gt;if&lt;/b&gt; (_table.TryGetValue(key, &lt;b&gt;out&lt;/b&gt; objValue)) {
                value = (V)objValue;
                &lt;b&gt;return&lt;/b&gt; &lt;b&gt;true&lt;/b&gt;;
            }
            value = &lt;b&gt;default&lt;/b&gt;(V);
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;false&lt;/b&gt;;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; TryGetValue&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, &lt;b&gt;out&lt;/b&gt; T value) {
            &lt;b&gt;object&lt;/b&gt; objValue;
            &lt;b&gt;if&lt;/b&gt; (_table.TryGetValue(key, &lt;b&gt;out&lt;/b&gt; objValue)) {
                value = (T)objValue;
                &lt;b&gt;return&lt;/b&gt; &lt;b&gt;true&lt;/b&gt;;
            }
            value = &lt;b&gt;default&lt;/b&gt;(T);
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;false&lt;/b&gt;;
        }

        &lt;b&gt;public&lt;/b&gt; V Get&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key) {
            &lt;b&gt;return&lt;/b&gt; (V)_table[key];
        }

        &lt;b&gt;public&lt;/b&gt; T Get&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            &lt;b&gt;return&lt;/b&gt; (T)_table[key];
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Set&amp;lt;K, V&amp;gt;(Key&amp;lt;K, V&amp;gt; key, V value) {
            _table[key] = value;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Set&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, T value) {
            _table[key] = value;
        }
    }&lt;/pre&gt;
&lt;p&gt;Note: the implementation changed a bit from the previous example. The &lt;code&gt;
Get()&lt;/code&gt; methods now use the &lt;code&gt;&lt;strong&gt;this&lt;/strong&gt;&lt;/code&gt; property 
instead of calling &lt;code&gt;TryGetValue()&lt;/code&gt;. This allows the &lt;code&gt;Get()
&lt;/code&gt;methods to be inlined at the cost of an additional cast or two in the 
code.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>In the last entry we defined a dictionary that can contain a value of any 
type and extra that value out of the dictionary without our code using a cast. 
The dictionary itself used a cast (which I show a "way" to remove it next time) but our code 
didn't. One problem it had, however, is it used declared keys instead of 
constructed keys. A declared key is a key can only be referenced by knowing the 
variable it is assigned to; a unique object. A constructed key, on the other 
hand, uses object equality instead of object identity for the key. String keys 
are constructed keys; you can read them from a file, calculate them or use a 
literal value. The dictionary will eventually compare the strings 
for equality. In other words, constructed keys can be constructed from data 
where declared keys cannot.</p>
        <p>Can we modify <code>PolyDictionary</code> to use constructed keys? One way to 
do it is to create a new <code>Key</code> type that takes the constructed key 
type as a 
parameter. One such type is, </p>
        <pre>
          <b>struct</b> Key&lt;K, V&gt; {
        <b>public</b> K Value;
        <b>public</b> Key(K value) {
            <b>this</b>.Value = value;
        }
        <b>public</b><b>static</b><b>implicit</b><b>operator</b> Key&lt;K, V&gt;(K value) {
            <b>return</b><b>new</b> Key&lt;K, V&gt;(value);
        }
    }</pre>
        <p>This <code><strong>struct</strong></code> just wraps the key value. I use a
<code><strong>struct</strong></code> instead of a <code><strong>class</strong></code> 
because structs will do a value comparison for equality by default, classes use 
reference equality.</p>
        <p>The existing methods of <code>PolyDictionary</code> 
do not take this kind of key; but, we can add methods to <code>PolyDictionary</code> that do. For 
example, we can create an <code>Add()</code> method that looks like,</p>
        <pre>
          <b>public</b>
          <b>void</b> Add&lt;K, V&gt;(Key&lt;K, V&gt; key, V value);</pre>
        <p>We can then create a <code>Get()</code> method that looks like,</p>
        <pre>
          <b>public</b> V Get&lt;K, V&gt;(Key&lt;K, V&gt; key);</pre>
        <p>All these methods can be added directly to <code>PolyDictionary</code> 
because, through method overloading, they don't interfere with the original, 
declared key versions.</p>
        <p>Using this dictionary looks like,</p>
        <pre>    Key&lt;<b>string</b>, <b>string</b>&gt; k1 = "k1";
    Key&lt;<b>string</b>, <b>int</b>&gt; k2 = "k2";
    Key&lt;<b>int</b>, <b>double</b>&gt; k3 = 3;

    PolyDictionary dictionary = <b>new</b> PolyDictionary();

    dictionary.Add(k1, "one");
    dictionary.Add(k2, 2);
    dictionary.Add(k3, 3.33);

    <b>string</b> v1 = dictionary.Get(k1);
    <b>int</b> v2 = dictionary.Get(k2);
    <b>double</b> v3 = dictionary.Get(k3);

    Console.WriteLine("v1 = {0}", v1);
    Console.WriteLine("v2 = {0}", v2);
    Console.WriteLine("v3 = {0}", v3);
</pre>
        <p>The complete example of <code>PolyDictionary</code> follows,</p>
        <pre>
          <b>class</b> PolyDictionary {
        <b>private</b> Dictionary&lt;<b>object</b>, <b>object</b>&gt; _table;

        <b>public</b> PolyDictionary() {
            _table = <b>new</b> Dictionary&lt;<b>object</b>, <b>object</b>&gt;();
        }

        <b>public</b><b>void</b> Add&lt;K, V&gt;(Key&lt;K, V&gt; key, V value) {
            _table.Add(key, value);
        }

        <b>public</b><b>void</b> Add&lt;T&gt;(Key&lt;T&gt; key, T value) {
            _table.Add(key, value);
        }

        <b>public</b><b>bool</b> Contains&lt;K, V&gt;(Key&lt;K, V&gt; key) {
            <b>return</b> _table.ContainsKey(key);
        }

        <b>public</b><b>bool</b> Contains&lt;T&gt;(Key&lt;T&gt; key) {
            <b>return</b> _table.ContainsKey(key);
        }

        <b>public</b><b>void</b> Remove&lt;K, V&gt;(Key&lt;K, V&gt; key) {
            _table.Remove(key);
        }

        <b>public</b><b>void</b> Remove&lt;T&gt;(Key&lt;T&gt; key) {
            _table.Remove(key);
        }

        <b>public</b><b>bool</b> TryGetValue&lt;K, V&gt;(Key&lt;K, V&gt; key, <b>out</b> V value) {
            <b>object</b> objValue;
            <b>if</b> (_table.TryGetValue(key, <b>out</b> objValue)) {
                value = (V)objValue;
                <b>return</b><b>true</b>;
            }
            value = <b>default</b>(V);
            <b>return</b><b>false</b>;
        }

        <b>public</b><b>bool</b> TryGetValue&lt;T&gt;(Key&lt;T&gt; key, <b>out</b> T value) {
            <b>object</b> objValue;
            <b>if</b> (_table.TryGetValue(key, <b>out</b> objValue)) {
                value = (T)objValue;
                <b>return</b><b>true</b>;
            }
            value = <b>default</b>(T);
            <b>return</b><b>false</b>;
        }

        <b>public</b> V Get&lt;K, V&gt;(Key&lt;K, V&gt; key) {
            <b>return</b> (V)_table[key];
        }

        <b>public</b> T Get&lt;T&gt;(Key&lt;T&gt; key) {
            <b>return</b> (T)_table[key];
        }

        <b>public</b><b>void</b> Set&lt;K, V&gt;(Key&lt;K, V&gt; key, V value) {
            _table[key] = value;
        }

        <b>public</b><b>void</b> Set&lt;T&gt;(Key&lt;T&gt; key, T value) {
            _table[key] = value;
        }
    }</pre>
        <p>Note: the implementation changed a bit from the previous example. The <code>
Get()</code> methods now use the <code><strong>this</strong></code> property 
instead of calling <code>TryGetValue()</code>. This allows the <code>Get()
</code>methods to be inlined at the cost of an additional cast or two in the 
code.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/195f76e3-a734-4502-8fd6-6d2e49f2e4e3</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>PolyDictionary</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/a2934e63-8a08-4fcf-9f5b-88ba1f50f7c7</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/a2934e63-8a08-4fcf-9f5b-88ba1f50f7c7</link>
      <pubDate>Sat, 17 Mar 2007 13:30:43 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;CLR&amp;#39;s standard &lt;code&gt;Dictionary&amp;lt;K,T&amp;gt;&lt;/code&gt; allows you to express the 
type of the key and the type value so you don&amp;#39;t have to cast on the way in 
and out of a 
dictionary. For example you can cache a bunch of strings based on some integer 
key. I use this in the following program that takes an integer number and writes 
out the English equivalent.&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; Program {
        &lt;b&gt;static&lt;/b&gt; Dictionary&amp;lt;&lt;b&gt;int&lt;/b&gt;, &lt;b&gt;string&lt;/b&gt;&amp;gt; names = &lt;b&gt;new&lt;/b&gt; Dictionary&amp;lt;&lt;b&gt;int&lt;/b&gt;, &lt;b&gt;string&lt;/b&gt;&amp;gt;();

        &lt;b&gt;static&lt;/b&gt; Program() {
            names[0] = "zero";
            names[1] = "one";
            names[2] = "two";
            names[3] = "three";
            names[4] = "four";
            names[5] = "five";
            names[6] = "six";
            names[7] = "seven";
            names[8] = "eight";
            names[9] = "nine";
            names[10] = "ten";
            names[11] = "eleven";
            names[12] = "twelve";
            names[13] = "thirteen";
            names[14] = "fourteen";
            names[15] = "fifteen";
            names[16] = "sixteen";
            names[17] = "seventeen";
            names[18] = "eighteen";
            names[19] = "nineteen";
            names[20] = "twenty";
            names[30] = "thirty";
            names[40] = "forty";
            names[50] = "fifty";
            names[60] = "sixty";
            names[70] = "seventy";
            names[80] = "eighty";
            names[90] = "ninety";
            names[100] = "hundred";
            names[1000] = "thousand";
            names[1000000] = "million";
            names[1000000000] = "billion";
        }

        &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; WriteValue(&lt;b&gt;int&lt;/b&gt; value, &lt;b&gt;int&lt;/b&gt; place) {
            &lt;b&gt;if&lt;/b&gt; (value &amp;gt;= place) {
                &lt;b&gt;int&lt;/b&gt; subValue = value / place;
                WriteValue(subValue);
                Console.Write(" {0} ", names[place]);
                value = value % place;
            }
            &lt;b&gt;return&lt;/b&gt; value;
        }

        &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; WriteValue(&lt;b&gt;int&lt;/b&gt; value) {
            &lt;b&gt;int&lt;/b&gt; originalValue = value;
            &lt;b&gt;if&lt;/b&gt; (value &amp;lt; 0) {
                value = -value;
                Console.WriteLine("negative ");
            }
            value = WriteValue(value, 1000000000);
            value = WriteValue(value, 1000000);
            value = WriteValue(value, 1000);
            value = WriteValue(value, 100);
            &lt;b&gt;if&lt;/b&gt; (value &amp;gt; 20) {
                &lt;b&gt;int&lt;/b&gt; subValue = (value / 10) * 10;
                Console.Write(names[subValue]);
                value = value % 10;
                &lt;b&gt;if&lt;/b&gt; (value == 0)
                    &lt;b&gt;return&lt;/b&gt;;
                Console.Write("-");
            }
            &lt;b&gt;if&lt;/b&gt; (value != 0 || originalValue == 0)
                Console.Write(names[value]);
        }

        &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Main(&lt;b&gt;string&lt;/b&gt;[] args) {
            &lt;b&gt;while&lt;/b&gt; (&lt;b&gt;true&lt;/b&gt;) {
                Console.Write("Enter number: ");
                &lt;b&gt;string&lt;/b&gt; line = Console.ReadLine();
                &lt;b&gt;if&lt;/b&gt; (line == "exit" || &lt;b&gt;string&lt;/b&gt;.IsNullOrEmpty(line))
                    &lt;b&gt;break&lt;/b&gt;;
                &lt;b&gt;int&lt;/b&gt; value;
                &lt;b&gt;if&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt;.TryParse(line, &lt;b&gt;out&lt;/b&gt; value)) {
                    WriteValue(value);
                    Console.WriteLine();
                }
                &lt;b&gt;else&lt;/b&gt;
                    Console.WriteLine("Error: expected number");
            }
        }
    }&lt;/pre&gt;

&lt;p&gt;This example doesn&amp;#39;t use any casts. The expression &lt;code&gt;names[10]&lt;/code&gt; is of type
&lt;code&gt;&lt;strong&gt;string&lt;/strong&gt;&lt;/code&gt; and the index is of type &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt;. 
This is great when the values of the dictionary are all homogeneous as &lt;code&gt;name&lt;/code&gt; is 
above. But what if I want to store values of varying types but still not use a 
cast. In other words, I want a heterogeneous, type-checked dictionary. If I 
don&amp;#39;t mind casts, I can just use a &lt;code&gt;Hashtable&lt;/code&gt; as in,&lt;/p&gt;
&lt;pre&gt;    Hashtable table = &lt;b&gt;new&lt;/b&gt; Hashtable();

    table.Add("k1", "one");
    table.Add("k2", 2);
    table.Add(3, 3.33);

    &lt;b&gt;string&lt;/b&gt; v1 = (&lt;b&gt;string&lt;/b&gt;)table["k1"];
    &lt;b&gt;int&lt;/b&gt; v2 = (&lt;b&gt;int&lt;/b&gt;)table["k2"];
    &lt;b&gt;double&lt;/b&gt; v3 = (&lt;b&gt;double&lt;/b&gt;)table[3];

    Console.WriteLine("v1 = {0}", v1);
    Console.WriteLine("v2 = {0}", v2);
    Console.WriteLine("v3 = {0}", v3);&lt;/pre&gt;
&lt;p&gt;Unfortunately, if I later change the code to,&lt;/p&gt;
&lt;pre&gt;    table.Add("k1", &lt;span style="background-color:yellow"&gt;1&lt;/span&gt;);
    table.Add("k2", 2);
    table.Add(3, 3.33);

    &lt;b&gt;string&lt;/b&gt; v1 = (&lt;b&gt;string&lt;/b&gt;)table["k1"];
    &lt;b&gt;int&lt;/b&gt; v2 = (&lt;b&gt;int&lt;/b&gt;)table["k2"];
    &lt;b&gt;double&lt;/b&gt; v3 = (&lt;b&gt;double&lt;/b&gt;)table[3];&lt;/pre&gt;
&lt;p&gt;The compiler will dutifully compile the code and I will get a runtime error 
at the first use of the dictionary when it tries to cast an integer to a string. 
I would like the compiler to catch this type of error instead of having to wait 
until my user does. &lt;/p&gt;
&lt;p&gt;I have keys of varying type and values of varying type. How can I get 
this and type verification as well? In other words, what I want is something 
like,&lt;/p&gt;
&lt;pre&gt;    dictionary.Add(k1, "one");
    dictionary.Add(k2, 2);
    dictionary.Add(k3, 3.33);

    &lt;b&gt;string&lt;/b&gt; v1 = dictionary[k1];
    &lt;b&gt;int&lt;/b&gt; v2 = dictionary[k2];
    &lt;b&gt;double&lt;/b&gt; v3 = dictionary[k3];&lt;/pre&gt;
&lt;p&gt;What I want to do is be able to infer the returns result of the expression 
&lt;code&gt;dictionary[k1]&lt;/code&gt; from the key. In the above example, there should be 
something about the &lt;code&gt;k1&lt;/code&gt; key that tells the compiler that the result will be a
&lt;code&gt;string&lt;/code&gt; and when I change it later to an &lt;code&gt;int&lt;/code&gt;, I want the 
compiler to catch the assignment to &lt;code&gt;string&lt;/code&gt; as a type error.&lt;/p&gt;
&lt;p&gt;To do this I need a method that can infer the type of the return result from 
a parameter. A simple example of such a method is,&lt;/p&gt;
&lt;pre&gt;    T NoOp(T value) { &lt;strong&gt;return&lt;/strong&gt; value; }&lt;/pre&gt;
&lt;p&gt;which returns the same value of the same type as it retrieves for any value 
of any type. The return type is inferred from the parameter &lt;code&gt;value&lt;/code&gt;&amp;#39;s type.&lt;/p&gt;
&lt;p&gt;This is not good enough yet. We don&amp;#39;t want the key type to be the same as the value type; 
we want the value type to be arbitrary. To do this we need to 
encode the value&amp;#39;s type in the key. One way is to have the 
key&amp;#39;s type include the value&amp;#39;s type as part of the key&amp;#39;s type definition. This can be done 
through supplying a dummy type parameter, a type parameter that is not needed in the definition of 
the type but the dummy type parameter is carried around by the type and can be 
used by type inferencing. To do this we need 
a method something like,&lt;/p&gt;
&lt;pre&gt;    T Get&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) { ... }&lt;/pre&gt;
&lt;p&gt;which takes a key and extracts the return type from the keys definition. This 
requires a &lt;code&gt;Key&lt;/code&gt; class definition that has one type parameter which is simply,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; Key&amp;lt;T&amp;gt; { &lt;b&gt;public&lt;/b&gt; Key() { } }
&lt;/pre&gt;
&lt;p&gt;Note we don&amp;#39;t use &lt;code&gt;T&lt;/code&gt; in &lt;code&gt;Key&lt;/code&gt;, it is just there so type inferencing will find it. We can now 
define some keys,&lt;/p&gt;
&lt;pre&gt;    Key&amp;lt;&lt;b&gt;string&lt;/b&gt;&amp;gt; k1 = &lt;b&gt;new&lt;/b&gt; Key&amp;lt;&lt;b&gt;string&lt;/b&gt;&amp;gt;();
    Key&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt; k2 = &lt;b&gt;new&lt;/b&gt; Key&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;();
    Key&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt; k3 = &lt;b&gt;new&lt;/b&gt; Key&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;The keys are just arbitrary instances. Type 
inferencing will now be able to extract &lt;code&gt;T&lt;/code&gt; from the key&amp;#39;s type and use it as the 
return result! This means that &lt;code&gt;Get(k1)&lt;/code&gt; will be&amp;nbsp; of type &lt;code&gt;string&lt;/code&gt; and
&lt;code&gt;Get(k2)&lt;/code&gt; will be of type 
&lt;code&gt;int&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Type inferencing also works the same way for other parameters of the method. 
For the &lt;code&gt;Add()&lt;/code&gt; method we can define it as,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, T value);&lt;/pre&gt;
&lt;p&gt;With this&amp;nbsp; &lt;code&gt;Add()&lt;/code&gt; the code above will compile because the type of &lt;code&gt;value&lt;/code&gt; is also 
inferred from the key!&lt;/p&gt;
&lt;p&gt;Unfortunately, the &lt;code&gt;this&lt;/code&gt; property does not accept type parameters 
so we cannot get the code, &lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;string&lt;/b&gt; v1 = dictionary[k1];
    &lt;b&gt;int&lt;/b&gt; v2 = dictionary[k2];
    &lt;b&gt;double&lt;/b&gt; v3 = dictionary[k3];&lt;/pre&gt;

&lt;p&gt;to compile; but if we replace the array indexers with a &lt;code&gt;Get()&lt;/code&gt; 
method we can get close, as in,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;string&lt;/b&gt; v1 = dictionary.Get(k1);
    &lt;b&gt;int&lt;/b&gt; v2 = dictionary.Get(k2);
    &lt;b&gt;double&lt;/b&gt; v3 = dictionary.Get(k3);&lt;/pre&gt;

&lt;p&gt;This works if dictionary has a &lt;code&gt;Get()&lt;/code&gt; method like we 
described above,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;public&lt;/b&gt; T Get&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key);&lt;/pre&gt;
&lt;p&gt;There we have it! With the &lt;code&gt;Add()&lt;/code&gt; and &lt;code&gt;Get()&lt;/code&gt; methods we have the beginnings of 
a dictionary that can hold any value of any type and retrieve the value back 
without requiring our use of the dictionary to use a cast. A complete example is given below,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; Key&amp;lt;T&amp;gt; { &lt;b&gt;public&lt;/b&gt; Key() { } }

    &lt;b&gt;class&lt;/b&gt; PolyDictionary {
        &lt;b&gt;private&lt;/b&gt; Dictionary&amp;lt;&lt;b&gt;object&lt;/b&gt;, &lt;b&gt;object&lt;/b&gt;&amp;gt; _table;

        &lt;b&gt;public&lt;/b&gt; PolyDictionary() {
            _table = &lt;b&gt;new&lt;/b&gt; Dictionary&amp;lt;&lt;b&gt;object&lt;/b&gt;, &lt;b&gt;object&lt;/b&gt;&amp;gt;();
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, T value) {
            _table.Add(key, value);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Contains&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            &lt;b&gt;return&lt;/b&gt; _table.ContainsKey(key);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Remove&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            _table.Remove(key);
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; TryGetValue&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, &lt;b&gt;out&lt;/b&gt; T value) {
            &lt;b&gt;object&lt;/b&gt; objValue;
            &lt;b&gt;if&lt;/b&gt; (_table.TryGetValue(key, &lt;b&gt;out&lt;/b&gt; objValue)) {
                value = (T)objValue;
                &lt;b&gt;return&lt;/b&gt; &lt;b&gt;true&lt;/b&gt;;
            }
            value = &lt;b&gt;default&lt;/b&gt;(T);
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;false&lt;/b&gt;;
        }

        &lt;b&gt;public&lt;/b&gt; T Get&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key) {
            T value;
            &lt;b&gt;if&lt;/b&gt; (!TryGetValue(key, &lt;b&gt;out&lt;/b&gt; value))
                &lt;b&gt;throw&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; KeyNotFoundException();
            &lt;b&gt;return&lt;/b&gt; value;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Set&amp;lt;T&amp;gt;(Key&amp;lt;T&amp;gt; key, T value) {
            _table[key] = value;
        }
    }&lt;/pre&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/a2934e63-8a08-4fcf-9f5b-88ba1f50f7c7</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>WPF Forum Best Practices</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/ce6fb4c0-0ea7-42d5-9b48-b58525105fba</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/ce6fb4c0-0ea7-42d5-9b48-b58525105fba</link>
      <pubDate>Tue, 27 Feb 2007 09:45:29 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Rob&amp;#39;s post
&lt;a href="http://rrelyea.spaces.live.com/Blog/cns!167AD7A5AB58D5FE!1676.entry"&gt;Best Forum Practices&lt;/a&gt; 
recommends some guidelines for the WPF forum. My favorite is,&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;u&gt;Recommended Steps for Answering [Questions]:&lt;/u&gt;&lt;/strong&gt; &lt;/p&gt;
&lt;p&gt;1) Answer the question&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;These are good guidelines for any question/answer style forum, not just 
WPF&amp;#39;s.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Rob's post
<a href="http://rrelyea.spaces.live.com/Blog/cns!167AD7A5AB58D5FE!1676.entry">Best Forum Practices</a> 
recommends some guidelines for the WPF forum. My favorite is,</p>
        <blockquote>
          <p>
            <strong>
              <u>Recommended Steps for Answering [Questions]:</u>
            </strong>
          </p>
          <p>1) Answer the question</p>
        </blockquote>
        <p>These are good guidelines for any question/answer style forum, not just 
WPF's.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/ce6fb4c0-0ea7-42d5-9b48-b58525105fba</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Follow-up to Advice</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/13f46be5-c8d7-4e17-a710-178d7fb76205</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/13f46be5-c8d7-4e17-a710-178d7fb76205</link>
      <pubDate>Mon, 19 Feb 2007 15:24:42 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I have to be honest; I didn’t expect the response I 
received from my
&lt;a href="http://www.removingalldoubt.com/commentview.aspx/a32977e2-cb7d-42ea-9d25-5e539423affd"&gt;
Fatherly advice to new programmers&lt;/a&gt; article. There have been some very nice 
things written about it, not only in the comments but in other blogs. I don’t 
consider myself a very good writer and having my writing style praised was 
highly unexpected. I thank everyone for 
their kind words. Also, if you haven’t read the comments posted to the article 
yet, I highly recommend it. They offer interesting insights from a variety of 
perspectives.&lt;/p&gt;
&lt;p&gt;I also recommend reading some of the blogs entries that 
have been written in response to it. I would like to point out one in particular 
from Jeff Atwood:
&lt;a href="http://www.codinghorror.com/blog/archives/000773.html"&gt;Shipping Isn&amp;#39;t 
Enough&lt;/a&gt;. I agree with him. You not only need to focus on shipping but make 
sure what you are working on is worth shipping. You need to focus on shipping 
programs people use and enjoy using.&lt;/p&gt;
&lt;p&gt;Other bloggers have pointed out that you often don’t that 
much control over what you are working on, such as
&lt;a href="http://mikeomatic.net/"&gt;Mike-O-Matic&lt;/a&gt;’s
&lt;a href="http://mikeomatic.net/?p=137"&gt;Shipping Is Enough, Sometimes&lt;/a&gt;. And 
other point out that sometimes you don’t know if what you are working on will be 
used or not, as in Avonelle’s &lt;a href="http://www.coolbits.nu/1130.aspx"&gt;If a 
program falls in a forest...&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;These entries remind me of one more bit of advice: you are 
not your users. Just because you like something some particular way doesn’t mean 
that your users will, nor just because you would never use something doesn’t mean 
nobody needs it. You are not your users; you should get to know them.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>I have to be honest; I didn’t expect the response I 
received from my
<a href="http://www.removingalldoubt.com/commentview.aspx/a32977e2-cb7d-42ea-9d25-5e539423affd">
Fatherly advice to new programmers</a> article. There have been some very nice 
things written about it, not only in the comments but in other blogs. I don’t 
consider myself a very good writer and having my writing style praised was 
highly unexpected. I thank everyone for 
their kind words. Also, if you haven’t read the comments posted to the article 
yet, I highly recommend it. They offer interesting insights from a variety of 
perspectives.</p>
        <p>I also recommend reading some of the blogs entries that 
have been written in response to it. I would like to point out one in particular 
from Jeff Atwood:
<a href="http://www.codinghorror.com/blog/archives/000773.html">Shipping Isn't 
Enough</a>. I agree with him. You not only need to focus on shipping but make 
sure what you are working on is worth shipping. You need to focus on shipping 
programs people use and enjoy using.</p>
        <p>Other bloggers have pointed out that you often don’t that 
much control over what you are working on, such as
<a href="http://mikeomatic.net/">Mike-O-Matic</a>’s
<a href="http://mikeomatic.net/?p=137">Shipping Is Enough, Sometimes</a>. And 
other point out that sometimes you don’t know if what you are working on will be 
used or not, as in Avonelle’s <a href="http://www.coolbits.nu/1130.aspx">If a 
program falls in a forest...</a>.</p>
        <p>These entries remind me of one more bit of advice: you are 
not your users. Just because you like something some particular way doesn’t mean 
that your users will, nor just because you would never use something doesn’t mean 
nobody needs it. You are not your users; you should get to know them.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/13f46be5-c8d7-4e17-a710-178d7fb76205</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>The Expression Problem: The JRuby Interpreter</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/a1411881-6880-4ff8-8e44-5e937d035a8c</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/a1411881-6880-4ff8-8e44-5e937d035a8c</link>
      <pubDate>Wed, 25 Oct 2006 14:32:15 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I previously discussed the expression problem could be solved with various patterns 
including the
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/861feae8-2404-4044-b661-aa13d432b08d"&gt;
visitor pattern&lt;/a&gt; and using
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/e6fb6ded-a66f-4707-97e7-0edaa04b30d9"&gt;
a procedural approach&lt;/a&gt;. It is interesting to note that JRuby used to use a 
visitor pattern but switched to a procedural approach to improve performance. 
You can read about it
&lt;a href="http://www.artima.com/forums/flat.jsp?forum=281&amp;thread=180325"&gt;here&lt;/a&gt;. 
This is a side note in the article since what they want to do is convert Ruby to 
run as byte code similar to how
&lt;a href="http://www.python.org/workshops/1997-10/proceedings/hugunin.html"&gt;
JPython&lt;/a&gt; works.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/a1411881-6880-4ff8-8e44-5e937d035a8c</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Linked List VI: Recursion - see recursion</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/9f6b9b8a-1fe4-4dc9-afda-1f37a24ffe02</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/9f6b9b8a-1fe4-4dc9-afda-1f37a24ffe02</link>
      <pubDate>Mon, 25 Sep 2006 10:06:36 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I finally have a definitive answer to the question of why &lt;span class="code"&gt;MyNode&lt;/span&gt; is needed. 
Consider the following, simplified, version of the &lt;span class="code"&gt;LinkedList&lt;/span&gt; classes I posed,&lt;/p&gt;
&lt;pre&gt;  &lt;b&gt;class&lt;/b&gt; C&amp;lt;X&amp;gt; { &lt;b&gt;class&lt;/b&gt; N { } }
  &lt;b&gt;class&lt;/b&gt; D: C&amp;lt;D.N&amp;gt; { }&lt;/pre&gt;
&lt;p&gt;This is really an obfuscated form of&lt;/p&gt;
&lt;pre&gt;  &lt;b&gt;class&lt;/b&gt; N&amp;lt;X&amp;gt; { }
  &lt;b&gt;class&lt;/b&gt; C&amp;lt;X&amp;gt; { }
  &lt;b&gt;class&lt;/b&gt; D: C&amp;lt;N&amp;lt;?&amp;gt;&amp;gt; { }&lt;/pre&gt;
&lt;p&gt;where ? needs to be replaced by an infinite list if &lt;span class="code"&gt;N&amp;lt;N&amp;lt;...&amp;gt;&amp;gt;&lt;/span&gt;. In other 
words, I am trying to define a type directly in terms of itself, a
&lt;span class="code"&gt;T&lt;/span&gt; where &lt;span class="code"&gt;T=N&amp;lt;T&amp;gt;&lt;/span&gt;. This is not 
allowed. An additional type is required to break the cycle, such as
&lt;span class="code"&gt;M&lt;/span&gt; in,&lt;/p&gt;

&lt;pre&gt;  &lt;b&gt;class&lt;/b&gt; M: N&amp;lt;M&amp;gt; { }&lt;/pre&gt;

&lt;p&gt;Then I can write,&lt;/p&gt;

&lt;pre&gt;  &lt;b&gt;class&lt;/b&gt; D: C&amp;lt;M&amp;gt; { }&lt;/pre&gt;

&lt;p&gt;So, there we have it, &lt;span class="code"&gt;MyNode&lt;/span&gt; is necessary to avoid defining 
a type directly in terms 
of itself. The unobfuscated version makes this much more clear.
&lt;span class="code"&gt;MyNode&lt;/span&gt; serves the same role as &lt;span class="code"&gt;M&lt;/span&gt; 
does above.&lt;/p&gt;
&lt;p&gt;Thanks again to &lt;a href="http://research.microsoft.com/~akenn/"&gt;Andrew&lt;/a&gt; 
for taking the time to beat this into my thick skull.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>I finally have a definitive answer to the question of why <span class="code">MyNode</span> is needed. 
Consider the following, simplified, version of the <span class="code">LinkedList</span> classes I posed,</p>
        <pre>
          <b>class</b> C&lt;X&gt; { <b>class</b> N { } }
  <b>class</b> D: C&lt;D.N&gt; { }</pre>
        <p>This is really an obfuscated form of</p>
        <pre>
          <b>class</b> N&lt;X&gt; { }
  <b>class</b> C&lt;X&gt; { }
  <b>class</b> D: C&lt;N&lt;?&gt;&gt; { }</pre>
        <p>where ? needs to be replaced by an infinite list if <span class="code">N&lt;N&lt;...&gt;&gt;</span>. In other 
words, I am trying to define a type directly in terms of itself, a
<span class="code">T</span> where <span class="code">T=N&lt;T&gt;</span>. This is not 
allowed. An additional type is required to break the cycle, such as
<span class="code">M</span> in,</p>
        <pre>
          <b>class</b> M: N&lt;M&gt; { }</pre>
        <p>Then I can write,</p>
        <pre>
          <b>class</b> D: C&lt;M&gt; { }</pre>
        <p>So, there we have it, <span class="code">MyNode</span> is necessary to avoid defining 
a type directly in terms 
of itself. The unobfuscated version makes this much more clear.
<span class="code">MyNode</span> serves the same role as <span class="code">M</span> 
does above.</p>
        <p>Thanks again to <a href="http://research.microsoft.com/~akenn/">Andrew</a> 
for taking the time to beat this into my thick skull.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/9f6b9b8a-1fe4-4dc9-afda-1f37a24ffe02</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Fatherly Advice To New Programmers</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/a32977e2-cb7d-42ea-9d25-5e539423affd</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/a32977e2-cb7d-42ea-9d25-5e539423affd</link>
      <pubDate>Tue, 19 Sep 2006 09:43:20 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;It looks like none of my children will become programmers. Instead of letting 
my fatherly advice to my new programmer son or daughter go to waste, I am going 
to inflict it on you. If you are newly embarking on the journey that is becoming 
a programmer, here is advice your father would tell you if he were a programmer. 
These are things I had to learn the hard way. &lt;/p&gt;
&lt;p&gt;&lt;b&gt;Keep Learning: &lt;/b&gt;Read. Go to conferences. Subscribe to journals. Take 
classes. Whatever it takes for you to keep learning, make it a priority. Learn 
about every language you can find. Take time to learn about any new frameworks, 
algorithms, techniques, models, paradigms, you can. Each gives you one more 
tool in your tool chest. Each will help you more easily tackle your next 
programming problem. Find a mentor, someone much better than you, and learn all 
they can teach you. Never stop learning.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Learn To Communicate&lt;/b&gt;: I often joke that the most important skill you 
can learn as a programmer is how to draw a rectangle on a white-board. 
Communication is critical to the job of a programmer. Communicating with 
customers, clients, users, co-workers, bosses, vice presidents, CEO's, 
board-members, VC capitalists, all will become important at some point in your 
career. Learn how to speak in public. Learn how to write in English. Learn to 
effectively communicate in person. Learn how to persuade without shouting, 
getting angry, or getting flustered. Learn how to speak without jargon. Help 
people understand what you are doing. Learn to break things into simple, 
understandable pieces. Learn to communicate by analogy and symbolism. Learn to 
communicate.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Be Predictable:&lt;/b&gt; Learn how fast you can comfortably program. Wait to 
predict how long it will take you to complete a task until you understand it. 
Allow for the unexpected. Plan for vacations and time-off. Live with your 
predictions. I don't believe I know a problem well enough to predict how long it 
will take to complete until I can break that task down into sub-tasks that each 
take no longer than 3 days (often less than one day). Live by this rule, 
under-promise, over-deliver. It is better to deliver in 10 days what you 
promised in 15 than to deliver in 10 days what you promised in 5. People depend, 
schedule, and plan around your predictions. Make them the best you can and make 
sure you can comfortably do them or you will be asked to live up to your 
uncomfortable predictions. You will not be good at it at first; to compensate, 
verify your predictions with someone more experienced. Learn to get better. Be 
predictable; other depend on you.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Own Up To Your Mistakes:&lt;/b&gt; You will make mistakes. How you handle your 
mistakes is how you will be judged. Learn how to say &amp;quot;I was wrong.&amp;quot; If you 
underestimated how long it will take you to do something, tell people as soon as 
it is clear to you. If you broke the build, fix it. If you created a bug, fix 
it. Don't deny the mistake, don't make excuses for the mistake, don't figure out 
how to hide the mistake, don't blame others for the mistake, do something about 
it. Take ownership of your mistake or you &lt;i&gt;will&lt;/i&gt; repeat it.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Never Let Bad Code Off Your Desk:&lt;/b&gt; Your job as a programmer is to write 
code that works, never let code off your desk you are not sure meets that 
criteria. Not only does it reflect badly on you, it is much more expensive, and 
much harder, to find a problem once it leaves your desk than before. Learn to 
love unit tests. Learn to love code coverage. Learn to test your code better 
than people who are paid to test it. Be embarrassed about bugs that are found 
after you have checked-in. Be especially embarrassed when a customer finds the 
bug. Don't rely on others to find your bugs for you, find them and fix them 
yourself. Don't hope it will work. Test it. Don't assume it will work. Test it. 
Don't whatever. Just test it. If you haven't tested it, it doesn't work; of this 
you &lt;i&gt;can&lt;/i&gt; be sure. But, even if you are diligent with testing, bugs will 
get by you. You will make mistakes but try your best not to.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Programming is Fun But Shipping is Your Job:&lt;/b&gt; Programming is fun. It is 
the joy of discovery. It is the joy of creation. It is the joy of accomplishment. It 
is the joy of learning. It is fun to see your handiwork displaying on the 
screen. It is fun to have your co-workers marvel at your code. It is fun to have 
people use your work. It is fun have your product lauded in public, used by 
neighbors, and discussed in the press. Programming should be fun and if it 
isn't, figure out what is making it not fun and fix it. However, shipping isn't 
fun. I often have said that shipping a product feels good, like when someone 
stops hitting you. Your job is completing the product, fixing the bugs, and 
shipping. If bugs need fixing, fix them. If documentation needs writing, write 
it. If code needs testing, test it. All of this is part of shipping. You don't 
get paid to program, you get paid to ship. Be good at your job.&lt;/p&gt;
&lt;p&gt;Remember these simple statements,&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Never stop learning.&lt;/li&gt;
	&lt;li&gt;Communication is critical.&lt;/li&gt;
	&lt;li&gt;Under promise, over deliver.&lt;/li&gt;
	&lt;li&gt;&amp;quot;I was wrong.&amp;quot;&lt;/li&gt;
	&lt;li&gt;If it is not tested it doesn't work.&lt;/li&gt;
	&lt;li&gt;Programming isn't your job, shipping is.&lt;/li&gt;
&lt;/ul&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>It looks like none of my children will become programmers. Instead of letting 
my fatherly advice to my new programmer son or daughter go to waste, I am going 
to inflict it on you. If you are newly embarking on the journey that is becoming 
a programmer, here is advice your father would tell you if he were a programmer. 
These are things I had to learn the hard way. </p>
        <p>
          <b>Keep Learning: </b>Read. Go to conferences. Subscribe to journals. Take 
classes. Whatever it takes for you to keep learning, make it a priority. Learn 
about every language you can find. Take time to learn about any new frameworks, 
algorithms, techniques, models, paradigms, you can. Each gives you one more 
tool in your tool chest. Each will help you more easily tackle your next 
programming problem. Find a mentor, someone much better than you, and learn all 
they can teach you. Never stop learning.</p>
        <p>
          <b>Learn To Communicate</b>: I often joke that the most important skill you 
can learn as a programmer is how to draw a rectangle on a white-board. 
Communication is critical to the job of a programmer. Communicating with 
customers, clients, users, co-workers, bosses, vice presidents, CEO's, 
board-members, VC capitalists, all will become important at some point in your 
career. Learn how to speak in public. Learn how to write in English. Learn to 
effectively communicate in person. Learn how to persuade without shouting, 
getting angry, or getting flustered. Learn how to speak without jargon. Help 
people understand what you are doing. Learn to break things into simple, 
understandable pieces. Learn to communicate by analogy and symbolism. Learn to 
communicate.</p>
        <p>
          <b>Be Predictable:</b> Learn how fast you can comfortably program. Wait to 
predict how long it will take you to complete a task until you understand it. 
Allow for the unexpected. Plan for vacations and time-off. Live with your 
predictions. I don't believe I know a problem well enough to predict how long it 
will take to complete until I can break that task down into sub-tasks that each 
take no longer than 3 days (often less than one day). Live by this rule, 
under-promise, over-deliver. It is better to deliver in 10 days what you 
promised in 15 than to deliver in 10 days what you promised in 5. People depend, 
schedule, and plan around your predictions. Make them the best you can and make 
sure you can comfortably do them or you will be asked to live up to your 
uncomfortable predictions. You will not be good at it at first; to compensate, 
verify your predictions with someone more experienced. Learn to get better. Be 
predictable; other depend on you.</p>
        <p>
          <b>Own Up To Your Mistakes:</b> You will make mistakes. How you handle your 
mistakes is how you will be judged. Learn how to say "I was wrong." If you 
underestimated how long it will take you to do something, tell people as soon as 
it is clear to you. If you broke the build, fix it. If you created a bug, fix 
it. Don't deny the mistake, don't make excuses for the mistake, don't figure out 
how to hide the mistake, don't blame others for the mistake, do something about 
it. Take ownership of your mistake or you <i>will</i> repeat it.</p>
        <p>
          <b>Never Let Bad Code Off Your Desk:</b> Your job as a programmer is to write 
code that works, never let code off your desk you are not sure meets that 
criteria. Not only does it reflect badly on you, it is much more expensive, and 
much harder, to find a problem once it leaves your desk than before. Learn to 
love unit tests. Learn to love code coverage. Learn to test your code better 
than people who are paid to test it. Be embarrassed about bugs that are found 
after you have checked-in. Be especially embarrassed when a customer finds the 
bug. Don't rely on others to find your bugs for you, find them and fix them 
yourself. Don't hope it will work. Test it. Don't assume it will work. Test it. 
Don't whatever. Just test it. If you haven't tested it, it doesn't work; of this 
you <i>can</i> be sure. But, even if you are diligent with testing, bugs will 
get by you. You will make mistakes but try your best not to.</p>
        <p>
          <b>Programming is Fun But Shipping is Your Job:</b> Programming is fun. It is 
the joy of discovery. It is the joy of creation. It is the joy of accomplishment. It 
is the joy of learning. It is fun to see your handiwork displaying on the 
screen. It is fun to have your co-workers marvel at your code. It is fun to have 
people use your work. It is fun have your product lauded in public, used by 
neighbors, and discussed in the press. Programming should be fun and if it 
isn't, figure out what is making it not fun and fix it. However, shipping isn't 
fun. I often have said that shipping a product feels good, like when someone 
stops hitting you. Your job is completing the product, fixing the bugs, and 
shipping. If bugs need fixing, fix them. If documentation needs writing, write 
it. If code needs testing, test it. All of this is part of shipping. You don't 
get paid to program, you get paid to ship. Be good at your job.</p>
        <p>Remember these simple statements,</p>
        <ul>
          <li>Never stop learning.</li>
          <li>Communication is critical.</li>
          <li>Under promise, over deliver.</li>
          <li>"I was wrong."</li>
          <li>If it is not tested it doesn't work.</li>
          <li>Programming isn't your job, shipping is.</li>
        </ul>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/a32977e2-cb7d-42ea-9d25-5e539423affd</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Linked List V: Revenge of the Type Parameter</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/2c3b30bf-6354-4056-ac6e-99ae1851756e</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/2c3b30bf-6354-4056-ac6e-99ae1851756e</link>
      <pubDate>Fri, 08 Sep 2006 12:37:06 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I honestly thought I was done with this topic but as it turns out I missed 
something. I stated firmly that &amp;quot;currently, in C#, we are stuck with the cast&amp;quot; 
but I was wrong. One of the great things about working at Microsoft is the people you can interact with. In 
back burner researching a definitive answer to Hallvard's 
question to my post of why linked list &lt;span class="code"&gt;LinkedList&amp;lt;T&amp;gt;&lt;/span&gt; cannot be written,&lt;/p&gt;
&lt;pre&gt;  &lt;b&gt;class&lt;/b&gt; LinkedList&amp;lt;T&amp;gt;: LinkedList&amp;lt;T, LinkedList&amp;lt;T&amp;gt;.Node&amp;gt; { }&lt;/pre&gt;
&lt;p&gt;I asked &lt;a href="http://research.microsoft.com/~akenn/"&gt;Andrew Kennedy&lt;/a&gt; to look at my page. 
I like talking to Andrew; I learn at least one new thing every time we talk. 
This was certainly no exception. He quickly pointed out something 
that was staring me squarely in the face but I missed entirely, folding my implementation of
&lt;span class="code"&gt;DoubleLinkedList&amp;lt;T&amp;gt;&lt;/span&gt; with &lt;span class="code"&gt;DoubleLinkedList&amp;lt;T, N&amp;gt;&lt;/span&gt; 
and closing the node type directly 
will remove the cast. In other words, &lt;span class="code"&gt;DoubleLinkedList&amp;lt;T&amp;gt;&lt;/span&gt; can be written without 
casts as,&lt;/p&gt;
&lt;pre&gt;
    &lt;b&gt;class&lt;/b&gt; DoubleLinkedList&amp;lt;T&amp;gt;: LinkedList&amp;lt;T, DoubleLinkedList&amp;lt;T&amp;gt;.DoubleNode&amp;gt;,
        IDoubleLinkedList&amp;lt;T&amp;gt; {

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; DoubleNode: Node {
            DoubleNode _previous;

            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; DoubleNode Next {
                &lt;b&gt;get&lt;/b&gt; {
                    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;base&lt;/b&gt;.Next;
                }
                &lt;b&gt;set&lt;/b&gt; {
                    &lt;b&gt;base&lt;/b&gt;.Next = value;
                    value._previous = &lt;b&gt;this&lt;/b&gt;;
                }
            }

            &lt;b&gt;public&lt;/b&gt; DoubleNode Previous { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _previous; } }
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerable&amp;lt;T&amp;gt; Backwards {
            get {
                &lt;b&gt;if&lt;/b&gt; (Last != &lt;b&gt;null&lt;/b&gt;) {
                    DoubleNode current = Last;
                    &lt;b&gt;do&lt;/b&gt; {
                        &lt;b&gt;yield&lt;/b&gt; &lt;b&gt;return&lt;/b&gt; current.Data;
                        current = current.Previous;
                    } &lt;b&gt;while&lt;/b&gt; (current != Last);
                }
            }
        }
    }&lt;/pre&gt;
   
&lt;p&gt;which closes the node parameter instead of leaving it open. This is one of 
those head-slapping, &amp;quot;how stupid of me&amp;quot; moments like when someone points out 
that &amp;quot;you know, if you would have pushed the other pawn instead, you would have 
had checkmate in three moves.&amp;quot; You can see that this is a straight forward 
application of the requires clause version (declaring it to be
&lt;span class="code"&gt;DoubleNode&lt;/span&gt; instead of requiring it). In my zest to introduce the concepts of the &amp;quot;this type&amp;quot; from LOOM and the 
requires clause from Scala, I missed what should have been obvious. 
Silly me. &lt;/p&gt;
&lt;p&gt;This solution has the limitation that you cannot derive something like
&lt;span class="code"&gt;TripleLinkedList&amp;lt;T&amp;gt;&lt;/span&gt; from &lt;span class="code"&gt;
DoubleLinkedList&amp;lt;T&amp;gt;&lt;/span&gt; so my example still holds some water (&lt;span class="code"&gt;TripleLinkedList&amp;lt;T, 
N&amp;gt;&lt;/span&gt; can be derived from &lt;span class="code"&gt;DoubleLinkedList&amp;lt;T, N&amp;gt;&lt;/span&gt;) 
but it is not nearly so compelling. I still think that one of the two features 
would be very useful but I need a much better motivating example.&lt;/p&gt;
   
&lt;p&gt;While I still don't have a definitive answer to Hallvard's question, I picked 
up this gem along the way. Not bad so far.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>I honestly thought I was done with this topic but as it turns out I missed 
something. I stated firmly that "currently, in C#, we are stuck with the cast" 
but I was wrong. One of the great things about working at Microsoft is the people you can interact with. In 
back burner researching a definitive answer to Hallvard's 
question to my post of why linked list <span class="code">LinkedList&lt;T&gt;</span> cannot be written,</p>
        <pre>
          <b>class</b> LinkedList&lt;T&gt;: LinkedList&lt;T, LinkedList&lt;T&gt;.Node&gt; { }</pre>
        <p>I asked <a href="http://research.microsoft.com/~akenn/">Andrew Kennedy</a> to look at my page. 
I like talking to Andrew; I learn at least one new thing every time we talk. 
This was certainly no exception. He quickly pointed out something 
that was staring me squarely in the face but I missed entirely, folding my implementation of
<span class="code">DoubleLinkedList&lt;T&gt;</span> with <span class="code">DoubleLinkedList&lt;T, N&gt;</span> 
and closing the node type directly 
will remove the cast. In other words, <span class="code">DoubleLinkedList&lt;T&gt;</span> can be written without 
casts as,</p>
        <pre>
          <b>class</b> DoubleLinkedList&lt;T&gt;: LinkedList&lt;T, DoubleLinkedList&lt;T&gt;.DoubleNode&gt;,
        IDoubleLinkedList&lt;T&gt; {

        <b>public</b><b>class</b> DoubleNode: Node {
            DoubleNode _previous;

            <b>public</b><b>override</b> DoubleNode Next {
                <b>get</b> {
                    <b>return</b><b>base</b>.Next;
                }
                <b>set</b> {
                    <b>base</b>.Next = value;
                    value._previous = <b>this</b>;
                }
            }

            <b>public</b> DoubleNode Previous { <b>get</b> { <b>return</b> _previous; } }
        }

        <b>public</b> IEnumerable&lt;T&gt; Backwards {
            get {
                <b>if</b> (Last != <b>null</b>) {
                    DoubleNode current = Last;
                    <b>do</b> {
                        <b>yield</b><b>return</b> current.Data;
                        current = current.Previous;
                    } <b>while</b> (current != Last);
                }
            }
        }
    }</pre>
        <p>which closes the node parameter instead of leaving it open. This is one of 
those head-slapping, "how stupid of me" moments like when someone points out 
that "you know, if you would have pushed the other pawn instead, you would have 
had checkmate in three moves." You can see that this is a straight forward 
application of the requires clause version (declaring it to be
<span class="code">DoubleNode</span> instead of requiring it). In my zest to introduce the concepts of the "this type" from LOOM and the 
requires clause from Scala, I missed what should have been obvious. 
Silly me. </p>
        <p>This solution has the limitation that you cannot derive something like
<span class="code">TripleLinkedList&lt;T&gt;</span> from <span class="code">
DoubleLinkedList&lt;T&gt;</span> so my example still holds some water (<span class="code">TripleLinkedList&lt;T, 
N&gt;</span> can be derived from <span class="code">DoubleLinkedList&lt;T, N&gt;</span>) 
but it is not nearly so compelling. I still think that one of the two features 
would be very useful but I need a much better motivating example.</p>
        <p>While I still don't have a definitive answer to Hallvard's question, I picked 
up this gem along the way. Not bad so far.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/2c3b30bf-6354-4056-ac6e-99ae1851756e</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Linked List IV: Removing casts</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/570895be-ef3d-4841-a5a2-31aa1c5f5946</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/570895be-ef3d-4841-a5a2-31aa1c5f5946</link>
      <pubDate>Fri, 14 Apr 2006 01:56:43 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
   &lt;p&gt;In the last entry we successfully derived a double-linked list implementation 
from a single-linked list implementation, but we had to use casts to get it to 
compile. What we want to do now is see if we can remove the casts.&lt;/p&gt;
&lt;p&gt;We will first remove the cast in the &lt;span class="code"&gt;Backwards&lt;/span&gt; 
method. &lt;/p&gt;
&lt;pre&gt;        DoubleNode current = (DoubleNode)Last;&lt;/pre&gt;
&lt;p&gt;The reason we need the cast is because the base class defines
&lt;span class="code"&gt;Last&lt;/span&gt; to be&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;protected&lt;/b&gt; Node Last { get { &lt;b&gt;return&lt;/b&gt; _last; } }&lt;/pre&gt;

&lt;p&gt;What we need is the type to be &lt;span class="code"&gt;DoubleNode&lt;/span&gt;, but this 
property is defined in a descendent class. To allow us to change the type we 
need to leave the type open, or, in other words,&amp;nbsp; add the node type as a 
type parameter. To accomplish this, I replaced all references 
to the node type with a type parameter. The new &lt;span class="code"&gt;LinkedList&lt;/span&gt; 
class looks 
like,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; LinkedList&amp;lt;T, NodeType&amp;gt;: IEnumerable&amp;lt;T&amp;gt;, ILinkedList&amp;lt;T&amp;gt; 
        &lt;b&gt;where&lt;/b&gt; NodeType: LinkedList&amp;lt;T, NodeType&amp;gt;.Node, &lt;b&gt;new&lt;/b&gt;() {

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Node {
            &lt;b&gt;private&lt;/b&gt; T _data;
            &lt;b&gt;private&lt;/b&gt; NodeType _next;

            &lt;b&gt;public&lt;/b&gt; T Data { 
                &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _data; }
                &lt;b&gt;set&lt;/b&gt; { _data = value; } 
            }
            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;virtual&lt;/b&gt; NodeType Next { 
                &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _next; } 
                &lt;b&gt;set&lt;/b&gt; { _next = value; } 
            }
        }

        NodeType _last;

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add(T value) {
            NodeType newNode = &lt;b&gt;new&lt;/b&gt; NodeType();
            newNode.Data = value;
            &lt;b&gt;if&lt;/b&gt; (_last == &lt;b&gt;null&lt;/b&gt;) {
                _last = newNode;
                newNode.Next = newNode;
            }
            &lt;b&gt;else&lt;/b&gt; {
                newNode.Next = _last.Next;
                _last.Next = newNode;
                _last = newNode;
            }
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Clear() {
            _last = &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerator&amp;lt;T&amp;gt; GetEnumerator() {
            &lt;b&gt;if&lt;/b&gt; (_last != &lt;b&gt;null&lt;/b&gt;) {
                NodeType current = _last;
                &lt;b&gt;do&lt;/b&gt; {
                    current = current.Next;
                    &lt;b&gt;yield&lt;/b&gt; &lt;b&gt;return&lt;/b&gt; current.Data;
                } &lt;b&gt;while&lt;/b&gt; (current != _last);
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            &lt;b&gt;return&lt;/b&gt; GetEnumerator();
        }

        &lt;b&gt;protected&lt;/b&gt; NodeType Last { 
            &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _last; } 
        }
    }&lt;/pre&gt;
&lt;p&gt;The &lt;b&gt;&lt;span class="code"&gt;where&lt;/span&gt;&lt;/b&gt; clause looks complicated but what 
it says is that &lt;span class="code"&gt;NodeType&lt;/span&gt;'s actual parameter must 
derive from the &lt;span class="code"&gt;Node&lt;/span&gt; type defined in the class. This 
allows me to use the properties defined for the node class on variables of type
&lt;span class="code"&gt;NodeType&lt;/span&gt;. The &lt;span class="code"&gt;&lt;b&gt;new&lt;/b&gt;()&lt;/span&gt; part says that the 
actual parameter must also 
have a default constructor. This allows us to remove the &lt;span class="code"&gt;
CreateNode()&lt;/span&gt; method.&lt;/p&gt;
&lt;p&gt;Unfortunately, this definition is a bit difficult to use 
because you need to define a node class to pass as a parameter. To make this 
easier, I defined a single parameter version,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; LinkedList&amp;lt;T&amp;gt;: LinkedList&amp;lt;T, LinkedList&amp;lt;T&amp;gt;.MyNode&amp;gt; {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; MyNode: Node { }
    }&lt;/pre&gt;
&lt;p&gt;I implemented the double-linked list as,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; DoubleLinkedList&amp;lt;T, NodeType&amp;gt;: LinkedList&amp;lt;T, NodeType&amp;gt;, IDoubleLinkedList&amp;lt;T&amp;gt; 
        where NodeType: DoubleLinkedList&amp;lt;T, NodeType&amp;gt;.DoubleNode, &lt;b&gt;new&lt;/b&gt;() {
        
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; DoubleNode: Node {
            NodeType _previous;

            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; NodeType Next {
                &lt;b&gt;get&lt;/b&gt; {
                    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;base&lt;/b&gt;.Next;
                }
                &lt;b&gt;set&lt;/b&gt; {
                    &lt;b&gt;base&lt;/b&gt;.Next = value;
                    value._previous = (NodeType)&lt;b&gt;this&lt;/b&gt;;
                }
            }

            &lt;b&gt;public&lt;/b&gt; NodeType Previous { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _previous; } }
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerable&amp;lt;T&amp;gt; Backwards {
            get {
                &lt;b&gt;if&lt;/b&gt; (Last != &lt;b&gt;null&lt;/b&gt;) {
                    NodeType current = Last;
                    &lt;b&gt;do&lt;/b&gt; {
                        &lt;b&gt;yield&lt;/b&gt; &lt;b&gt;return&lt;/b&gt; current.Data;
                        current = current.Previous;
                    } &lt;b&gt;while&lt;/b&gt; (current != Last);
                }
            }
        }
    }&lt;/pre&gt;
&lt;p&gt;This looks almost identical to the previous &lt;span class="code"&gt;
DoubleLinkedList&lt;/span&gt; that I posted last time but it no longer needs a cast in
&lt;span class="code"&gt;Backwards&lt;/span&gt;. This is achieved by constraining types 
passed as &lt;span class="code"&gt;NodeType&lt;/span&gt; to descend from &lt;span class="code"&gt;
DoubleNode&lt;/span&gt; instead of just &lt;span class="code"&gt;Node&lt;/span&gt;. We can pass
&lt;span class="code"&gt;NodeType&lt;/span&gt; to &lt;span class="code"&gt;LinkedList&amp;lt;T, NodeType&amp;gt;&lt;/span&gt; 
because the constrains on &lt;span class="code"&gt;NodeType&lt;/span&gt; are compatible with 
the constraints for &lt;span class="code"&gt;NodeType&lt;/span&gt; in &lt;span class="code"&gt;
LinkedList&amp;lt;T, NodeType&amp;gt;&lt;/span&gt;. I require that &lt;span class="code"&gt;NodeType&lt;/span&gt; 
derive from &lt;span class="code"&gt;DoubleNode&lt;/span&gt; which, itself, derives from
&lt;span class="code"&gt;Node&lt;/span&gt;. &lt;span class="code"&gt;LinkedList&amp;lt;T, NodeType&amp;gt;&lt;/span&gt; 
requires &lt;span class="code"&gt;NodeType&lt;/span&gt; to derive from &lt;span class="code"&gt;Node&lt;/span&gt;; requiring it 
derive from &lt;span class="code"&gt;DoubleNode&lt;/span&gt; ensures that is the case. I 
will also make this easier to use, like &lt;span class="code"&gt;LinkedList&amp;lt;T, NodeType&amp;gt;&lt;/span&gt; 
above, by creating &lt;span class="code"&gt;DoubleLink&amp;lt;T&amp;gt;&lt;/span&gt; from
&lt;span class="code"&gt;DoubleLink&amp;lt;T, NodeType&amp;gt;&lt;/span&gt;, as in,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; DoubleLinkedList&amp;lt;T&amp;gt;: DoubleLinkedList&amp;lt;T, DoubleLinkedList&amp;lt;T&amp;gt;.MyNode&amp;gt; {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; MyNode: DoubleNode { }
    }&lt;/pre&gt;
&lt;p&gt;But, we still need a cast in the &lt;span class="code"&gt;Next&lt;/span&gt; property. 
The reason we need it is, even though we know that &lt;span class="code"&gt;NodeType&lt;/span&gt; 
derives from &lt;span class="code"&gt;DoubleNode&lt;/span&gt;, the compiler only is sure 
that the type of the object itself is &lt;span class="code"&gt;DoubleNode&lt;/span&gt;. It 
cannot prove that it must be a &lt;span class="code"&gt;NodeType&lt;/span&gt; and there is 
no way in C# to declare that it must be. Currently, in C#, we are stuck with the 
cast. A couple languages have tried to deal 
with this problem. One such language is
&lt;a href="http://www.cs.pomona.edu/~kim/README.html#Match"&gt;LOOM&lt;/a&gt; by
&lt;a href="http://www.cs.pomona.edu/~kim/"&gt;Kim Bruce&lt;/a&gt; and others. LOOM allows 
declaring that a variable must be the same type as &lt;b&gt;&lt;span class="code"&gt;
this&lt;/span&gt;&lt;/b&gt;. What that might look like in our example is the following,&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; DoubleNode: Node {
            &lt;b&gt;this&lt;/b&gt; _previous;

            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; NodeType Next {
                get {
                    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;base&lt;/b&gt;.Next;
                }
                set {
                    &lt;b&gt;base&lt;/b&gt;.Next = value;
                    value._previous = &lt;b&gt;this&lt;/b&gt;;
                }
            }

            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;this&lt;/b&gt; Previous { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _previous; } }
        }&lt;/pre&gt;
&lt;p&gt;where I assume that the keyword &lt;b&gt;&lt;span class="code"&gt;this&lt;/span&gt;&lt;/b&gt; is used 
where the type is assumed to be the type of &lt;b&gt;&lt;span class="code"&gt;this&lt;/span&gt;&lt;/b&gt;. 
This concept also shows up in Eiffel as &lt;span class="code"&gt;&lt;b&gt;like&lt;/b&gt; Current&lt;/span&gt;. Unfortunately, proving that &lt;span class="code"&gt;NodeType&lt;/span&gt; 
and &lt;span class="code"&gt;DoubleNode&lt;/span&gt;'s &lt;b&gt;&lt;span class="code"&gt;this&lt;/span&gt;&lt;/b&gt; 
type are identitical is a non-trivial problem and has the side affect of adding 
exact typing to the language or leaves the type system unsound as Eiffel's
&lt;span class="code"&gt;&lt;b&gt;like&lt;/b&gt; Current&lt;/span&gt; does.&lt;/p&gt;
&lt;p&gt;Another approach is to constrain the decedents of &lt;span class="code"&gt;
DoubleNode&lt;/span&gt; to also to be decedents of &lt;span class="code"&gt;NodeType&lt;/span&gt;. 
The only requirement we have on &lt;b&gt;&lt;span class="code"&gt;this&lt;/span&gt;&lt;/b&gt; is that it 
be assignable to a variable of type &lt;span class="code"&gt;NodeType&lt;/span&gt;. If we 
could express that all concrete implementations of &lt;span class="code"&gt;DoubleNode&lt;/span&gt; 
are required to be decedents of &lt;span class="code"&gt;NodeType&lt;/span&gt; this 
requirement would be met. This is the approach that
&lt;a href="http://scala.epfl.ch/"&gt;Scala&lt;/a&gt;, by
&lt;a href="http://lampwww.epfl.ch/~odersky/"&gt;Martin Odersky&lt;/a&gt; and others, took to the problem. What this might 
look like in C# is,&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract class&lt;/b&gt; DoubleNode: Node &lt;b&gt;requires&lt;/b&gt; NodeType {
            NodeType _previous;

            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; NodeType Next {
                get {
                    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;base&lt;/b&gt;.Next;
                }
                set {
                    &lt;b&gt;base&lt;/b&gt;.Next = value;
                    value._previous = &lt;b&gt;this&lt;/b&gt;;
                }
            }

            &lt;b&gt;public&lt;/b&gt; NodeType Previous { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _previous; } }
        }&lt;/pre&gt;
&lt;p&gt;This states that descendants of &lt;span class="code"&gt;DoubleNode&lt;/span&gt; are required to also be decedents of type 
&lt;span class="code"&gt;NodeType&lt;/span&gt; (or be &lt;span class="code"&gt;NodeType&lt;/span&gt;, as 
is more likely the case). Knowing this we can then remove the cast of &lt;b&gt;&lt;span class="code"&gt;this&lt;/span&gt;&lt;/b&gt; 
because we are guaranteed it is assignment compatible with &lt;span class="code"&gt;NodeType&lt;/span&gt;. &lt;/p&gt;
&lt;p&gt;Whether either of these extensions make it into C# is anyone's guess. It is 
still open whether the solutions presented are really better than the problem. Is 
requiring the cast really that bad? I will leave that up to you to answer. Also 
I glossed over some tricky problems that would need to be addressed to implement 
either option, not the least of which are the changes to the CLR.&lt;/p&gt;
&lt;p&gt;This all started off innocently enough. We wanted to implement&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;interface&lt;/b&gt; ILinkedList&amp;lt;T&amp;gt;: IEnumerable&amp;lt;T&amp;gt; {
        &lt;b&gt;void&lt;/b&gt; Add(T value);
        &lt;b&gt;void&lt;/b&gt; Clear();
    }&lt;/pre&gt;
&lt;p&gt;and,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;interface&lt;/b&gt; IDoubleLinkedList&amp;lt;T&amp;gt;: ILinkedList&amp;lt;T&amp;gt; {
        IEnumerable&amp;lt;T&amp;gt; Backwards { &lt;b&gt;get&lt;/b&gt;; }
    }&lt;/pre&gt;
&lt;p&gt;but things got complicated when we wanted to share code and 
remove casts. This innocent looking problem is devilishly hard to express in a 
type-checked object-oriented language.&lt;/p&gt;

&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/570895be-ef3d-4841-a5a2-31aa1c5f5946</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Linked List III: Double-linked list</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/fadae73e-92b8-4bf5-b262-b9267c60c8b5</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/fadae73e-92b8-4bf5-b262-b9267c60c8b5</link>
      <pubDate>Mon, 10 Apr 2006 18:26:07 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;A straight forward implementation of a double-linked list that implements the 
interface,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;interface&lt;/b&gt; IDoubleLinkedList&amp;lt;T&amp;gt;: ILinkedList&amp;lt;T&amp;gt; {
        IEnumerable&amp;lt;T&amp;gt; Backwards { get; }
    }
&lt;/pre&gt;
&lt;p&gt;can be implemented as,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; DoubleLinkedList&amp;lt;T&amp;gt;: IDoubleLinkedList&amp;lt;T&amp;gt;, IEnumerable&amp;lt;T&amp;gt; {

        &lt;b&gt;private&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Node {
            &lt;b&gt;public&lt;/b&gt; T Data;
            &lt;b&gt;public&lt;/b&gt; Node Next;
            &lt;b&gt;public&lt;/b&gt; Node Previous;
        }

        &lt;b&gt;private&lt;/b&gt; Node _last;

        &lt;b&gt;public&lt;/b&gt; DoubleLinkedList() { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add(T value) {
            Node newNode = &lt;b&gt;new&lt;/b&gt; Node();
            newNode.Data = value;
            &lt;b&gt;if&lt;/b&gt; (_last == &lt;b&gt;null&lt;/b&gt;) {
                newNode.Next = newNode;
                newNode.Previous = newNode;
                _last = newNode;
            }
            &lt;b&gt;else&lt;/b&gt; {
                newNode.Next = _last.Next;
                _last.Next.Previous = newNode;
                _last.Next = newNode;
                newNode.Previous = _last;
                _last = newNode;
            }
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Clear() {
            _last = &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerator&amp;lt;T&amp;gt; GetEnumerator() {
            &lt;b&gt;if&lt;/b&gt; (_last != &lt;b&gt;null&lt;/b&gt;) {
                Node current = _last;
                &lt;b&gt;do&lt;/b&gt; {
                    current = current.Next;
                    yield &lt;b&gt;return&lt;/b&gt; current.Data;
                } &lt;b&gt;while&lt;/b&gt; (current != _last);
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            &lt;b&gt;return&lt;/b&gt; GetEnumerator();
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerable&amp;lt;T&amp;gt; Backwards {
            get {
                &lt;b&gt;if&lt;/b&gt; (_last != &lt;b&gt;null&lt;/b&gt;) {
                    Node current = _last;
                    &lt;b&gt;do&lt;/b&gt; {
                        yield &lt;b&gt;return&lt;/b&gt; current.Data;
                        current = current.Previous;
                    } &lt;b&gt;while&lt;/b&gt; (current != _last);
                }
            }
        }
    }&lt;/pre&gt;
&lt;p&gt;With a casual comparison of this implementation to the implementation of
&lt;span class="code"&gt;LinkList&amp;lt;T&amp;gt;&lt;/span&gt; you will see that most of the methods are 
the same. &lt;span class="code"&gt;Clear()&lt;/span&gt; and &lt;span class="code"&gt;GetEnumator()&lt;/span&gt; 
are identical. &lt;span class="code"&gt;Add()&lt;/span&gt; is nearly identical; in fact, it 
would be identical if we changed the &lt;span class="code"&gt;Node&lt;/span&gt; 
implementation to&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;private&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Node {
            &lt;b&gt;public&lt;/b&gt; T Data;
            &lt;b&gt;private&lt;/b&gt; Node _next;
            &lt;b&gt;public&lt;/b&gt; Node Previous;

            &lt;b&gt;public&lt;/b&gt; Node Next {
                get {
                    &lt;b&gt;return&lt;/b&gt; _next;
                }
                set {
                    _next = value;
                    value.Previous = &lt;b&gt;this&lt;/b&gt;;
                }
            }
        }&lt;/pre&gt;
&lt;p&gt;With this change to the &lt;span class="code"&gt;Node&lt;/span&gt; class, the only 
difference between &lt;span class="code"&gt;LinkedList&amp;lt;T&amp;gt;&lt;/span&gt; and
&lt;span class="code"&gt;DoubleLinked&amp;lt;T&amp;gt;&lt;/span&gt; is the &lt;span class="code"&gt;Node&lt;/span&gt; 
class and the &lt;span class="code"&gt;Backwards&lt;/span&gt; property. It seems obvious we 
should use inheritance to share code.
&lt;span class="code"&gt;DoubleLinked&amp;lt;T&amp;gt;&lt;/span&gt; should derive from &lt;span class="code"&gt;
LinkedList&amp;lt;T&amp;gt;&lt;/span&gt;. To allow code sharing we need 
to make some changes to &lt;span class="code"&gt;LinkedList&amp;lt;T&amp;gt;&lt;/span&gt;. First we 
need to change &lt;span class="code"&gt;Node&lt;/span&gt; implementation to allow
&lt;span class="code"&gt;DoubleLink&amp;lt;T&amp;gt;&lt;/span&gt; to override the behavior of
&lt;span class="code"&gt;Next&lt;/span&gt;,&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Node {
            &lt;b&gt;public&lt;/b&gt; T Data;
            &lt;b&gt;private&lt;/b&gt; Node _next;
            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;virtual&lt;/b&gt; Node Next { get { &lt;b&gt;return&lt;/b&gt; _next; } set { _next = value; } }
        }&lt;/pre&gt;
&lt;p&gt;Then we need to add,&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;protected&lt;/b&gt; Node Last { get { &lt;b&gt;return&lt;/b&gt; _last; } }&lt;/pre&gt;
&lt;p&gt;to allow &lt;span class="code"&gt;DoubleLinked&amp;lt;T&amp;gt;&lt;/span&gt; to access to
&lt;span class="code"&gt;_last&lt;/span&gt; but not modify it. &lt;span class="code"&gt;DoubleLink&amp;lt;T&amp;gt;&lt;/span&gt; 
need &lt;span class="code"&gt;Last&lt;/span&gt; to implement &lt;span class="code"&gt;Backwards&lt;/span&gt;. Additionally we need to 
introduce&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;virtual&lt;/b&gt; Node CreateNode() { &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Node(); }&lt;/pre&gt;
&lt;p&gt;and change the first statement in the &lt;span class="code"&gt;Add()&lt;/span&gt; method to,&lt;/p&gt;
&lt;pre&gt;            Node newNode = CreateNode();&lt;/pre&gt;
&lt;p&gt;to allow &lt;span class="code"&gt;DoubleLinked&amp;lt;T&amp;gt;&lt;/span&gt; to override which class to 
create for the nodes in the list. This allows &lt;span class="code"&gt;DoubleLink&amp;lt;T&amp;gt;&lt;/span&gt; 
to create &lt;span class="code"&gt;DoubleNode&lt;/span&gt; instead of &lt;span class="code"&gt;
Node&lt;/span&gt;. With these changes we can now change the implementation of 
&lt;span class="code"&gt;DoubleLink&amp;lt;T&amp;gt;&lt;/span&gt; implementation to,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; DoubleLinkedList&amp;lt;T&amp;gt;: LinkedList&amp;lt;T&amp;gt;, IDoubleLinkedList&amp;lt;T&amp;gt; {

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; DoubleNode: Node {
            &lt;b&gt;public&lt;/b&gt; DoubleNode Previous;

            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; Node Next {
                get {
                    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;base&lt;/b&gt;.Next;
                }
                set {
                    &lt;b&gt;base&lt;/b&gt;.Next = value;
                    ((DoubleNode)value).Previous = &lt;b&gt;this&lt;/b&gt;;
                }
            }
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerable&amp;lt;T&amp;gt; Backwards {
            get {
                &lt;b&gt;if&lt;/b&gt; (Last != &lt;b&gt;null&lt;/b&gt;) {
                    DoubleNode current = (DoubleNode)Last;
                    &lt;b&gt;do&lt;/b&gt; {
                        yield &lt;b&gt;return&lt;/b&gt; current.Data;
                        current = current.Previous;
                    } &lt;b&gt;while&lt;/b&gt; (current != Last);
                }
            }
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; LinkedList&amp;lt;T&amp;gt;.Node CreateNode() { &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; DoubleNode();  }
    }&lt;/pre&gt;
&lt;p&gt;There we have it. We used inheritance to share code. Unfortunately, we had to 
use casts to get this to work. The casts show we are now running into some 
limitations in the expressiveness of the C# type 
system. We know that all the items of the list will be of type &lt;span class="code"&gt;
DoubleNode&lt;/span&gt; but we need to convince the compiler (and the CLR) with a cast 
in the &lt;b&gt;&lt;span class="code"&gt;set&lt;/span&gt;&lt;/b&gt; part of the &lt;span class="code"&gt;Next&lt;/span&gt; 
method and the &lt;span class="code"&gt;Backwards&lt;/span&gt; property. It 
would be nice to write this without casts. Next time we look at a way to rid 
ourselves of one the cast in the &lt;span class="code"&gt;Backwards&lt;/span&gt; property and the virtual &lt;span class="code"&gt;CreateNode()&lt;/span&gt; 
method. We will also look at some possible ways to increase the expressiveness 
of C#'s type system to allow us to get rid of the final cast.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>A straight forward implementation of a double-linked list that implements the 
interface,</p>
        <pre>
          <b>interface</b> IDoubleLinkedList&lt;T&gt;: ILinkedList&lt;T&gt; {
        IEnumerable&lt;T&gt; Backwards { get; }
    }
</pre>
        <p>can be implemented as,</p>
        <pre>
          <b>class</b> DoubleLinkedList&lt;T&gt;: IDoubleLinkedList&lt;T&gt;, IEnumerable&lt;T&gt; {

        <b>private</b><b>class</b> Node {
            <b>public</b> T Data;
            <b>public</b> Node Next;
            <b>public</b> Node Previous;
        }

        <b>private</b> Node _last;

        <b>public</b> DoubleLinkedList() { }

        <b>public</b><b>void</b> Add(T value) {
            Node newNode = <b>new</b> Node();
            newNode.Data = value;
            <b>if</b> (_last == <b>null</b>) {
                newNode.Next = newNode;
                newNode.Previous = newNode;
                _last = newNode;
            }
            <b>else</b> {
                newNode.Next = _last.Next;
                _last.Next.Previous = newNode;
                _last.Next = newNode;
                newNode.Previous = _last;
                _last = newNode;
            }
        }

        <b>public</b><b>void</b> Clear() {
            _last = <b>null</b>;
        }

        <b>public</b> IEnumerator&lt;T&gt; GetEnumerator() {
            <b>if</b> (_last != <b>null</b>) {
                Node current = _last;
                <b>do</b> {
                    current = current.Next;
                    yield <b>return</b> current.Data;
                } <b>while</b> (current != _last);
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            <b>return</b> GetEnumerator();
        }

        <b>public</b> IEnumerable&lt;T&gt; Backwards {
            get {
                <b>if</b> (_last != <b>null</b>) {
                    Node current = _last;
                    <b>do</b> {
                        yield <b>return</b> current.Data;
                        current = current.Previous;
                    } <b>while</b> (current != _last);
                }
            }
        }
    }</pre>
        <p>With a casual comparison of this implementation to the implementation of
<span class="code">LinkList&lt;T&gt;</span> you will see that most of the methods are 
the same. <span class="code">Clear()</span> and <span class="code">GetEnumator()</span> 
are identical. <span class="code">Add()</span> is nearly identical; in fact, it 
would be identical if we changed the <span class="code">Node</span> 
implementation to</p>
        <pre>
          <b>private</b>
          <b>class</b> Node {
            <b>public</b> T Data;
            <b>private</b> Node _next;
            <b>public</b> Node Previous;

            <b>public</b> Node Next {
                get {
                    <b>return</b> _next;
                }
                set {
                    _next = value;
                    value.Previous = <b>this</b>;
                }
            }
        }</pre>
        <p>With this change to the <span class="code">Node</span> class, the only 
difference between <span class="code">LinkedList&lt;T&gt;</span> and
<span class="code">DoubleLinked&lt;T&gt;</span> is the <span class="code">Node</span> 
class and the <span class="code">Backwards</span> property. It seems obvious we 
should use inheritance to share code.
<span class="code">DoubleLinked&lt;T&gt;</span> should derive from <span class="code">
LinkedList&lt;T&gt;</span>. To allow code sharing we need 
to make some changes to <span class="code">LinkedList&lt;T&gt;</span>. First we 
need to change <span class="code">Node</span> implementation to allow
<span class="code">DoubleLink&lt;T&gt;</span> to override the behavior of
<span class="code">Next</span>,</p>
        <pre>
          <b>protected</b>
          <b>class</b> Node {
            <b>public</b> T Data;
            <b>private</b> Node _next;
            <b>public</b><b>virtual</b> Node Next { get { <b>return</b> _next; } set { _next = value; } }
        }</pre>
        <p>Then we need to add,</p>
        <pre>
          <b>protected</b> Node Last { get { <b>return</b> _last; } }</pre>
        <p>to allow <span class="code">DoubleLinked&lt;T&gt;</span> to access to
<span class="code">_last</span> but not modify it. <span class="code">DoubleLink&lt;T&gt;</span> 
need <span class="code">Last</span> to implement <span class="code">Backwards</span>. Additionally we need to 
introduce</p>
        <pre>
          <b>protected</b>
          <b>virtual</b> Node CreateNode() { <b>return</b><b>new</b> Node(); }</pre>
        <p>and change the first statement in the <span class="code">Add()</span> method to,</p>
        <pre>            Node newNode = CreateNode();</pre>
        <p>to allow <span class="code">DoubleLinked&lt;T&gt;</span> to override which class to 
create for the nodes in the list. This allows <span class="code">DoubleLink&lt;T&gt;</span> 
to create <span class="code">DoubleNode</span> instead of <span class="code">
Node</span>. With these changes we can now change the implementation of 
<span class="code">DoubleLink&lt;T&gt;</span> implementation to,</p>
        <pre>
          <b>class</b> DoubleLinkedList&lt;T&gt;: LinkedList&lt;T&gt;, IDoubleLinkedList&lt;T&gt; {

        <b>protected</b><b>class</b> DoubleNode: Node {
            <b>public</b> DoubleNode Previous;

            <b>public</b><b>override</b> Node Next {
                get {
                    <b>return</b><b>base</b>.Next;
                }
                set {
                    <b>base</b>.Next = value;
                    ((DoubleNode)value).Previous = <b>this</b>;
                }
            }
        }

        <b>public</b> IEnumerable&lt;T&gt; Backwards {
            get {
                <b>if</b> (Last != <b>null</b>) {
                    DoubleNode current = (DoubleNode)Last;
                    <b>do</b> {
                        yield <b>return</b> current.Data;
                        current = current.Previous;
                    } <b>while</b> (current != Last);
                }
            }
        }

        <b>protected</b><b>override</b> LinkedList&lt;T&gt;.Node CreateNode() { <b>return</b><b>new</b> DoubleNode();  }
    }</pre>
        <p>There we have it. We used inheritance to share code. Unfortunately, we had to 
use casts to get this to work. The casts show we are now running into some 
limitations in the expressiveness of the C# type 
system. We know that all the items of the list will be of type <span class="code">
DoubleNode</span> but we need to convince the compiler (and the CLR) with a cast 
in the <b><span class="code">set</span></b> part of the <span class="code">Next</span> 
method and the <span class="code">Backwards</span> property. It 
would be nice to write this without casts. Next time we look at a way to rid 
ourselves of one the cast in the <span class="code">Backwards</span> property and the virtual <span class="code">CreateNode()</span> 
method. We will also look at some possible ways to increase the expressiveness 
of C#'s type system to allow us to get rid of the final cast.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/fadae73e-92b8-4bf5-b262-b9267c60c8b5</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Linked Lists II: Simple Generics</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/287726e9-3515-49c8-a1d0-79bf895c55e7</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/287726e9-3515-49c8-a1d0-79bf895c55e7</link>
      <pubDate>Sat, 01 Apr 2006 01:26:22 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;In the last entry we looked at implementing a collection class 
using a linked list data structure. This time I will show some ways to use that implementation 
to implement the generic 
interfaces introduced last time. The complete class looks like,&lt;/p&gt;

&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; LinkedList: IEnumerable {

        &lt;b&gt;private&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Node {
            &lt;b&gt;public&lt;/b&gt; &lt;b&gt;object&lt;/b&gt; Data;
            &lt;b&gt;public&lt;/b&gt; Node Next;
        }

        &lt;b&gt;private&lt;/b&gt; Node _last;

        &lt;b&gt;public&lt;/b&gt; LinkedList() { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add(&lt;b&gt;object&lt;/b&gt; value) {
            Node newNode = &lt;b&gt;new&lt;/b&gt; Node();
            newNode.Data = value;
            &lt;b&gt;if&lt;/b&gt; (_last == &lt;b&gt;null&lt;/b&gt;) {
                newNode.Next = newNode;
                _last = newNode;
            }
            &lt;b&gt;else&lt;/b&gt; {
                newNode.Next = _last.Next;
                _last.Next = newNode;
                _last = newNode;
            }
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Clear() {
            _last = &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerator GetEnumerator() {
            &lt;b&gt;if&lt;/b&gt; (_last != &lt;b&gt;null&lt;/b&gt;) {
                Node current = _last;
                &lt;b&gt;do&lt;/b&gt; {
                    current = current.Next;
                    yield &lt;b&gt;return&lt;/b&gt; current.Data;
                } &lt;b&gt;while&lt;/b&gt; (current != _last);
            }
        }
    }&lt;/pre&gt;
&lt;p&gt;The interface we want to implement is,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;interface&lt;/b&gt; ILinkedList&amp;lt;T&amp;gt;: IEnumerable&amp;lt;T&amp;gt; {
        &lt;b&gt;void&lt;/b&gt; Add(T value);
        &lt;b&gt;void&lt;/b&gt; Clear();
    }&lt;/pre&gt;
&lt;p&gt;One obvious, but bad, way to implement this interface is to 
subclass &lt;span class="code"&gt;LinkedList&lt;/span&gt; like,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; LinkedList&amp;lt;T&amp;gt;: LinkedList, ILinkedList&amp;lt;T&amp;gt;, IEnumerable&amp;lt;T&amp;gt; {

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add(T value) { &lt;b&gt;base&lt;/b&gt;.Add(value); }

        IEnumerator&amp;lt;T&amp;gt; IEnumerable&amp;lt;T&amp;gt;.GetEnumerator() {
            &lt;b&gt;foreach&lt;/b&gt; (T item &lt;b&gt;in&lt;/b&gt; &lt;b&gt;this&lt;/b&gt;)
                yield &lt;b&gt;return&lt;/b&gt; item;
        }
    }&lt;/pre&gt;
&lt;p&gt;The reason this is so bad is because given,&lt;/p&gt;
&lt;pre&gt;    LinkedList&amp;lt;&lt;b&gt;string&lt;/b&gt;&amp;gt; list = &lt;b&gt;new&lt;/b&gt; LinkedList&amp;lt;&lt;b&gt;string&lt;/b&gt;&amp;gt;();&lt;/pre&gt;
&lt;p&gt;the following statements are both legal,&lt;/p&gt;
&lt;pre&gt;    list.Add("some string");
    list.Add(1);&lt;/pre&gt;
&lt;p&gt;The reason is because the first statement calls the &lt;span class="code"&gt;
LinkedList&amp;lt;T&amp;gt;.Add(T value)&lt;/span&gt; above, as expected, but the second will call
&lt;span class="code"&gt;LinkedList.Add(&lt;b&gt;object&lt;/b&gt; value)&lt;/span&gt;, because the 
generic &lt;span class="code"&gt;Add&lt;/span&gt; is overloaded with the the non-generic version. Even if it 
was obscured by the new &lt;span class="code"&gt;Add&lt;/span&gt; method you could still access 
&lt;span class="code"&gt;Add(&lt;b&gt;object&lt;/b&gt; value)&lt;/span&gt; by,&lt;/p&gt;
&lt;pre&gt;    LinkedList list2 = list;
    list2.Add(1);&lt;/pre&gt;
&lt;p&gt;We wanted the compiler to be able to flag when we add a 
non-string to the list as an error; this implementation doesn't do that. A slightly better approach is 
to use delegation instead of 
inheritance, as in,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; LinkedListD&amp;lt;T&amp;gt;: ILinkedList&amp;lt;T&amp;gt;, IEnumerable&amp;lt;T&amp;gt; {
        &lt;b&gt;private&lt;/b&gt; LinkedList _list = &lt;b&gt;new&lt;/b&gt; LinkedList();

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add(T value) { _list.Add(value); }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Clear() { _list.Clear(); }

        IEnumerator&amp;lt;T&amp;gt; IEnumerable&amp;lt;T&amp;gt;.GetEnumerator() {
            &lt;b&gt;foreach&lt;/b&gt; (T item &lt;b&gt;in&lt;/b&gt; _list)
                yield &lt;b&gt;return&lt;/b&gt; item;
        }

        IEnumerator IEnumerable.GetEnumerator() {
            &lt;b&gt;return&lt;/b&gt; _list.GetEnumerator();
        }
    }&lt;/pre&gt;
&lt;p&gt;But this is still not good enough because, not only can we no longer inherit the implementation of &lt;span class="code"&gt;
Clear()&lt;/span&gt; and &lt;span class="code"&gt;GetEnumerator()&lt;/span&gt;, we also use 
more memory by having to create an instance of &lt;span class="code"&gt;LinkedList&lt;/span&gt; 
to wrap. Additionally, if we wanted to add an &lt;span class="code"&gt;Insert()&lt;/span&gt; 
method, that put values at the beginning of the list instead of the end, we would have to 
manually update &lt;span class="code"&gt;LinkedListD&lt;/span&gt;. A much better approach is to scrap the first implementation and 
re-implement the class as a generic class, as in,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; LinkedList&amp;lt;T&amp;gt;: ILinkedList&amp;lt;T&amp;gt;, IEnumerable&amp;lt;T&amp;gt; {
        &lt;b&gt;private&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Node {
            &lt;b&gt;public&lt;/b&gt; T Data;
            &lt;b&gt;public&lt;/b&gt; Node Next;
        }

        &lt;b&gt;private&lt;/b&gt; Node _last;

        &lt;b&gt;public&lt;/b&gt; LinkedList() { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add(T value) {
            Node newNode = &lt;b&gt;new&lt;/b&gt; Node();
            newNode.Data = value;
            &lt;b&gt;if&lt;/b&gt; (_last == &lt;b&gt;null&lt;/b&gt;) {
                newNode.Next = newNode;
                _last = newNode;
            }
            &lt;b&gt;else&lt;/b&gt; {
                newNode.Next = _last.Next;
                _last.Next = newNode;
                _last = newNode;
            }
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Clear() {
            _last = &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;public&lt;/b&gt; IEnumerator&amp;lt;T&amp;gt; GetEnumerator() {
            &lt;b&gt;if&lt;/b&gt; (_last != &lt;b&gt;null&lt;/b&gt;) {
                Node current = _last;
                &lt;b&gt;do&lt;/b&gt; {
                    current = current.Next;
                    yield &lt;b&gt;return&lt;/b&gt; current.Data;
                } &lt;b&gt;while&lt;/b&gt; (current != _last);
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            &lt;b&gt;return&lt;/b&gt; GetEnumerator();
        }
    }&lt;/pre&gt;
&lt;p&gt;With this approach, if we really need a list with data type &lt;b&gt;
&lt;span class="code"&gt;object&lt;/span&gt;&lt;/b&gt;, we can always use &lt;span class="code"&gt;LinkedList&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt;&lt;/span&gt; 
which gives us a class essentially the same class as what we started with.&amp;nbsp; 
Sometimes it is just better to rewrite. Note that the BCL took a similar 
approach. List&amp;lt;T&amp;gt; and Dictionary&amp;lt;K,T&amp;gt; do not inherit from ArrayList and 
Hashtable.&lt;/p&gt;
&lt;p&gt;Next time I will try a first crack at implementing &lt;span class="code"&gt;
IDoubleLinkedList&amp;lt;T&amp;gt;&lt;/span&gt;.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/287726e9-3515-49c8-a1d0-79bf895c55e7</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Linked Lists I: Simple implementation</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/23df347a-fa30-4429-96a5-68d1a1ed27ad</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/23df347a-fa30-4429-96a5-68d1a1ed27ad</link>
      <pubDate>Sun, 26 Mar 2006 01:07:54 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Last time I investigated several ways to implement an expression evaluator 
using a procedural style and several object oriented styles. I used this to 
demonstrate a data structure that doesn't lend itself well to being representing 
in an object oriented style. Another problematic structure is a linked list. It 
is not so much the linked list itself but writing it is such a way that is both 
type safe and also supports code sharing with, say, a doubly-linked list. What I want to implement is a class 
that implements the following interface.&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;b&gt;interface&lt;/b&gt; ILinkedList&amp;lt;T&amp;gt;: IEnumerable&amp;lt;T&amp;gt; {
        &lt;b&gt;void&lt;/b&gt; Add(T value);
        &lt;b&gt;void&lt;/b&gt; Clear();
    }&lt;/pre&gt;
    
&lt;p&gt;And then a subclass of that class that implements,&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;b&gt;interface&lt;/b&gt; IDoubleLinkedList&amp;lt;T&amp;gt;: ILinkedList&amp;lt;T&amp;gt; {
        IEnumerable&amp;lt;T&amp;gt; Backwards { &lt;b&gt;get&lt;/b&gt;; }
    }&lt;/pre&gt;
&lt;p&gt;which inherits the implementation of &lt;span class="code"&gt;Add()&lt;/span&gt; and 
&lt;span class="code"&gt;Clear()&lt;/span&gt; and efficiently 
implements &lt;span class="code"&gt;Backwards&lt;/span&gt;. For now, I will ignore the generic parameter and just 
implement a simple linked list. First, lets create a Node that will form the 
nodes of the linked list.&lt;/p&gt; 
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; Node {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;object&lt;/b&gt; Data;
        &lt;b&gt;public&lt;/b&gt; Node Next;
    }&lt;/pre&gt;
&lt;p&gt;A linked list consists of a list of these nodes.&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; LinkedList: IEnumerable {
        Node _last;
    }&lt;/pre&gt;
&lt;p&gt;When an item is added to the list we will create a new node to hold it and 
create circular list where the &lt;span class="code"&gt;_last&lt;/span&gt; instance variable
will always point to the last node. This way we can quickly find both the
last node and the first node of the list because, since the list is circular, 
the last node's &lt;span class="code"&gt;Next&lt;/span&gt; field points to the first node. 
The reason I chose this particular way of implementing a linked list will be 
obvious if you have watched
&lt;a href="http://channel9.msdn.com/ShowPost.aspx?PostID=159952#159952"&gt;this video&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Add(&lt;b&gt;object&lt;/b&gt; value) {
            Node newNode = &lt;b&gt;new&lt;/b&gt; Node();
            newNode.Data = value;
            &lt;b&gt;if&lt;/b&gt; (_last == &lt;b&gt;null&lt;/b&gt;) {
                newNode.Next = newNode;
                _last = newNode;
            }
            &lt;b&gt;else&lt;/b&gt; {
                newNode.Next = _last.Next;
                _last.Next = newNode;
                _last = newNode;
            }
        }&lt;/pre&gt;
&lt;p&gt;Clearing the list is simple, just forget all the nodes.&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Clear() {
            _last = &lt;b&gt;null&lt;/b&gt;;
        }&lt;/pre&gt;
&lt;p&gt;I implemented &lt;span class="code"&gt;IEnumerable&lt;/span&gt; interface by using the new 
&lt;b&gt;&lt;span class="code"&gt;yield&lt;/span&gt;&lt;/b&gt; feature of C# 2.0. 
I start at the last node of the list, walk forward (to the first node) and yield an
element, each successive loop will yield another element until we have yielded the
last element (which is pointed to by &lt;span class="code"&gt;_last&lt;/span&gt;).&lt;/p&gt;
&lt;pre&gt;        &lt;b&gt;public&lt;/b&gt; IEnumerator GetEnumerator() {
            &lt;b&gt;if&lt;/b&gt; (_last != &lt;b&gt;null&lt;/b&gt;) {
                Node current = _last;
                &lt;b&gt;do&lt;/b&gt; {
                    current = current.Next;
                    &lt;b&gt;yield&lt;/b&gt; &lt;b&gt;return&lt;/b&gt; current.Data;
                } &lt;b&gt;while&lt;/b&gt; (current != _last);
            }
        }&lt;/pre&gt;
&lt;p&gt;Now I have a reasonable implementation of a linked list. Next time we will 
take several different approaches to implement the interfaces defined above.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Last time I investigated several ways to implement an expression evaluator 
using a procedural style and several object oriented styles. I used this to 
demonstrate a data structure that doesn't lend itself well to being representing 
in an object oriented style. Another problematic structure is a linked list. It 
is not so much the linked list itself but writing it is such a way that is both 
type safe and also supports code sharing with, say, a doubly-linked list. What I want to implement is a class 
that implements the following interface.</p>
        <pre class="code">
          <b>interface</b> ILinkedList&lt;T&gt;: IEnumerable&lt;T&gt; {
        <b>void</b> Add(T value);
        <b>void</b> Clear();
    }</pre>
        <p>And then a subclass of that class that implements,</p>
        <pre class="code">
          <b>interface</b> IDoubleLinkedList&lt;T&gt;: ILinkedList&lt;T&gt; {
        IEnumerable&lt;T&gt; Backwards { <b>get</b>; }
    }</pre>
        <p>which inherits the implementation of <span class="code">Add()</span> and 
<span class="code">Clear()</span> and efficiently 
implements <span class="code">Backwards</span>. For now, I will ignore the generic parameter and just 
implement a simple linked list. First, lets create a Node that will form the 
nodes of the linked list.</p>
        <pre>
          <b>class</b> Node {
        <b>public</b><b>object</b> Data;
        <b>public</b> Node Next;
    }</pre>
        <p>A linked list consists of a list of these nodes.</p>
        <pre>
          <b>class</b> LinkedList: IEnumerable {
        Node _last;
    }</pre>
        <p>When an item is added to the list we will create a new node to hold it and 
create circular list where the <span class="code">_last</span> instance variable
will always point to the last node. This way we can quickly find both the
last node and the first node of the list because, since the list is circular, 
the last node's <span class="code">Next</span> field points to the first node. 
The reason I chose this particular way of implementing a linked list will be 
obvious if you have watched
<a href="http://channel9.msdn.com/ShowPost.aspx?PostID=159952#159952">this video</a>.</p>
        <pre>
          <b>public</b>
          <b>void</b> Add(<b>object</b> value) {
            Node newNode = <b>new</b> Node();
            newNode.Data = value;
            <b>if</b> (_last == <b>null</b>) {
                newNode.Next = newNode;
                _last = newNode;
            }
            <b>else</b> {
                newNode.Next = _last.Next;
                _last.Next = newNode;
                _last = newNode;
            }
        }</pre>
        <p>Clearing the list is simple, just forget all the nodes.</p>
        <pre>
          <b>public</b>
          <b>void</b> Clear() {
            _last = <b>null</b>;
        }</pre>
        <p>I implemented <span class="code">IEnumerable</span> interface by using the new 
<b><span class="code">yield</span></b> feature of C# 2.0. 
I start at the last node of the list, walk forward (to the first node) and yield an
element, each successive loop will yield another element until we have yielded the
last element (which is pointed to by <span class="code">_last</span>).</p>
        <pre>
          <b>public</b> IEnumerator GetEnumerator() {
            <b>if</b> (_last != <b>null</b>) {
                Node current = _last;
                <b>do</b> {
                    current = current.Next;
                    <b>yield</b><b>return</b> current.Data;
                } <b>while</b> (current != _last);
            }
        }</pre>
        <p>Now I have a reasonable implementation of a linked list. Next time we will 
take several different approaches to implement the interfaces defined above.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/23df347a-fa30-4429-96a5-68d1a1ed27ad</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>A Tour of XAML - Part VI - Forward Compatibility (continued)</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/12d47e2d-1767-4a3c-8802-3d5f0a624f66</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/12d47e2d-1767-4a3c-8802-3d5f0a624f66</link>
      <pubDate>Sat, 18 Mar 2006 17:25:10 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Returning to the Party example we where using, lets say you want to author a 
document that has 10 kazoos when the version 2 assembly is present but replaces 
them with 4 extra balloons if we only have the version 1 assembly. This can be 
written using a markup compatibility AlternateContent block. This might look 
like,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
        &amp;lt;mc:AlternateContent&amp;gt;
            &amp;lt;mc:Choice Requires="v2"&amp;gt;
                &amp;lt;Balloon Color="Green" Shape="Dog" /&amp;gt;
                &amp;lt;v2:Favor Kind="Kazoo" Quantity="10" /&amp;gt;
            &amp;lt;/mc:Choice&amp;gt;
            &amp;lt;mc:Fallback&amp;gt;
                &amp;lt;Balloon Color="Green" /&amp;gt;
                &amp;lt;Balloon Color="Violet" /&amp;gt;
                &amp;lt;Balloon Color="Orange" /&amp;gt;
                &amp;lt;Balloon Color="Yellow" /&amp;gt;
            &amp;lt;/mc:Fallback&amp;gt;
        &amp;lt;/mc:AlternateContent&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;

&lt;p&gt;When the version 1 assembly is present this is interpreted as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party xmln="...assembly-v1-uri..."&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
        &amp;lt;Balloon Color="Green" /&amp;gt;
        &amp;lt;Balloon Color="Violet" /&amp;gt;
        &amp;lt;Balloon Color="Orange" /&amp;gt;
        &amp;lt;Balloon Color="Yellow" /&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;

&lt;p&gt;but in version 2 it is interpreted as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party xmlns="...assembly-v2-uri..."&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
        &amp;lt;Balloon Color="Green" Shape="Dog" /&amp;gt;
        &amp;lt;Favor Kind="Kazoo" Quantity="10" /&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;

&lt;p&gt;The content of the Choice element is used when the 
v2 namespace is available because it is mentioned in the Requires attribute. 
This corresponds to when the version 2 assembly is in use. If v2 is not 
available, the content of the Fallback element is used. AlternateContent 
supports an arbitrary list of Choice elements and the Requires can be an 
arbitrary list of prefix names. &lt;/p&gt;
&lt;p&gt;Of course exchanging balloons for kazoos is not a very compelling example. For a more practical example, let's 
assume we have following classes in version 1 of an assembly,&lt;/p&gt;
&lt;pre&gt;    [ContentProperty("Content")]
    &lt;b&gt;class&lt;/b&gt; Paragraph {
        &lt;b&gt;private&lt;/b&gt; List&amp;lt;Inline&amp;gt; _content = new List&amp;lt;Inline&amp;gt;();
        &lt;b&gt;public&lt;/b&gt; List&amp;lt;Inline&amp;gt; Content { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _content; } }
    }
    
    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Inline { }
    
    [ContentProperty("Text")]
    &lt;b&gt;class&lt;/b&gt; Run : Inline {
        &lt;b&gt;string&lt;/b&gt; _text;
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;string&lt;/b&gt; Text { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _text; } &lt;b&gt;set&lt;/b&gt; { _text = value; } }
    }
    
    &lt;b&gt;class&lt;/b&gt; Image : Inline {
        &lt;b&gt;private&lt;/b&gt; Uri _source;
        &lt;b&gt;public&lt;/b&gt; Uri Source { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _source; } &lt;b&gt;set&lt;/b&gt; { _source = value; } }
    }&lt;/pre&gt;

&lt;p&gt;Now in the version 2 assembly we add a new class that looks like,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;class&lt;/b&gt; Graph : Inline {
        &lt;b&gt;private&lt;/b&gt; List&amp;lt;Point&amp;gt; _points = &lt;b&gt;new&lt;/b&gt; List&amp;lt;Point&amp;gt;();
        &lt;b&gt;public&lt;/b&gt; List&amp;lt;Point&amp;gt; Points { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _points; } }
    }&lt;/pre&gt;

&lt;p&gt;Now we want to write a paragraph that uses the new Graph class when version 2 
of the assembly is present, because, for example, it scales better, but in 
version 1 we will just use a bitmap image of the graph. This might 
look like,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Paragraph mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&amp;gt;
        &amp;lt;Run&amp;gt;The sales projects for the next quarter are&amp;lt;/Run&amp;gt;
        &amp;lt;AlternateContent&amp;gt;
            &amp;lt;mc:Choice Requires="v2"&amp;gt;
                &amp;lt;v2:Graph Data="1,2 2,3 3,5" /&amp;gt;
            &amp;lt;/mc:Choice&amp;gt;
            &amp;lt;mc:Fallback&amp;gt;
                 &amp;lt;Image Source="SalesData.jpg&amp;quot; /&amp;gt;
            &amp;lt;/mc:Fallback&amp;gt;
        &amp;lt;/mc:AlternateContent&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;

&lt;p&gt;When the version 2 assembly is present, this is interpreted as,&lt;/p&gt;

&lt;pre&gt;    &amp;lt;Paragraph xmlns="...assembly-v2-uri..."&amp;gt;
        &amp;lt;Run&amp;gt;The sales projects for the next quarter are&amp;lt;/Run&amp;gt;
        &amp;lt;Graph Data="1,2 2,3 3,5" /&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;
    
&lt;p&gt;but, when only version 1 available, it is interpreted as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Paragraph xmln="...assembly-v1-uri..."&amp;gt;
        &amp;lt;Run&amp;gt;The sales projects for the next quarter are&amp;lt;/Run&amp;gt;
        &amp;lt;Image Source="SalesData.jpg&amp;quot; /&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;
    
&lt;p&gt;using the bitmap instead of of the Graph class. This allows a document author 
to produce a file that takes advantage of a new feature, such as Graph with its 
better scaling properties, but still allows older versions to see a the graph at 
a lower fidelity.&lt;/p&gt;
    
&lt;p&gt;These classes make a better example for another feature of markup 
compatibility, the ProcessContent attribute. Let's add another class in the 
version 2 assembly,&lt;/p&gt;
&lt;pre&gt;    [ContentProperty("Content")]
    &lt;b&gt;class&lt;/b&gt; Glow : Inline {
        &lt;b&gt;private&lt;/b&gt; List&amp;lt;Inline&amp;gt; _content = new List&amp;lt;Inline&amp;gt;();
        &lt;b&gt;public&lt;/b&gt; List&amp;lt;Inline&amp;gt; Content { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _content; } }
    }&lt;/pre&gt;
    
&lt;p&gt;This class allows us to make the content to appear to glow when drawn. This 
allows us to write a document that looks like,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Paragraph mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&amp;gt;
        &amp;lt;Run&amp;gt;The word&amp;lt;/Run&amp;gt; 
        &amp;lt;v2:Glow&amp;gt;&amp;lt;Run&amp;gt;glow&amp;lt;/Run&amp;gt;&amp;lt;/v2:Glow&amp;gt; 
        &amp;lt;Run&amp;gt;will appear to glow when it viewed with version 2.&amp;lt;/Run&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;
    
&lt;p&gt;Unfortunately, with version 1, this is interpreted as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Paragraph xmln="...assembly-v1-uri..."&amp;gt;
        &amp;lt;Run&amp;gt;The word&amp;lt;/Run&amp;gt; 
        &amp;lt;Run&amp;gt;will appear to glow when it viewed with version 2.&amp;lt;/Run&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;
&lt;p&gt;The word &amp;quot;glow&amp;quot; disappeared because, by default, when an element is ignored its 
content is ignored as well. This default can be modified by using the ProcessContent attribute. If the original document is modified to be,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Paragraph 
      mc:Ignorable="v2" 
      mc:ProcessContent="v2:Glow"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&amp;gt;
        &amp;lt;Run&amp;gt;The word&amp;lt;/Run&amp;gt; 
        &amp;lt;v2:Glow&amp;gt;&amp;lt;Run&amp;gt;glow&amp;lt;/Run&amp;gt;&amp;lt;/v2:Glow&amp;gt; 
        &amp;lt;Run&amp;gt;will appear to glow when it viewed with version 2.&amp;lt;/Run&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;
&lt;p&gt;This will tell the reader to just ignore the tags for Glow if it doesn't 
understand it but leave the content intact. This is then interpreted as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Paragraph xmln="...assembly-v1-uri..."&amp;gt;
        &amp;lt;Run&amp;gt;The word&amp;lt;/Run&amp;gt; 
        &amp;lt;Run&amp;gt;glow&amp;lt;/Run&amp;gt;
        &amp;lt;Run&amp;gt;will appear to glow when it viewed with version 2.&amp;lt;/Run&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;

&lt;p&gt;for version 1, and will be interpreted as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Paragraph xmlns:v2="...assembly-v2-uri..."&amp;gt;
        &amp;lt;Run&amp;gt;The word&amp;lt;/Run&amp;gt; 
        &amp;lt;Glow&amp;gt;&amp;lt;Run&amp;gt;glow&amp;lt;/Run&amp;gt;&amp;lt;/Glow&amp;gt; 
        &amp;lt;Run&amp;gt;will appear to glow when it viewed with version 2.&amp;lt;/Run&amp;gt;
    &amp;lt;/Paragraph&amp;gt;&lt;/pre&gt;

&lt;p&gt;when version 2 is present which is exactly what we wanted.&lt;/p&gt;
&lt;p&gt;In general, forward compatibility allows previous versions of a document 
reader to read a document intended for later versions and render the content at 
a lower fidelity. This helps immensely when deploying a newer version of an 
assembly. During initial deployment it might not be that wide spread. You can 
have your users start taking advantage of the new features immediately because 
older versions will still be able to read newer documents, at a lower fidelity, 
even when they don't have the new assembly.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Returning to the Party example we where using, lets say you want to author a 
document that has 10 kazoos when the version 2 assembly is present but replaces 
them with 4 extra balloons if we only have the version 1 assembly. This can be 
written using a markup compatibility AlternateContent block. This might look 
like,</p>
        <pre>    &lt;Party mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
        &lt;mc:AlternateContent&gt;
            &lt;mc:Choice Requires="v2"&gt;
                &lt;Balloon Color="Green" Shape="Dog" /&gt;
                &lt;v2:Favor Kind="Kazoo" Quantity="10" /&gt;
            &lt;/mc:Choice&gt;
            &lt;mc:Fallback&gt;
                &lt;Balloon Color="Green" /&gt;
                &lt;Balloon Color="Violet" /&gt;
                &lt;Balloon Color="Orange" /&gt;
                &lt;Balloon Color="Yellow" /&gt;
            &lt;/mc:Fallback&gt;
        &lt;/mc:AlternateContent&gt;
    &lt;/Party&gt;</pre>
        <p>When the version 1 assembly is present this is interpreted as,</p>
        <pre>    &lt;Party xmln="...assembly-v1-uri..."&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
        &lt;Balloon Color="Green" /&gt;
        &lt;Balloon Color="Violet" /&gt;
        &lt;Balloon Color="Orange" /&gt;
        &lt;Balloon Color="Yellow" /&gt;
    &lt;/Party&gt;</pre>
        <p>but in version 2 it is interpreted as,</p>
        <pre>    &lt;Party xmlns="...assembly-v2-uri..."&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
        &lt;Balloon Color="Green" Shape="Dog" /&gt;
        &lt;Favor Kind="Kazoo" Quantity="10" /&gt;
    &lt;/Party&gt;</pre>
        <p>The content of the Choice element is used when the 
v2 namespace is available because it is mentioned in the Requires attribute. 
This corresponds to when the version 2 assembly is in use. If v2 is not 
available, the content of the Fallback element is used. AlternateContent 
supports an arbitrary list of Choice elements and the Requires can be an 
arbitrary list of prefix names. </p>
        <p>Of course exchanging balloons for kazoos is not a very compelling example. For a more practical example, let's 
assume we have following classes in version 1 of an assembly,</p>
        <pre>    [ContentProperty("Content")]
    <b>class</b> Paragraph {
        <b>private</b> List&lt;Inline&gt; _content = new List&lt;Inline&gt;();
        <b>public</b> List&lt;Inline&gt; Content { <b>get</b> { <b>return</b> _content; } }
    }
    
    <b>abstract</b><b>class</b> Inline { }
    
    [ContentProperty("Text")]
    <b>class</b> Run : Inline {
        <b>string</b> _text;
        <b>public</b><b>string</b> Text { <b>get</b> { <b>return</b> _text; } <b>set</b> { _text = value; } }
    }
    
    <b>class</b> Image : Inline {
        <b>private</b> Uri _source;
        <b>public</b> Uri Source { <b>get</b> { <b>return</b> _source; } <b>set</b> { _source = value; } }
    }</pre>
        <p>Now in the version 2 assembly we add a new class that looks like,</p>
        <pre>
          <b>class</b> Graph : Inline {
        <b>private</b> List&lt;Point&gt; _points = <b>new</b> List&lt;Point&gt;();
        <b>public</b> List&lt;Point&gt; Points { <b>get</b> { <b>return</b> _points; } }
    }</pre>
        <p>Now we want to write a paragraph that uses the new Graph class when version 2 
of the assembly is present, because, for example, it scales better, but in 
version 1 we will just use a bitmap image of the graph. This might 
look like,</p>
        <pre>    &lt;Paragraph mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&gt;
        &lt;Run&gt;The sales projects for the next quarter are&lt;/Run&gt;
        &lt;AlternateContent&gt;
            &lt;mc:Choice Requires="v2"&gt;
                &lt;v2:Graph Data="1,2 2,3 3,5" /&gt;
            &lt;/mc:Choice&gt;
            &lt;mc:Fallback&gt;
                 &lt;Image Source="SalesData.jpg" /&gt;
            &lt;/mc:Fallback&gt;
        &lt;/mc:AlternateContent&gt;
    &lt;/Paragraph&gt;</pre>
        <p>When the version 2 assembly is present, this is interpreted as,</p>
        <pre>    &lt;Paragraph xmlns="...assembly-v2-uri..."&gt;
        &lt;Run&gt;The sales projects for the next quarter are&lt;/Run&gt;
        &lt;Graph Data="1,2 2,3 3,5" /&gt;
    &lt;/Paragraph&gt;</pre>
        <p>but, when only version 1 available, it is interpreted as,</p>
        <pre>    &lt;Paragraph xmln="...assembly-v1-uri..."&gt;
        &lt;Run&gt;The sales projects for the next quarter are&lt;/Run&gt;
        &lt;Image Source="SalesData.jpg" /&gt;
    &lt;/Paragraph&gt;</pre>
        <p>using the bitmap instead of of the Graph class. This allows a document author 
to produce a file that takes advantage of a new feature, such as Graph with its 
better scaling properties, but still allows older versions to see a the graph at 
a lower fidelity.</p>
        <p>These classes make a better example for another feature of markup 
compatibility, the ProcessContent attribute. Let's add another class in the 
version 2 assembly,</p>
        <pre>    [ContentProperty("Content")]
    <b>class</b> Glow : Inline {
        <b>private</b> List&lt;Inline&gt; _content = new List&lt;Inline&gt;();
        <b>public</b> List&lt;Inline&gt; Content { <b>get</b> { <b>return</b> _content; } }
    }</pre>
        <p>This class allows us to make the content to appear to glow when drawn. This 
allows us to write a document that looks like,</p>
        <pre>    &lt;Paragraph mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&gt;
        &lt;Run&gt;The word&lt;/Run&gt; 
        &lt;v2:Glow&gt;&lt;Run&gt;glow&lt;/Run&gt;&lt;/v2:Glow&gt; 
        &lt;Run&gt;will appear to glow when it viewed with version 2.&lt;/Run&gt;
    &lt;/Paragraph&gt;</pre>
        <p>Unfortunately, with version 1, this is interpreted as,</p>
        <pre>    &lt;Paragraph xmln="...assembly-v1-uri..."&gt;
        &lt;Run&gt;The word&lt;/Run&gt; 
        &lt;Run&gt;will appear to glow when it viewed with version 2.&lt;/Run&gt;
    &lt;/Paragraph&gt;</pre>
        <p>The word "glow" disappeared because, by default, when an element is ignored its 
content is ignored as well. This default can be modified by using the ProcessContent attribute. If the original document is modified to be,</p>
        <pre>    &lt;Paragraph 
      mc:Ignorable="v2" 
      mc:ProcessContent="v2:Glow"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&gt;
        &lt;Run&gt;The word&lt;/Run&gt; 
        &lt;v2:Glow&gt;&lt;Run&gt;glow&lt;/Run&gt;&lt;/v2:Glow&gt; 
        &lt;Run&gt;will appear to glow when it viewed with version 2.&lt;/Run&gt;
    &lt;/Paragraph&gt;</pre>
        <p>This will tell the reader to just ignore the tags for Glow if it doesn't 
understand it but leave the content intact. This is then interpreted as,</p>
        <pre>    &lt;Paragraph xmln="...assembly-v1-uri..."&gt;
        &lt;Run&gt;The word&lt;/Run&gt; 
        &lt;Run&gt;glow&lt;/Run&gt;
        &lt;Run&gt;will appear to glow when it viewed with version 2.&lt;/Run&gt;
    &lt;/Paragraph&gt;</pre>
        <p>for version 1, and will be interpreted as,</p>
        <pre>    &lt;Paragraph xmlns:v2="...assembly-v2-uri..."&gt;
        &lt;Run&gt;The word&lt;/Run&gt; 
        &lt;Glow&gt;&lt;Run&gt;glow&lt;/Run&gt;&lt;/Glow&gt; 
        &lt;Run&gt;will appear to glow when it viewed with version 2.&lt;/Run&gt;
    &lt;/Paragraph&gt;</pre>
        <p>when version 2 is present which is exactly what we wanted.</p>
        <p>In general, forward compatibility allows previous versions of a document 
reader to read a document intended for later versions and render the content at 
a lower fidelity. This helps immensely when deploying a newer version of an 
assembly. During initial deployment it might not be that wide spread. You can 
have your users start taking advantage of the new features immediately because 
older versions will still be able to read newer documents, at a lower fidelity, 
even when they don't have the new assembly.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/12d47e2d-1767-4a3c-8802-3d5f0a624f66</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>A Tour of XAML V: Forward compatibility</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/25290e01-64e5-49dd-919f-374f2162542c</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/25290e01-64e5-49dd-919f-374f2162542c</link>
      <pubDate>Sun, 12 Feb 2006 18:28:43 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;As we saw last time, XAML supports backwards compatibility. XAML also 
supports forward compatibility. Forward compatibility is easiest to understand from through a set of examples. Take the balloon 
example before. Say we want to write a XAML document that says, when you have 
the version 2 assembly, I want a dog shaped balloon. If, however, you only have 
the version 1 assembly, a default shaped balloon is fine. In other words, I want 
a document that contains some version 2 specific references in it but it is OK to just ignore 
them when you have a version 1 assembly. In our example, we want to mark the Shape property some way that 
the version 1 reader will know it can ignore the property. In XAML you can use 
the markup compatibility namespace to accomplish this. You can write,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Balloon Color="Red" v2:Shape="Dog" 
      xmlns="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"
      mc:Ignorable="v2" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;This takes advantage of the Ignorable attribute of from the markup 
compatibility namespace. mc:Ignorable=&amp;quot;v2&amp;quot; says that any attribute or element 
from the namespace 
associated with the &amp;quot;v2&amp;quot; prefix can be ignored and you would still have a 
document that would have an acceptable meaning. If a XAML reader only has the 
version 1 assembly, it would interpreted the above document as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Balloon Color="Red" xmlns="...assembly-v1-uri..."  /&amp;gt;&lt;/pre&gt;
&lt;p&gt;If the reader has the version 2 assembly, it would interpret it as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Balloon Color="Red" Shape="Dog" xmlns="...assembly-v2-uri..." /&amp;gt;&lt;/pre&gt;
&lt;p&gt;mc:Ignorable can also applies to elements. To see example of this lets define a class, Party, that is 
define as,&lt;/p&gt;
&lt;pre&gt;    [ContentProperty("Balloons")]
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Party {
        List&amp;lt;Balloon&amp;gt; _balloons = &lt;b&gt;new&lt;/b&gt; List&amp;lt;Balloon&amp;gt;();
        &lt;b&gt;public&lt;/b&gt; List&amp;lt;Balloon&amp;gt; Balloons { &lt;b&gt;get&lt;/b&gt; { return _balloons; } 
    }&lt;/pre&gt;
&lt;p&gt;This allows us to define a Party instance that contains balloons. For this 
example, let's assume that Party was defined in the Version 1 assembly and is 
unmodified in the Version 2 assembly. We can then 
write a XAML document that looks like,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party xmln="...assembly-v1-uri..."&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;
&lt;p&gt;We can now also write a document that will include a third dog shaped balloon 
but only if we are using the version 2 assembly, and not include if we are still 
using version 1. It looks like,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
        &amp;lt;v2:Balloon Color="Green" Shape="Dog" /&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;

&lt;p&gt;This will be interpreted exactly as the prior document when reading it with 
version 1. With version 2, however, it would be interpreted as if it was,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party xmlns="...assembly-v2-uri..."&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
        &amp;lt;Balloon Color="Green" Shape="Dog" /&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;

&lt;p&gt;We can also add a new a new class, such as Favor, that can be used in a 
document such as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
        &amp;lt;v2:Balloon Color="Green" Shape="Dog" /&amp;gt;
        &amp;lt;v2:Favor Kind="Kazoo" Quantity="10" /&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;

&lt;p&gt;This doesn't affect the version 1 interpretation of the document, but adds 10 kazoos to 
the version 2 interpretation. If the author determines that the kazoos are 
really necessary to the interpretation of either the reference to v1 can be 
removed and the document rewritten to,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Party xmlns="...assembly-v2-uri..."&amp;gt;
        &amp;lt;Balloon Color="Red" /&amp;gt;
        &amp;lt;Balloon Color="Blue" /&amp;gt;
        &amp;lt;Balloon Color="Green" Shape="Dog" /&amp;gt;
        &amp;lt;Favor Kind="Kazoo" Quantity="10" /&amp;gt;
    &amp;lt;/Party&amp;gt;&lt;/pre&gt;

&lt;p&gt;or the the ignorable attribute can just be removed which amounts to an 
equivalent document given subsumption described in the previous entry.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>As we saw last time, XAML supports backwards compatibility. XAML also 
supports forward compatibility. Forward compatibility is easiest to understand from through a set of examples. Take the balloon 
example before. Say we want to write a XAML document that says, when you have 
the version 2 assembly, I want a dog shaped balloon. If, however, you only have 
the version 1 assembly, a default shaped balloon is fine. In other words, I want 
a document that contains some version 2 specific references in it but it is OK to just ignore 
them when you have a version 1 assembly. In our example, we want to mark the Shape property some way that 
the version 1 reader will know it can ignore the property. In XAML you can use 
the markup compatibility namespace to accomplish this. You can write,</p>
        <pre>    &lt;Balloon Color="Red" v2:Shape="Dog" 
      xmlns="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"
      mc:Ignorable="v2" /&gt;</pre>
        <p>This takes advantage of the Ignorable attribute of from the markup 
compatibility namespace. mc:Ignorable="v2" says that any attribute or element 
from the namespace 
associated with the "v2" prefix can be ignored and you would still have a 
document that would have an acceptable meaning. If a XAML reader only has the 
version 1 assembly, it would interpreted the above document as,</p>
        <pre>    &lt;Balloon Color="Red" xmlns="...assembly-v1-uri..."  /&gt;</pre>
        <p>If the reader has the version 2 assembly, it would interpret it as,</p>
        <pre>    &lt;Balloon Color="Red" Shape="Dog" xmlns="...assembly-v2-uri..." /&gt;</pre>
        <p>mc:Ignorable can also applies to elements. To see example of this lets define a class, Party, that is 
define as,</p>
        <pre>    [ContentProperty("Balloons")]
    <b>public</b><b>class</b> Party {
        List&lt;Balloon&gt; _balloons = <b>new</b> List&lt;Balloon&gt;();
        <b>public</b> List&lt;Balloon&gt; Balloons { <b>get</b> { return _balloons; } 
    }</pre>
        <p>This allows us to define a Party instance that contains balloons. For this 
example, let's assume that Party was defined in the Version 1 assembly and is 
unmodified in the Version 2 assembly. We can then 
write a XAML document that looks like,</p>
        <pre>    &lt;Party xmln="...assembly-v1-uri..."&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
    &lt;/Party&gt;</pre>
        <p>We can now also write a document that will include a third dog shaped balloon 
but only if we are using the version 2 assembly, and not include if we are still 
using version 1. It looks like,</p>
        <pre>    &lt;Party mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
        &lt;v2:Balloon Color="Green" Shape="Dog" /&gt;
    &lt;/Party&gt;</pre>
        <p>This will be interpreted exactly as the prior document when reading it with 
version 1. With version 2, however, it would be interpreted as if it was,</p>
        <pre>    &lt;Party xmlns="...assembly-v2-uri..."&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
        &lt;Balloon Color="Green" Shape="Dog" /&gt;
    &lt;/Party&gt;</pre>
        <p>We can also add a new a new class, such as Favor, that can be used in a 
document such as,</p>
        <pre>    &lt;Party mc:Ignorable="v2"
      xmln="...assembly-v1-uri..."
      xmlns:v2="...assembly-v2-uri..."
      xmlns:mc="http://schemas.micrsoft.com/winfx/2006/markup-compatibility"&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
        &lt;v2:Balloon Color="Green" Shape="Dog" /&gt;
        &lt;v2:Favor Kind="Kazoo" Quantity="10" /&gt;
    &lt;/Party&gt;</pre>
        <p>This doesn't affect the version 1 interpretation of the document, but adds 10 kazoos to 
the version 2 interpretation. If the author determines that the kazoos are 
really necessary to the interpretation of either the reference to v1 can be 
removed and the document rewritten to,</p>
        <pre>    &lt;Party xmlns="...assembly-v2-uri..."&gt;
        &lt;Balloon Color="Red" /&gt;
        &lt;Balloon Color="Blue" /&gt;
        &lt;Balloon Color="Green" Shape="Dog" /&gt;
        &lt;Favor Kind="Kazoo" Quantity="10" /&gt;
    &lt;/Party&gt;</pre>
        <p>or the the ignorable attribute can just be removed which amounts to an 
equivalent document given subsumption described in the previous entry.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/25290e01-64e5-49dd-919f-374f2162542c</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Tour of XAML IV: Backward compatibility</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/70564b92-7b34-424c-97e5-916c7f661eb8</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/70564b92-7b34-424c-97e5-916c7f661eb8</link>
      <pubDate>Thu, 02 Feb 2006 13:50:35 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;XAML has support for both forward and backward compatibility of XAML 
documents. To understand backwards compatibility in a more formal sense, think 
of a XAML reader combined with some set of assemblies as the predicate that 
defines a set. If the reader with the given set of assemblies accepts a XAML 
document 
without error it is part of the set. If it rejects a document, it is not part of 
the set. You can think of the XAML reader and assemblies as defining a set, &lt;i&gt;{r(s,x)|x}&lt;/i&gt; where &lt;i&gt;x&lt;/i&gt; 
is the XAML file and &lt;i&gt;r(s,x)&lt;/i&gt; is the XAML reader and &lt;i&gt;s&lt;/i&gt; is a set of 
assemblies. You can then describe the relationship between&amp;nbsp; two sets of 
assemblies with respect to XAML. The assemblies imply set schemas that the XAML 
reader uses to interpret the XAML document. The schema implied by the WPF 
assemblies states there is a Button element and a DockPanel element and the 
Button element can be included in a DockPanel as one of it children, for 
example. The a set of implied schemas&amp;nbsp; &lt;i&gt;s&lt;sub&gt;2&lt;/sub&gt;&lt;/i&gt; is backwards compatible 
with &lt;i&gt;s&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt; if &lt;i&gt;{r(s&lt;sub&gt;1&lt;/sub&gt;, x)|x} &amp;#x2229; {r(s&lt;sub&gt;2&lt;/sub&gt;,
x)|x} = {r(s&lt;sub&gt;1&lt;/sub&gt;, x)|x}&lt;/i&gt; or, in other words, &lt;i&gt;s&lt;sub&gt;2&lt;/sub&gt;&lt;/i&gt; is 
backwards compatible with &lt;i&gt;s&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt; if the reader will accept same XAML documents 
with &lt;i&gt;s&lt;/i&gt;&lt;sub&gt;&lt;i&gt;2&lt;/i&gt;&lt;/sub&gt; as it accepts with 
&lt;i&gt;s&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt;.&lt;/p&gt;
&lt;p&gt;XAML really doesn't have to do much to claim it supports 
backwards compatibility because backwards compatibility is really a relationship 
between two sets of XAML schemas (and the implying assemblies) than it is between XAML documents. XAML, 
however, simplifies establishing this relationship by allowing one schema to declare it subsumes another 
schema. That means that, 
given both &lt;i&gt;s&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt; and &lt;i&gt;s&lt;sub&gt;2&lt;/sub&gt;&lt;/i&gt;, XAML allows &lt;i&gt;s&lt;sub&gt;2&lt;/sub&gt;&lt;/i&gt; to declare that any reference elements of 
&lt;i&gt;s&lt;sub&gt;1&lt;/sub&gt;&lt;/i&gt; should be considered a reference to elements of &lt;i&gt;s&lt;sub&gt;2&lt;/sub&gt;&lt;/i&gt;.&lt;/p&gt;
&lt;p&gt;To get more concrete, suppose you had an assembly that declared a single type,&lt;/p&gt;
&lt;pre&gt;   &lt;b&gt; public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Balloon {
        Color _color;
        
        &lt;b&gt;public&lt;/b&gt; Color Color { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _color; } &lt;b&gt;set&lt;/b&gt; { _color = value; } }
    }&lt;/pre&gt;
&lt;p&gt;A XAML reader will infer a schema that would allow you to write a XAML 
document like,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Balloon Color="Red" xmlns="...assembly-v1-uri..." /&amp;gt&lt;/pre&gt;
&lt;p&gt;Now, lets say, in version 2 of the assembly you want to add a shape to the balloon 
class to support different balloon shapes. In the version 2 assembly you can modify 
the class to,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Balloon {
        Color _color;
        Shape _shape;
        
        &lt;b&gt;public&lt;/b&gt; Color Color { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _color; } &lt;b&gt;set&lt;/b&gt; { _color = value; } }
        &lt;b&gt;public&lt;/b&gt; Shape Shape { &lt;b&gt;get&lt;/b&gt; { &lt;b&gt;return&lt;/b&gt; _shape; } &lt;b&gt;set&lt;/b&gt; { _shape = value; } }
    }&lt;/pre&gt;
&lt;p&gt;Now we can write a XAML document that refers to the new assembly by writing,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Balloon Color="Red" Shape="Dog" xmlns="...assembly-v2-uri..."/&amp;gt&lt;/pre&gt;

&lt;p&gt;We, however, still want to read all XAML documents that refer to the previous 
assembly as well using the new assembly. We can do this by declaring, in the new 
assembly, that this assembly is compatible with the old assembly with a 
XmlnsCompatibleWith(&amp;quot;...assembly-v2-uri...&amp;quot;,&amp;quot;...assembly-v1-uri...&amp;quot;) attribute. 
When the XAML reader sees that attribute, it will silently interpret all references to &amp;quot;...assembly-v1-uri...&amp;quot; as if they where referring 
to &amp;quot;...assembly-v2-uri...&amp;quot;. A XAML reader, presented with the version 2 
assembly, will treat,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Balloon Color="Red" xmlns="...assembly-v1-uri..." /&amp;gt&lt;/pre&gt;
&lt;p&gt;exactly as if it was written as,&lt;/p&gt;
&lt;pre&gt;    &amp;lt;Balloon Color="Red" xmlns="...assembly-v2-uri..." /&amp;gt&lt;/pre&gt;
&lt;p&gt;This allows all XAML documents referring to version 1 assembly to be readable 
when you only have version 2 of the assembly. In fact, assuming you follow CLR 
guidelines for evolving an assembly, any XAML file that was legal using the 
version 1 assembly will be legal using the version 2 assembly.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/70564b92-7b34-424c-97e5-916c7f661eb8</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Cider's January CTP</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/45a081b3-b81e-4237-9805-eef190d854fc</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/45a081b3-b81e-4237-9805-eef190d854fc</link>
      <pubDate>Fri, 27 Jan 2006 19:59:06 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Cider has been available since December in CTP form. This is really old news 
and reasons why I haven't blogged about it till now you can see my previous post 
about my and my machines independent
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/45335adf-f01a-4af1-b211-610c26529d00"&gt;
vacations&lt;/a&gt;. To get the January CTP see the Channel 9 page
&lt;a href="http://channel9.msdn.com/wiki/default.aspx/Cider.JanuaryCTPReleaseNotes"&gt;
http://channel9.msdn.com/wiki/default.aspx/Cider.JanuaryCTPReleaseNotes&lt;/a&gt;. You 
can keep track of our developments through our Channel 9 home page at
&lt;a href="http://channel9.msdn.com/wiki/default.aspx/Cider.HomePage"&gt;
http://channel9.msdn.com/wiki/default.aspx/Cider.HomePage&lt;/a&gt;. I will try to be 
better about timely blogging updates but given my past history maybe it would be 
better if you checked the home page now and then...&lt;/p&gt;
&lt;p&gt;This month we are focusing on the grid design experience. Even though we 
shipped it in December we really stole, uh, er, borrowed the grid design 
experience from Sparkle (aka the Expression Interactive Designer) which is also 
now available in CTP form available from
&lt;a href="http://www.microsoft.com/downloads/details.aspx?familyid=ed9f5fb2-4cfc-4d2c-9af8-580d644e3d1d&amp;displaylang=en"&gt;
http://www.microsoft.com/downloads/details.aspx?familyid=ed9f5fb2-4cfc-4d2c-9af8-580d644e3d1d&amp;amp;displaylang=en&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;The Cider CTPs are not beta quality. I say that to make sure you know what to 
expect. We are delivering bits early and often to give all of you a chance to 
influence our development by giving us early feedback on our design and the 
general direction we are taking. I encourage all of you to take advantage of 
this. We are listening and care a lot about what you think.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/45a081b3-b81e-4237-9805-eef190d854fc</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>A Solution to a Puzzle</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/933cf015-8fc8-4fcb-b531-f2f00ff9c280</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/933cf015-8fc8-4fcb-b531-f2f00ff9c280</link>
      <pubDate>Sat, 17 Dec 2005 02:39:15 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;A few months back &lt;a href="http://www.winethirty.com/default.aspx"&gt;Randy 
Kimmerly&lt;/a&gt; posted a &lt;a href="http://www.winethirty.com/blog.aspx?id=146"&gt;blog&lt;/a&gt; 
about one the puzzles on my desk. &lt;/p&gt;
&lt;img src='http://www.winethirty.com/images/cube_puzzle.jpg' width='570px' /&gt;
&lt;p&gt;Twisted in the correct way it will form a 3x3x3 cube. It is a snake cube 
puzzle that goes by the commercial name of Cubra&lt;font face="Times New Roman"&gt;©&lt;/font&gt;. 
Randy got excited about the puzzle not for the puzzle itself but by the 
challenge of writing a program that will produce the solution. He wrote a very 
clever C# program to produce a solution. I thought the solution would be more 
concise in Prolog so I volunteered to produce a Prolog version. I had to dust off my &lt;a href="http://en.wikipedia.org/wiki/Prolog"&gt;
Prolog&lt;/a&gt; skills, I hadn't used Prolog since I used to support Turbo Prolog for 
&lt;a href="http://www.borland.com"&gt;Borland&lt;/a&gt;, so my skills are a bit rusty. Here is my solution,&lt;/p&gt;
&lt;blockquote&gt;
&lt;pre class="code"&gt;linkTurns([f, f, t, f, t, t, t, t, f, t, t, t, t, t, t, t, 
   t, f, t, t, t, f, t, t, t, f]).

inrange(0). inrange(1). inrange(2).
cell(X, Y, Z) :- inrange(X), inrange(Y), inrange(Z).

move(right, cell(X, Y, Z), cell(X1, Y, Z)) :- X1 is X + 1, cell(X1, Y, Z).
move(left, cell(X, Y, Z), cell(X1, Y, Z)) :- X1 is X - 1, cell(X1, Y, Z).
move(down, cell(X, Y, Z), cell(X, Y1, Z)) :- Y1 is Y + 1, cell(X, Y1, Z).
move(up, cell(X, Y, Z), cell(X, Y1, Z)) :- Y1 is Y - 1, cell(X, Y1, Z).
move(in, cell(X, Y, Z), cell(X, Y, Z1)) :- Z1 is Z + 1, cell(X, Y, Z1).
move(out, cell(X, Y, Z), cell(X, Y, Z1)) :- Z1 is Z - 1, cell(X, Y, Z1).

legalTurn(left, X) :- member(X, [up, down, in, out]).
legalTurn(right, X) :- member(X, [up, down, in, out]).
legalTurn(up, X) :- member(X, [left, right, in, out]).
legalTurn(down, X) :- member(X, [left, right, in, out]).
legalTurn(in, X) :- member(X, [left, right, up, down]).
legalTurn(out, X) :- member(X, [left, right, up, down]).

free(X, Y) :- member(X, Y), !, fail.
free(_, _).

solution(Cells, Moves, [], Cells, Moves).
solution([LastCell|UsedCells], [LastMove|OldMoves], 
   [t|Turns], ResultCells, ResultMoves) :-
   legalTurn(LastMove, NewMove), move(NewMove, LastCell, NewCell), 
   free(NewCell, UsedCells),   solution([NewCell, LastCell|UsedCells], 
   [NewMove, LastMove|OldMoves], Turns, ResultCells, ResultMoves).
solution([LastCell|UsedCells], [LastMove|OldMoves], 
   [f|Turns], ResultCells, ResultMoves) :- 
   move(LastMove, LastCell, NewCell), free(NewCell, UsedCells), 
   solution([NewCell, LastCell|UsedCells], [LastMove, LastMove|OldMoves], 
   Turns, ResultCells, ResultMoves).

solution(Cells, Moves) :- linkTurns(L), solution([cell(0, 0, 0)], 
   [right], L, Cells, Moves).


print_solution([], []).
print_solution([Cell|Cells], [Move|Moves]) :- 
   print_solution(Cells, Moves), write(Move), put(9), write('to '), 
   write(Cell), nl.

goal :- solution(Cells, Moves), print_solution(Cells, Moves).&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;The clause &lt;span class="code"&gt;linkTurns/1&lt;/span&gt; represents where the string 
of blocks turns and where it doesn't. &lt;span class="code"&gt;inrange/1&lt;/span&gt; 
represents the valid ranges the coordinates of a block can have, 0, 1 or 2. This 
is used to build &lt;span class="code"&gt;cell/3&lt;/span&gt; which represents the locations 
the blocks can occupy in a 3x3 result. &lt;span class="code"&gt;move/3&lt;/span&gt; 
calculates how to get from one block to another.&amp;nbsp; &lt;span class="code"&gt;
legalTurn/2&lt;/span&gt; generates legal turns. &lt;span class="code"&gt;free/2&lt;/span&gt; helps 
decide if a cell is already occupied.&amp;nbsp; &lt;span class="code"&gt;solution/5&lt;/span&gt; 
calculates the solution; and &lt;span class="code"&gt;solution/2&lt;/span&gt; is a 
simplified wrapper around&lt;span class="code"&gt; solution/5&lt;/span&gt;. &lt;span class="code"&gt;
print_solution/2&lt;/span&gt; is a utility clause to help print the solution in a some 
what readable form. Finally &lt;span class="code"&gt;goal&lt;/span&gt; is a clause that 
kicks off the whole process (a dead giveaway to Turbo Prolog roots).
&lt;p&gt;This will only print one solution (because of the implied cut in using I/O) even though there are two possible. To see 
both use,&lt;p&gt;
&lt;pre class="code"&gt;  ?- solution(Cells, Moves).&lt;/pre&gt;
&lt;p&gt;You will notice that both solutions are reflexive of each other so you could 
say there is really only one solution.&lt;/p&gt;
&lt;p&gt;I found an interesting site
&lt;a href="http://www.geocities.com/jaapsch/puzzles/snakecube.htm"&gt;here&lt;/a&gt; that 
discusses these puzzles as well as gives a break down of how many of these kinds 
of puzzle there can be.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/933cf015-8fc8-4fcb-b531-f2f00ff9c280</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>The Expression Problem: Part IV - Layers</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/bece3be7-04a1-4130-b1ac-0b88c94e7708</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/bece3be7-04a1-4130-b1ac-0b88c94e7708</link>
      <pubDate>Sat, 03 Dec 2005 17:48:04 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;So far I have presented three different approaches to solving the expression 
problem, procedural, pure object-oriented, and a visitor pattern. This time I 
will present a technique I will refer to as layers. Like the visitor pattern, it is a modification of the 
pure object-oriented approach that takes advantage of partial classes. The 
solution begins very similarly to the other object-oriented approaches, I create an abstract 
class to represent an abstraction of expressions,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr { }&lt;/pre&gt;
&lt;p&gt;Notice the addition of the &lt;span class="code"&gt;partial&lt;/span&gt; modifier. I will 
take advantage of that shortly. For now I will just flush out the rest of the 
hierarchy in a way that should, by now, be very familiar. I created a class to 
represent literals,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Literal: Expr {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Value;

        &lt;b&gt;public&lt;/b&gt; Literal(&lt;b&gt;double&lt;/b&gt; value) { Value = value; }
    }&lt;/pre&gt;
&lt;p&gt;Notice that, as with the pure object-oriented approach, I can keep the field 
used to hold the value as protected. This is also true for the class to 
represent an abstraction of binary operators.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryOperator: Expr {
        &lt;b&gt;protected&lt;/b&gt; Expr Left;
        &lt;b&gt;protected&lt;/b&gt; Expr Right;

        &lt;b&gt;public&lt;/b&gt; BinaryOperator(Expr left, Expr right) {
            Left = left;
            Right = right;
        }
    }&lt;/pre&gt;
&lt;p&gt;The actual binary operators are just descendants of &lt;span class="code"&gt;
BinaryOperator&lt;/span&gt; with no additional data.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Subtract: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Subtract(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Multiply: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Multiply(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Divide: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Divide(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }&lt;/pre&gt;
&lt;p&gt;So far, this is nearly identical to the pure object-oriented approach. Where 
it differs is in how new operations are added.&amp;nbsp; To add the
&lt;span class="code"&gt;Evaluate()&lt;/span&gt; method, instead of modifying each class to add the methods, I can take advantage of the fact I left them 
as partial classes and create additional parts that contain the methods instead. 
First I created a new part of the &lt;span class="code"&gt;Expr&lt;/span&gt; class to 
introduce the virtual method &lt;span class="code"&gt;Evaluate()&lt;/span&gt;.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate();
    }&lt;/pre&gt;
&lt;p&gt;Compiling now will generate several errors indicating that the other classes 
do not implement the &lt;span class="code"&gt;Evaluate()&lt;/span&gt; method.&amp;nbsp; This is 
want I wanted. Using &lt;span class="code"&gt;abstract&lt;/span&gt; in the above class part lets the compiler help me 
determine when I have completed the implementation of the evaluate operation. 
The rest of the class parts for &lt;span class="code"&gt;Evaluate()&lt;/span&gt; looks like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Literal {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate() {
            &lt;b&gt;return&lt;/b&gt; Value;
        }
    }

    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;sealed&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate() {
            &lt;b&gt;return&lt;/b&gt; EvaluateOp(Left.Evaluate(), Right.Evaluate());
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right);
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left + right;
        }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Subtract {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left - right;
        }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Multiply {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left * right;
        }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Divide {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left / right;
        }
    }&lt;/pre&gt;
&lt;p&gt;I call each of the collections of class parts a layer. You can think 
of them much like a transparency teachers uses on overhead projectors. You can 
build up a class by combining layers of functionality. I usually keep each layer 
in its own file named for the layer. In this case, Evaluator.cs might be a good 
choice.&lt;/p&gt;
&lt;p&gt;To demonstrate building up a class with through layers I 
will create a printing layer.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print();
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Literal {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print() {
            Console.Write(Value);
        }
    }

    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;sealed&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print() {
            Left.Print();
            PrintOp();
            Right.Print();
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp();
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" + ");
        }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Subtract {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" - ");
        }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Multiply {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" * ");
        }
    }

    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Divide {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" / ");
        }
    }&lt;/pre&gt;
&lt;p&gt;As in the other approaches, I will demonstrate how to add support for the 
Power expression form. I have two choices, I can add it just as we did in the pure object-oriented approach,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;class&lt;/b&gt; Power: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Power(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; Math.Pow(left, right);
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" ^ ");
        }
    }&lt;/pre&gt;
&lt;p&gt;or I could divide it into multiple parts that can be co-located with the other 
similar parts. The data part would look like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Power: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Power(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }&lt;/pre&gt;
&lt;p&gt;The part for the expression layer would look like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Power: BinaryExpr {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; Math.Pow(left, right);
        }
    }&lt;/pre&gt;
&lt;p&gt;An the printing layer part would look like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Power: BinaryExpr {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" ^ ");
        }
    }&lt;/pre&gt;
&lt;p&gt;It is this flexibility that makes layers so appealing. You can decide, case 
by case, which is the right way to modify the hierarchy.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/bece3be7-04a1-4130-b1ac-0b88c94e7708</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>The Expression Problem: Part III - Visitor Pattern</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/861feae8-2404-4044-b661-aa13d432b08d</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/861feae8-2404-4044-b661-aa13d432b08d</link>
      <pubDate>Fri, 25 Nov 2005 16:16:02 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;So far we have looked at two ways to represent the following expression 
forms,&lt;/p&gt;
&lt;blockquote&gt;
&lt;table border="0" id="table1"&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;number&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Literal&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;expr&lt;/i&gt; + &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Add&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; - &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Subtract&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; * &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Multiply&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; / &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Divide&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;
&lt;/blockquote&gt;
&lt;p&gt;The first was procedural and the second object-oriented. Using the 
procedural approach, it was easier to add operations than data types. Using an 
object-oriented approach, the opposite was true. What I will demonstrate now is 
a technique that balances some of the advantages and disadvantages of both into 
a hybrid approach called the
&lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;Visitor Pattern&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;There are several ways to apply the visitor problem to expressions, each with 
their own unique set of advantages and disadvantages, but I will only cover one 
of these approaches.&lt;/p&gt;
&lt;p&gt;The visitor pattern is a modification of the the object-oriented approach 
that allows an operation to be separated from the class hierarchy into 
its own class. To demonstrate how a visitor pattern can be applied, I will first 
created a visitor interface that will be implemented by all visitors. It looks like,&lt;/p&gt;
  &lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;interface&lt;/b&gt; IExprVisitor&amp;lt;R&amp;gt; {
        R Visit(Literal literal);
        R Visit(Add add);
        R Visit(Subtract subtract);
        R Visit(Multiply multiply);
        R Visit(Divide divide);
    }&lt;sup&gt;&lt;a name="ref-note1" href="#note1"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/pre&gt;
&lt;p&gt;Here I use a generic type to leave the type of the return result open. The 
expression evaluator will use &lt;span class="code"&gt;double&lt;/span&gt; but &lt;span class="code"&gt;double&lt;/span&gt; isn't an appropriate return 
result for printing, for example. Using a type parameter allows different visitors 
to have their own result types.&lt;/p&gt;
&lt;p&gt;Now I will create the class hierarchy that will be visited. I will first 
create an 
abstract class to represent the expressions, just as I did in the previous object 
oriented example.&lt;/p&gt;
  &lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; R Accept&amp;lt;R&amp;gt;(IExprVisitor&amp;lt;R&amp;gt; visitor);
    }&lt;/pre&gt;
&lt;p&gt;The method &lt;span class="code"&gt;Accept()&lt;/span&gt; is key to the visitor pattern. 
It accepts the visitor and, in turn, calls the correct &lt;span class="code"&gt;
Visit()&lt;/span&gt; 
method on the visitor, based on the type of the instance being visited. To do this, each descendant overrides 
the &lt;span class="code"&gt;Accept()&lt;/span&gt; method and calls the correct method. To 
show how this is done I will implement the Literal expression form. &lt;/p&gt;
  &lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Literal: Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Value;

        &lt;b&gt;public&lt;/b&gt; Literal(&lt;b&gt;double&lt;/b&gt; value) { Value = value; }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; R Accept&amp;lt;R&amp;gt;(IExprVisitor&amp;lt;R&amp;gt; visitor) {
            &lt;b&gt;return&lt;/b&gt; visitor.Visit(this);
        }
    }&lt;/pre&gt;
&lt;p&gt;The above &lt;span class="code"&gt;Literal&lt;/span&gt; class is very similar to the 
original pure object oriented version with the addition of the &lt;span class="code"&gt;
Accept()&lt;/span&gt; method. The implementation of the method is trivial, simply call
&lt;span class="code"&gt;visitor.Visit(this)&lt;/span&gt;. The compiler will determine that
&lt;span class="code"&gt;IExprVisitor&amp;lt;R&amp;gt;.Visitor(Literal literal)&lt;/span&gt; is the method 
to bind to based on the type of the &lt;span class="code"&gt;this&lt;/span&gt; parameter.&lt;/p&gt;
&lt;p&gt;Next, as before, I introduce a base class to represent an abstraction of a 
binary operator.&lt;/p&gt;
  &lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryOperator: Expr {
        &lt;b&gt;public&lt;/b&gt; Expr Right;
        &lt;b&gt;public&lt;/b&gt; Expr Left;

        &lt;b&gt;public&lt;/b&gt; BinaryOperator(Expr left, Expr right) {
            Right = right;
            Left = left;
        }
    }&lt;/pre&gt;
&lt;p&gt;Notice that I do not yet implement the &lt;span class="code"&gt;Accept()&lt;/span&gt; method. 
I could have, after adding &lt;span class="code"&gt;R Visit(BinaryOperator binop)&lt;/span&gt; 
to the &lt;span class="code"&gt;IExprVisitor&lt;/span&gt; interface, but I didn't need it 
for the visitors I wanted to create. I have found that it is usually best to only have 
the visitors visit the concrete classes and avoid the abstract. A visitor can 
always simulate visiting a abstract base class by calling a common routine in 
each of the concrete class visitor methods (you will see this technique below in 
the &lt;span class="code"&gt;Printer&lt;/span&gt; visitor). This leaves the visitor less 
cluttered when the abstract class doesn't need to be visited separately. In other 
words, my &lt;span class="code"&gt;Accept()&lt;/span&gt; methods only calls one &lt;span class="code"&gt;
Visit()&lt;/span&gt; method for each instance, and that for the most derived type. This has the 
additional advantage of allowing the &lt;span class="code"&gt;Visit()&lt;/span&gt; method to 
have a meaningful result, which wouldn't be possible if the &lt;span class="code"&gt;
Accept()&lt;/span&gt; method called more than one &lt;span class="code"&gt;Visit()&lt;/span&gt; 
methods.&lt;/p&gt;
&lt;p&gt;Now that I have a base class for binary operators, I can now implement the 
binary operator expression forms.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; R Accept&amp;lt;R&amp;gt;(IExprVisitor&amp;lt;R&amp;gt; visitor) {
            &lt;b&gt;return&lt;/b&gt; visitor.Visit(this);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Subtract: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Subtract(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; R Accept&amp;lt;R&amp;gt;(IExprVisitor&amp;lt;R&amp;gt; visitor) {
            &lt;b&gt;return&lt;/b&gt; visitor.Visit(this);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Multiply: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Multiply(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; R Accept&amp;lt;R&amp;gt;(IExprVisitor&amp;lt;R&amp;gt; visitor) {
            return visitor.Visit(this);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Divide: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Divide(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; R Accept&amp;lt;R&amp;gt;(IExprVisitor&amp;lt;R&amp;gt; visitor) {
            &lt;b&gt;return&lt;/b&gt; visitor.Visit(this);
        }
    }&lt;/pre&gt;
&lt;p&gt;The implementation of these should come as no surprise.&amp;nbsp; They each 
override the &lt;span class="code"&gt;Accept()&lt;/span&gt; method and call the visitor 
method associated with their type.&lt;/p&gt;
&lt;p&gt;Now that we have the class hierarchy in place, I will now implement the 
expression evaluator as a visitor.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Evaluator: IExprVisitor&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt; {
        &lt;b&gt;public&lt;/b&gt; Evaluator() { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate(Expr expr) {
            &lt;b&gt;return&lt;/b&gt; expr.Accept(this);
        }

        &lt;b&gt;double&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Visit(Literal literal) {
            &lt;b&gt;return&lt;/b&gt; literal.Value;
        }

        &lt;b&gt;double&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Visit(Add add) {
            &lt;b&gt;return&lt;/b&gt; Evaluate(add.Left) + Evaluate(add.Right);
        }

        &lt;b&gt;double&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Visit(Subtract subtract) {
            &lt;b&gt;return&lt;/b&gt; Evaluate(subtract.Left) - Evaluate(subtract.Right);
        }

        &lt;b&gt;double&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Visit(Multiply multiply) {
            &lt;b&gt;return&lt;/b&gt; Evaluate(multiply.Left) * Evaluate(multiply.Right);
        }

        &lt;b&gt;double&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Visit(Divide divide) {
            &lt;b&gt;return&lt;/b&gt; Evaluate(divide.Left) / Evaluate(divide.Right);
        }
    }&lt;/pre&gt;
&lt;p&gt;The expression evaluator can be used by creating a new visitor and calling 
the &lt;span class="code"&gt;Evaluate()&lt;/span&gt; method of the evaluator, passing the root of the expression tree. 
For example,&lt;/p&gt;
&lt;blockquote&gt;
&lt;pre class="code"&gt;Expr expr = &lt;b&gt;new&lt;/b&gt; Add(&lt;b&gt;new&lt;/b&gt; Multiply(&lt;b&gt;new&lt;/b&gt; Literal(10), &lt;b&gt;new&lt;/b&gt; Literal(4)),
    &lt;b&gt;new&lt;/b&gt; Literal(2));

Evalutor evaluator = &lt;b&gt;new&lt;/b&gt; Evaluator();
&lt;b&gt;double&lt;/b&gt; result = evaluator.Evaluate(expr);
  
Console.WriteLine("The answer is {0}", result);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;The visitor pattern makes it easy to add new operations. To demonstrate this, 
as before, I will add a print operation. This looks very much like the 
expression evaluator above.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Printer: IExprVisitor&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt; {
        &lt;b&gt;public&lt;/b&gt; Printer() { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print(Expr expr) {
            expr.Accept(this);
        }

        &lt;b&gt;object&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt;.Visit(Literal literal) {
            Console.Write(literal.Value);
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;void&lt;/b&gt; PrintBinaryOperator(BinaryOperator binOp, char opChar) {
            Print(binOp.Left);
            Console.Write(" {0} ", opChar);
            Print(binOp.Right);
        }

        &lt;b&gt;object&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt;.Visit(Add add) {
            PrintBinaryOperator(add, '+');
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;object&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt;.Visit(Subtract subtract) {
            PrintBinaryOperator(subtract, '-');
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;object&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt;.Visit(Multiply multiply) {
            PrintBinaryOperator(multiply, '*');
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;null&lt;/b&gt;;
        }

        &lt;b&gt;object&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt;.Visit(Divide divide) {
            PrintBinaryOperator(divide, '/');
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;null&lt;/b&gt;;
        }
    }&lt;/pre&gt;
&lt;p&gt;As this shows, using a parameterized type for the visitor interface is awkward 
when you don't have anything to return. What I would want to do is implement
&lt;span class="code"&gt;IExprVisitor&amp;lt;void&amp;gt;&lt;/span&gt; but &lt;span class="code"&gt;void&lt;/span&gt; 
is not allowed as a type parameter so I use &lt;span class="code"&gt;object&lt;/span&gt; 
instead. This means I have to return something, so I always return
&lt;span class="code"&gt;null&lt;/span&gt;. This should be seen as awkwardness introduced by 
my choice of interface styles, not of the visitor pattern itself.&lt;/p&gt;
&lt;p&gt;The visitor pattern shares some of the advantages of the procedural approach, 
in that it is easy to add new operations and new operations can be added 
dynamically, but we lose the natural ability to add new data types that is 
normally associated with an object-oriented approach as well as lose 
representation encapsulation since the instance fields need to be visible to the 
visitors. We kept the natural size optimization and the completeness 
verification by the compiler, however. To demonstrate the difficult of adding a 
new type, I will again add Power. The first step is to add the new 
&lt;span class="code"&gt;Power&lt;/span&gt; type.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Power: BinaryOperator {
        &lt;b&gt;public&lt;/b&gt; Power(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; R Accept&amp;lt;R&amp;gt;(IExprVisitor&amp;lt;R&amp;gt; visitor) {
            &lt;b&gt;return&lt;/b&gt; visitor.Visit(this);
        }
    }&lt;/pre&gt;
&lt;p&gt;Now we need to add a method to &lt;span class="code"&gt;IExprVisitor&amp;lt;R&amp;gt;&lt;/span&gt; 
for the &lt;span class="code"&gt;Power&lt;/span&gt; type that each visitor will need to implement. It looks like,&lt;/p&gt;
&lt;pre class="code"&gt;        R Visit(Power power);&lt;/pre&gt;
&lt;p&gt;Next I need to add a method for in each visitor to handle the new class. For
&lt;span class="code"&gt;Evaluator&lt;/span&gt; it is,&lt;/p&gt;
&lt;pre class="code"&gt;        &lt;b&gt;double&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Visit(Power power) {
            &lt;b&gt;return&lt;/b&gt; Math.Pow(Evaluate(power.Left), Evaluate(power.Right));
        }&lt;/pre&gt;
&lt;p&gt;And and for the &lt;span class="code"&gt;Printer&lt;/span&gt; class it looks like.&lt;/p&gt;
&lt;pre class="code"&gt;        &lt;b&gt;object&lt;/b&gt; IExprVisitor&amp;lt;&lt;b&gt;object&lt;/b&gt;&amp;gt;.Visit(Power power) {
            PrintBinaryOperator(power, '^');
            &lt;b&gt;return&lt;/b&gt; &lt;b&gt;null&lt;/b&gt;;
        }&lt;/pre&gt;
&lt;p&gt;This is just one way to apply the visitor pattern to the expression problem. 
Other ways have their own strengths and weaknesses by trading off different 
advantages and disadvantages of the the procedural and object-oriented styles. 
Some visitor pattern applications have their own unique advantages, such as being able 
to mesh functionality by executing several visitors concurrently such as 
evaluating and printing.&lt;/p&gt;
&lt;p&gt;Next time we will investigate a different modified object-oriented approach 
that is sometimes dubbed groups but I will call layers.&lt;/p&gt;
&lt;hr/&gt;
&lt;p&gt;&lt;a name="note1" href="#ref-note1"&gt;1&lt;/a&gt; - This application of the visitor
pattern is patterned after one from &lt;a href="http://research.microsoft.com/~akenn/generics/gadtoop.pdf"&gt;Generalized Algebraic Data Types and Object-Oriented Programming&lt;/a&gt;.
 &lt;a href="#ref-note1"&gt;&amp;lt;&amp;lt; back &amp;lt;&amp;lt;&lt;/a&gt;&lt;/p&gt;
&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/861feae8-2404-4044-b661-aa13d432b08d</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>The Expression Problem: Part II - Object-oriented</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/eb49ee14-56da-410b-93d4-bd39e88d54d7</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/eb49ee14-56da-410b-93d4-bd39e88d54d7</link>
      <pubDate>Sat, 19 Nov 2005 12:49:38 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Last time we took a procedural approach to solve the &lt;i&gt;expression problem&lt;/i&gt;. 
This time I will demonstrate an object-oriented approach. As a 
reminder, we want to model the following forms of expressions,&lt;/p&gt;
&lt;blockquote&gt;
&lt;table border="0" id="table1"&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;number&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Literal&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;expr&lt;/i&gt; + &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Add&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; - &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Subtract&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; * &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Multiply&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; / &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Divide&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;
&lt;/blockquote&gt;
&lt;p&gt;The most natural thing to do in an object-oriented language is to make each of the above 
expression forms its own class. First, I will introduce a base class to provide an expression abstraction.&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
    }
&lt;/pre&gt;
&lt;p&gt;Now I will now create a sub-class for each expression.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;class&lt;/b&gt; Literal: Expr {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Value;

        &lt;b&gt;public&lt;/b&gt; Literal(&lt;b&gt;double&lt;/b&gt; value) {
            Value = value;
        }
    }
    
    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryExpr: Expr {
        &lt;b&gt;protected&lt;/b&gt; Expr Left;
        &lt;b&gt;protected&lt;/b&gt; Expr Right;

        &lt;b&gt;public&lt;/b&gt; BinaryExpr(Expr left, Expr right) {
            Left = left;
            Right = right;
        }
    }
    
    &lt;b&gt;class&lt;/b&gt; Add: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }
    
    &lt;b&gt;class&lt;/b&gt; Subtract: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Subtract(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }
    
    &lt;b&gt;class&lt;/b&gt; Multiply: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Multiply(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }
    
    &lt;b&gt;class&lt;/b&gt; Divide: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Divide(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
    }&lt;/pre&gt;
&lt;p&gt;I created a base class for the binary expressions which I will take 
advantage of below. &lt;/p&gt;
&lt;p&gt;To evaluate the expression I will add an abstract virtual method,
&lt;span class="code"&gt;Evaluate()&lt;/span&gt;, to &lt;span class="code"&gt;Expr&lt;/span&gt;. &lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate();
    }&lt;/pre&gt;
&lt;p&gt;Then I will override the &lt;span class="code"&gt;Evaluate()&lt;/span&gt; method for 
each of the above classes. Evaluating a literal is simply returning the value of 
the literal so I modified the &lt;span class="code"&gt;Literal&lt;/span&gt; class to,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;class&lt;/b&gt; Literal: Expr {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Value;

        &lt;b&gt;public&lt;/b&gt; Literal(&lt;b&gt;double&lt;/b&gt; value) {
            Value = value;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate() {
            return Value;
        }
    }
&lt;/pre&gt;
&lt;p&gt;All binary expressions need to evaluate their left-hand expression and 
right-hand expression and then perform their operation on the results. To represent this, I 
overrode &lt;span class="code"&gt;Evaluate()&lt;/span&gt; to evaluate both &lt;span class="code"&gt;Left&lt;/span&gt; and &lt;span class="code"&gt;Right&lt;/span&gt; 
and then call a newly introduced &lt;span class="code"&gt;EvaluateOp()&lt;/span&gt; 
method. I sealed the &lt;span class="code"&gt;Evaluate()&lt;/span&gt; method because I want 
descendants to override &lt;span class="code"&gt;EvaluateOp()&lt;/span&gt; not
&lt;span class="code"&gt;Evaluate()&lt;/span&gt;.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryExpr: Expr {
        &lt;b&gt;protected&lt;/b&gt; Expr Left;
        &lt;b&gt;protected&lt;/b&gt; Expr Right;

        &lt;b&gt;public&lt;/b&gt; BinaryExpr(Expr left, Expr right) {
            Left = left;
            Right = right;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;sealed&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate() {
            return EvaluateOp(Left.Evaluate(), Right.Evaluate());
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right);
    }
&lt;/pre&gt;
&lt;p&gt;Now I can implemented the concrete descendents of &lt;span class="code"&gt;BinaryExpr&lt;/span&gt;.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;class&lt;/b&gt; Add: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            return left + right;
        }
    }

    &lt;b&gt;class&lt;/b&gt; Subtract: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Subtract(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            return left - right;
        }
    }

    &lt;b&gt;class&lt;/b&gt; Multiply: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Multiply(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            return left * right;
        }
    }

    &lt;b&gt;class&lt;/b&gt; Divide: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Divide(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            return left / right;
        }
    }&lt;/pre&gt;
&lt;p&gt;The advantages an object-oriented approach are,&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;New data types can be added without affecting any of the other data 
	types. &lt;/li&gt;
	&lt;li&gt;Each data type is encapsulated, only the data type needs to have access 
	the instance variables.&lt;/li&gt;
	&lt;li&gt;All the operations affecting the instance variables are in one place, 
	the methods of instance variable's class.&lt;/li&gt;
	&lt;li&gt;New operations can be added as abstract methods. The compiler will then 
	generate an error if an operation is not implemented for one of the leaf 
	classes.&lt;/li&gt;
	&lt;li&gt;Efficient storage is natural. Adding field to one of the expression 
	types do not affect the others.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To demonstrate how easy it is to add a new data type I will again add support 
for Power.&lt;/p&gt;
&lt;blockquote&gt;
&lt;table border="0" id="table2"&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;expr&lt;/i&gt; ^ &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Power&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;
&lt;/blockquote&gt;
&lt;p&gt; To do this I will add a class to represent the Power expression form. 
This looks like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;class&lt;/b&gt; Power: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Power(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            return Math.Pow(left, right);
        }
    }&lt;/pre&gt;
&lt;p&gt;Note that the &lt;span class="code"&gt;Power&lt;/span&gt; data type can be added without 
modifying the other classes. &lt;/p&gt;
&lt;p&gt;The disadvantages to an object-oriented approach are,&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;It is difficult to add new operations because adding an operation 
	requires modifying all the classes.&lt;/li&gt;
	&lt;li&gt;The logic for each operation is spread over multiple classes and often 
	multiple files. This makes it cumbersome to get a complete picture what the 
	operation does.&lt;/li&gt;
	&lt;li&gt;It is very difficult to dynamically add operations and can't be done 
	without careful planning.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To demonstrate some of the difficulties of adding a new operation, I will add 
the Print operation. First I will modify the base &lt;span class="code"&gt;Expr&lt;/span&gt; 
class to add an abstract &lt;span class="code"&gt;Print()&lt;/span&gt; method.&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate();
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print();
    }&lt;/pre&gt;
&lt;p&gt;Now I will override this method in each class similar to the way I did for 
the &lt;span class="code"&gt;Evaluate()&lt;/span&gt; method.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;class&lt;/b&gt; Literal: Expr {
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Value;

        &lt;b&gt;public&lt;/b&gt; Literal(&lt;b&gt;double&lt;/b&gt; value) {
            Value = value;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate() {
            &lt;b&gt;return&lt;/b&gt; Value;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print() {
            Console.Write(Value);
        }
    }

    &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryExpr: Expr {
        &lt;b&gt;protected&lt;/b&gt; Expr Left;
        &lt;b&gt;protected&lt;/b&gt; Expr Right;

        &lt;b&gt;public&lt;/b&gt; BinaryExpr(Expr left, Expr right) {
            Left = left;
            Right = right;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;sealed&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate() {
            &lt;b&gt;return&lt;/b&gt; EvaluateOp(Left.Evaluate(), Right.Evaluate());
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right);

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;sealed&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print() {
            Left.Print();
            PrintOp();
            Right.Print();
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp();
    }

    &lt;b&gt;class&lt;/b&gt; Add: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : base(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left + right;
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" + ");
        }
    }

    &lt;b&gt;class&lt;/b&gt; Subtract: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Subtract(Expr left, Expr right) : base(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left - right;
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" - ");
        }
    }

    &lt;b&gt;class&lt;/b&gt; Multiply: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Multiply(Expr left, Expr right) : base(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left * right;
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" * ");
        }
    }

    &lt;b&gt;class&lt;/b&gt; Divide: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Divide(Expr left, Expr right) : base(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; left / right;
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" / ");
        }
    }
    
    &lt;b&gt;class&lt;/b&gt; Power: BinaryExpr {
        &lt;b&gt;public&lt;/b&gt; Power(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; EvaluateOp(&lt;b&gt;double&lt;/b&gt; left, &lt;b&gt;double&lt;/b&gt; right) {
            &lt;b&gt;return&lt;/b&gt; Math.Pow(left, right);
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PrintOp() {
            Console.Write(" ^ ");
        }
    }&lt;/pre&gt;
&lt;p&gt;As you can see, each of the classes needed to be modified to implement
&lt;span class="code"&gt;Print()&lt;/span&gt;. You can also note that the compiler 
complained until each of the classes implemented the &lt;span class="code"&gt;Print()&lt;/span&gt; 
operation. This is because we used an abstract method in the &lt;span class="code"&gt;
Expr&lt;/span&gt; class.&lt;/p&gt;
&lt;p&gt;If you compare the procedural approach vs. the object-oriented approach you 
will notice that they are pretty much opposites. It is easy to add operations in 
the procedural approach but difficult using an object-oriented approach. Adding 
data types is difficult using in a procedural approach, but easy in an 
object-oriented approach. Data needs to be public in procedural, but can be 
private in object oriented. When deciding which approach to use you need to try 
an predict what will occur more often, adding new data types or adding new 
operations. What I will present next are some compromise solutions that balance 
the advantages and disadvantages.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Last time we took a procedural approach to solve the <i>expression problem</i>. 
This time I will demonstrate an object-oriented approach. As a 
reminder, we want to model the following forms of expressions,</p>
        <blockquote>
          <table border="0" id="table1">
            <tr>
              <td width="100">
                <i>number</i>
              </td>
              <td>Literal</td>
            </tr>
            <tr>
              <td width="100">
                <i>expr</i> + <i>expr</i></td>
              <td>Add</td>
            </tr>
            <tr>
              <td width="75">
                <i>expr</i> - <i>expr</i></td>
              <td>Subtract</td>
            </tr>
            <tr>
              <td width="75">
                <i>expr</i> * <i>expr</i></td>
              <td>Multiply</td>
            </tr>
            <tr>
              <td width="75">
                <i>expr</i> / <i>expr</i></td>
              <td>Divide</td>
            </tr>
          </table>
        </blockquote>
        <p>The most natural thing to do in an object-oriented language is to make each of the above 
expression forms its own class. First, I will introduce a base class to provide an expression abstraction.</p>
        <pre>
          <b>abstract</b>
          <b>class</b> Expr {
    }
</pre>
        <p>Now I will now create a sub-class for each expression.</p>
        <pre class="code">
          <b>class</b> Literal: Expr {
        <b>protected</b><b>double</b> Value;

        <b>public</b> Literal(<b>double</b> value) {
            Value = value;
        }
    }
    
    <b>abstract</b><b>class</b> BinaryExpr: Expr {
        <b>protected</b> Expr Left;
        <b>protected</b> Expr Right;

        <b>public</b> BinaryExpr(Expr left, Expr right) {
            Left = left;
            Right = right;
        }
    }
    
    <b>class</b> Add: BinaryExpr {
        <b>public</b> Add(Expr left, Expr right) : <b>base</b>(left, right) { }
    }
    
    <b>class</b> Subtract: BinaryExpr {
        <b>public</b> Subtract(Expr left, Expr right) : <b>base</b>(left, right) { }
    }
    
    <b>class</b> Multiply: BinaryExpr {
        <b>public</b> Multiply(Expr left, Expr right) : <b>base</b>(left, right) { }
    }
    
    <b>class</b> Divide: BinaryExpr {
        <b>public</b> Divide(Expr left, Expr right) : <b>base</b>(left, right) { }
    }</pre>
        <p>I created a base class for the binary expressions which I will take 
advantage of below. </p>
        <p>To evaluate the expression I will add an abstract virtual method,
<span class="code">Evaluate()</span>, to <span class="code">Expr</span>. </p>
        <pre>
          <b>abstract</b>
          <b>class</b> Expr {
        <b>public</b><b>abstract</b><b>double</b> Evaluate();
    }</pre>
        <p>Then I will override the <span class="code">Evaluate()</span> method for 
each of the above classes. Evaluating a literal is simply returning the value of 
the literal so I modified the <span class="code">Literal</span> class to,</p>
        <pre class="code">
          <b>class</b> Literal: Expr {
        <b>protected</b><b>double</b> Value;

        <b>public</b> Literal(<b>double</b> value) {
            Value = value;
        }

        <b>public</b><b>override</b><b>double</b> Evaluate() {
            return Value;
        }
    }
</pre>
        <p>All binary expressions need to evaluate their left-hand expression and 
right-hand expression and then perform their operation on the results. To represent this, I 
overrode <span class="code">Evaluate()</span> to evaluate both <span class="code">Left</span> and <span class="code">Right</span> 
and then call a newly introduced <span class="code">EvaluateOp()</span> 
method. I sealed the <span class="code">Evaluate()</span> method because I want 
descendants to override <span class="code">EvaluateOp()</span> not
<span class="code">Evaluate()</span>.</p>
        <pre class="code">
          <b>abstract</b>
          <b>class</b> BinaryExpr: Expr {
        <b>protected</b> Expr Left;
        <b>protected</b> Expr Right;

        <b>public</b> BinaryExpr(Expr left, Expr right) {
            Left = left;
            Right = right;
        }

        <b>public</b><b>sealed</b><b>override</b><b>double</b> Evaluate() {
            return EvaluateOp(Left.Evaluate(), Right.Evaluate());
        }

        <b>protected</b><b>abstract</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right);
    }
</pre>
        <p>Now I can implemented the concrete descendents of <span class="code">BinaryExpr</span>.</p>
        <pre class="code">
          <b>class</b> Add: BinaryExpr {
        <b>public</b> Add(Expr left, Expr right) : <b>base</b>(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            return left + right;
        }
    }

    <b>class</b> Subtract: BinaryExpr {
        <b>public</b> Subtract(Expr left, Expr right) : <b>base</b>(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            return left - right;
        }
    }

    <b>class</b> Multiply: BinaryExpr {
        <b>public</b> Multiply(Expr left, Expr right) : <b>base</b>(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            return left * right;
        }
    }

    <b>class</b> Divide: BinaryExpr {
        <b>public</b> Divide(Expr left, Expr right) : <b>base</b>(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            return left / right;
        }
    }</pre>
        <p>The advantages an object-oriented approach are,</p>
        <ol>
          <li>New data types can be added without affecting any of the other data 
	types. </li>
          <li>Each data type is encapsulated, only the data type needs to have access 
	the instance variables.</li>
          <li>All the operations affecting the instance variables are in one place, 
	the methods of instance variable's class.</li>
          <li>New operations can be added as abstract methods. The compiler will then 
	generate an error if an operation is not implemented for one of the leaf 
	classes.</li>
          <li>Efficient storage is natural. Adding field to one of the expression 
	types do not affect the others.</li>
        </ol>
        <p>To demonstrate how easy it is to add a new data type I will again add support 
for Power.</p>
        <blockquote>
          <table border="0" id="table2">
            <tr>
              <td width="100">
                <i>expr</i> ^ <i>expr</i></td>
              <td>Power</td>
            </tr>
          </table>
        </blockquote>
        <p> To do this I will add a class to represent the Power expression form. 
This looks like,</p>
        <pre class="code">
          <b>class</b> Power: BinaryExpr {
        <b>public</b> Power(Expr left, Expr right) : <b>base</b>(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            return Math.Pow(left, right);
        }
    }</pre>
        <p>Note that the <span class="code">Power</span> data type can be added without 
modifying the other classes. </p>
        <p>The disadvantages to an object-oriented approach are,</p>
        <ol>
          <li>It is difficult to add new operations because adding an operation 
	requires modifying all the classes.</li>
          <li>The logic for each operation is spread over multiple classes and often 
	multiple files. This makes it cumbersome to get a complete picture what the 
	operation does.</li>
          <li>It is very difficult to dynamically add operations and can't be done 
	without careful planning.</li>
        </ol>
        <p>To demonstrate some of the difficulties of adding a new operation, I will add 
the Print operation. First I will modify the base <span class="code">Expr</span> 
class to add an abstract <span class="code">Print()</span> method.</p>
        <pre>
          <b>abstract</b>
          <b>class</b> Expr {
        <b>public</b><b>abstract</b><b>double</b> Evaluate();
        <b>public</b><b>abstract</b><b>void</b> Print();
    }</pre>
        <p>Now I will override this method in each class similar to the way I did for 
the <span class="code">Evaluate()</span> method.</p>
        <pre class="code">
          <b>class</b> Literal: Expr {
        <b>protected</b><b>double</b> Value;

        <b>public</b> Literal(<b>double</b> value) {
            Value = value;
        }

        <b>public</b><b>override</b><b>double</b> Evaluate() {
            <b>return</b> Value;
        }

        <b>public</b><b>override</b><b>void</b> Print() {
            Console.Write(Value);
        }
    }

    <b>abstract</b><b>class</b> BinaryExpr: Expr {
        <b>protected</b> Expr Left;
        <b>protected</b> Expr Right;

        <b>public</b> BinaryExpr(Expr left, Expr right) {
            Left = left;
            Right = right;
        }

        <b>public</b><b>sealed</b><b>override</b><b>double</b> Evaluate() {
            <b>return</b> EvaluateOp(Left.Evaluate(), Right.Evaluate());
        }

        <b>protected</b><b>abstract</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right);

        <b>public</b><b>sealed</b><b>override</b><b>void</b> Print() {
            Left.Print();
            PrintOp();
            Right.Print();
        }

        <b>protected</b><b>abstract</b><b>void</b> PrintOp();
    }

    <b>class</b> Add: BinaryExpr {
        <b>public</b> Add(Expr left, Expr right) : base(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            <b>return</b> left + right;
        }

        <b>protected</b><b>override</b><b>void</b> PrintOp() {
            Console.Write(" + ");
        }
    }

    <b>class</b> Subtract: BinaryExpr {
        <b>public</b> Subtract(Expr left, Expr right) : base(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            <b>return</b> left - right;
        }

        <b>protected</b><b>override</b><b>void</b> PrintOp() {
            Console.Write(" - ");
        }
    }

    <b>class</b> Multiply: BinaryExpr {
        <b>public</b> Multiply(Expr left, Expr right) : base(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            <b>return</b> left * right;
        }

        <b>protected</b><b>override</b><b>void</b> PrintOp() {
            Console.Write(" * ");
        }
    }

    <b>class</b> Divide: BinaryExpr {
        <b>public</b> Divide(Expr left, Expr right) : base(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            <b>return</b> left / right;
        }

        <b>protected</b><b>override</b><b>void</b> PrintOp() {
            Console.Write(" / ");
        }
    }
    
    <b>class</b> Power: BinaryExpr {
        <b>public</b> Power(Expr left, Expr right) : <b>base</b>(left, right) { }

        <b>protected</b><b>override</b><b>double</b> EvaluateOp(<b>double</b> left, <b>double</b> right) {
            <b>return</b> Math.Pow(left, right);
        }

        <b>protected</b><b>override</b><b>void</b> PrintOp() {
            Console.Write(" ^ ");
        }
    }</pre>
        <p>As you can see, each of the classes needed to be modified to implement
<span class="code">Print()</span>. You can also note that the compiler 
complained until each of the classes implemented the <span class="code">Print()</span> 
operation. This is because we used an abstract method in the <span class="code">
Expr</span> class.</p>
        <p>If you compare the procedural approach vs. the object-oriented approach you 
will notice that they are pretty much opposites. It is easy to add operations in 
the procedural approach but difficult using an object-oriented approach. Adding 
data types is difficult using in a procedural approach, but easy in an 
object-oriented approach. Data needs to be public in procedural, but can be 
private in object oriented. When deciding which approach to use you need to try 
an predict what will occur more often, adding new data types or adding new 
operations. What I will present next are some compromise solutions that balance 
the advantages and disadvantages.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/eb49ee14-56da-410b-93d4-bd39e88d54d7</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>The Expression Problem: Part I - Procedural</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/e6fb6ded-a66f-4707-97e7-0edaa04b30d9</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/e6fb6ded-a66f-4707-97e7-0edaa04b30d9</link>
      <pubDate>Sat, 12 Nov 2005 16:52:47 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Expressions are difficult to represent because they form a matrix of 
operations and data types. Languages make it either easy to add new operations 
but difficult to add data types or easy to add new data types but hard to add 
new operations. This problem isn't limited to expressions, of course, but it is 
a very clear and familiar example so I will use it to characterize the more 
general problem. I will 
present four ways to approach the problem, each with their particular strengths 
and weaknesses. For my examples 
I representing a simple expression language comprising of the following 
expression forms,&lt;/p&gt;
&lt;blockquote&gt;
&lt;table border="0" id="table1"&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;number&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Literal&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;expr&lt;/i&gt; + &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Add&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; - &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Subtract&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; * &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Multiply&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td width="75"&gt;&lt;i&gt;expr&lt;/i&gt; / &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Divide&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;
&lt;/blockquote&gt;
&lt;p&gt;Some operations I want to perform on these expressions include 
evaluating expressions and printing expressions. The operations and the expressions form a matrix 
of functionality, expression kind by operation,&lt;/p&gt;
&lt;blockquote&gt;
	&lt;table border="1" id="table3" style="border-collapse: collapse" width="321"&gt;
		&lt;tr&gt;
			&lt;td width="72"&gt;&amp;nbsp;&lt;/td&gt;
			&lt;td&gt;Evaluate&lt;/td&gt;
			&lt;td width="102"&gt;Print&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td width="72"&gt;Literal&lt;/td&gt;
			&lt;td&gt;&lt;i&gt;evaluate literal&lt;/i&gt;&lt;/td&gt;
			&lt;td width="102"&gt;&lt;i&gt;print literal&lt;/i&gt;&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td width="72"&gt;Add&lt;/td&gt;
			&lt;td&gt;&lt;i&gt;evaluate add&lt;/i&gt;&lt;/td&gt;
			&lt;td width="102"&gt;&lt;i&gt;print add&lt;/i&gt;&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td width="72"&gt;Subtract&lt;/td&gt;
			&lt;td&gt;&lt;i&gt;evaluate subtract&lt;/i&gt;&lt;/td&gt;
			&lt;td width="102"&gt;&lt;i&gt;print subtract&lt;/i&gt;&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td width="72"&gt;Multiply&lt;/td&gt;
			&lt;td&gt;&lt;i&gt;evaluate multiply&lt;/i&gt;&lt;/td&gt;
			&lt;td width="102"&gt;&lt;i&gt;print multiply&lt;/i&gt;&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td width="72"&gt;Divide&lt;/td&gt;
			&lt;td&gt;&lt;i&gt;evaluate divide&lt;/i&gt;&lt;/td&gt;
			&lt;td width="102"&gt;&lt;i&gt;print divide&lt;/i&gt;&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;
&lt;/blockquote&gt;
&lt;p&gt;Languages either make it easier to add new columns, 
that is operations, or add new rows, that is new expression kinds. Procedural 
and functional languages typically make it easy to add new operations. 
Object-oriented languages typically make it easier to add new expression kinds 
represented as new data types. &lt;/p&gt;
&lt;p&gt;The first approach I will demonstrate is procedural. I define a data type, 
&lt;span class="code"&gt;Expr&lt;/span&gt;, that will hold the operator and the operands.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;enum&lt;/b&gt; Oper { Add, Subtract, Multiply, Divide, Literal }

    &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; Oper Oper;
        &lt;b&gt;public&lt;/b&gt; Expr Left;
        &lt;b&gt;public&lt;/b&gt; Expr Right;
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Value;

        &lt;b&gt;public&lt;/b&gt; Expr(Oper oper, Expr left, Expr right) { ... }
        &lt;b&gt;public&lt;/b&gt; Expr(double value) { ... }
    }&lt;sup&gt;&lt;a href="#note1" name="ref-note1"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/pre&gt;
&lt;p&gt;The expression evaluation operation for this data structure looks like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;static&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Evaluate(Expr e) {
        &lt;b&gt;switch&lt;/b&gt; (e.Oper) {
            &lt;b&gt;case&lt;/b&gt; Oper.Add: &lt;b&gt;return&lt;/b&gt; Evaluate(e.Left) + Evaluate(e.Right);
            &lt;b&gt;case&lt;/b&gt; Oper.Subtract: &lt;b&gt;return&lt;/b&gt; Evaluate(e.Left) - Evaluate(e.Right);
            &lt;b&gt;case&lt;/b&gt; Oper.Multiply: &lt;b&gt;return&lt;/b&gt; Evaluate(e.Left) * Evaluate(e.Right);
            &lt;b&gt;case&lt;/b&gt; Oper.Divide: &lt;b&gt;return&lt;/b&gt; Evaluate(e.Left) / Evaluate(e.Right);
            &lt;b&gt;case&lt;/b&gt; Oper.Literal: &lt;b&gt;return&lt;/b&gt; e.Value;
            &lt;b&gt;default&lt;/b&gt;: Debug.Fail("Unknown operator"); &lt;b&gt;return&lt;/b&gt; 0;
        }
    }&lt;/pre&gt;
&lt;p&gt;The advantages to a procedural approach are,&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;It is very simple to add additional operations (such as
	&lt;span class="code"&gt;Evaluate()&lt;/span&gt;).&lt;/li&gt;
	&lt;li&gt;All the logic for an operation is centralized in one place, and often in a single 
	routine.&lt;/li&gt;
	&lt;li&gt;New operations can be added without having the modify existing 
	operations.&lt;/li&gt;
	&lt;li&gt;New operations can be also be added dynamically without affecting or 
	needing to recompile existing operations.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To demonstrate some of the advantages of using a procedural approach we will 
add a print operation. It looks like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Print(Expr e) {
        &lt;b&gt;switch&lt;/b&gt; (e.Oper) {
            &lt;b&gt;case&lt;/b&gt; Oper.Add: Print(e.Left); Console.Write(" + "); Print(e.Right); &lt;b&gt;break&lt;/b&gt;;
            &lt;b&gt;case&lt;/b&gt; Oper.Subtract: Print(e.Left); Console.Write(" - "); Print(e.Right); &lt;b&gt;break&lt;/b&gt;;
            &lt;b&gt;case&lt;/b&gt; Oper.Multiply: Print(e.Left); Console.Write(" * "); Print(e.Right); &lt;b&gt;break&lt;/b&gt;;
            &lt;b&gt;case&lt;/b&gt; Oper.Divide: Print(e.Left); Console.Write(" / "); Print(e.Right); &lt;b&gt;break&lt;/b&gt;;
            &lt;b&gt;case&lt;/b&gt; Oper.Literal: Console.Write(e.Value); &lt;b&gt;break&lt;/b&gt;;
            &lt;b&gt;default&lt;/b&gt;: Debug.Fail("Unknown operator"); &lt;b&gt;break&lt;/b&gt;;
        }
    }&lt;sup&gt;&lt;a href="#note2" name="ref-note2"&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/pre&gt;
&lt;p&gt;Adding the &lt;span class="code"&gt;Print&lt;/span&gt; operation on the &lt;span class="code"&gt;Expr&lt;/span&gt; type doesn't 
require any modifications to &lt;span class="code"&gt;Expr&lt;/span&gt; or
&lt;span class="code"&gt;Evaluate()&lt;/span&gt;. &lt;/p&gt;
&lt;p&gt;Some disadvantages to a procedural approach are,&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;It is difficult to add additional data types (in our example, each data 
	type represents a different operator) because adding a new type affects 
	all operations.&lt;/li&gt;
	&lt;li&gt;Each operation must account for every data type.&lt;/li&gt;
	&lt;li&gt;The internal representation of the data type must be accessible to every 
	operation. This makes even minor changes to the data layout have far 
	reaching effects and often leads to difficult to maintain implementations.&lt;/li&gt;
	&lt;li&gt;It is very difficult, and requires careful planning, to dynamically add 
	data types.&lt;/li&gt;
	&lt;li&gt;Efficient storage of the data types requires variant record support in 
	the language, as discussed in &lt;a href="#note1"&gt;note 1&lt;/a&gt; below, (which can 
	be simulated though inheritance in &lt;i&gt;object-oriented&lt;/i&gt; languages but I 
	don't provide and example of that).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To demonstrate the difficulty of adding a data type, let's add power support. 
&lt;/p&gt;
&lt;blockquote&gt;
&lt;table border="0" id="table2"&gt;
	&lt;tr&gt;
		&lt;td width="100"&gt;&lt;i&gt;expr&lt;/i&gt; ^ &lt;i&gt;expr&lt;/i&gt;&lt;/td&gt;
		&lt;td&gt;Power&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;
&lt;/blockquote&gt;
&lt;p&gt;This represents the expression &lt;i&gt;x&lt;sup&gt;n&lt;/sup&gt;&lt;/i&gt;. To implement this we first we need to modify the enumeration 
to add &lt;span class="code"&gt;Power&lt;/span&gt;,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;enum&lt;/b&gt; Oper { Add, Subtract, Multiply, Divide, Literal, Power }&lt;/pre&gt;
&lt;p&gt;Next we need to add an additional &lt;i&gt;case statement&lt;/i&gt; to &lt;span class="code"&gt;Evaluate()&lt;/span&gt;'s
&lt;i&gt;switch statement&lt;/i&gt;,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;case&lt;/b&gt; Oper.Power: &lt;b&gt;return&lt;/b&gt; Math.Pow(left, right);&lt;/pre&gt;
&lt;p&gt;An finally we need to also add another &lt;i&gt;case statement&lt;/i&gt; to &lt;span class="code"&gt;Print&lt;/span&gt;'s
&lt;i&gt;switch statement &lt;/i&gt;that looks like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;case&lt;/b&gt; Oper.Power: Print.(e.Left); Console.Write(" ^ "); Print(e.Right); &lt;b&gt;break&lt;/b&gt;;&lt;/pre&gt;
&lt;p&gt;Note we had to modify both operations and the &lt;span class="code"&gt;Oper&lt;/span&gt; enumeration. If we had several 
operations, we would have had 
to modify most, if not all, of them. Also, note that the compiler didn't help us 
find any of the places we need to modify since the code was legal after each of the above modifications. 
If we had made the changes to just &lt;span class="code"&gt;Evaluate()&lt;/span&gt; for 
example, the compiler wouldn't have complained, but we would receive a runtime 
error if we called &lt;span class="code"&gt;Print()&lt;/span&gt; with an expression tree 
that contains a &lt;span class="code"&gt;Power&lt;/span&gt; node.&lt;/p&gt;
&lt;p&gt;To learn more about the expression problem and its history, see
&lt;a href="http://www.cs.pomona.edu/~kim/"&gt;Kim Bruce&lt;/a&gt;'s excellent paper,
&lt;a href="http://www.cs.pomona.edu/~kim/README.html#Wood"&gt;Some Challenging Typing 
Issues in Object-Oriented Languages&lt;/a&gt;. Be warned, it will be a bit of a 
spoiler for some of what I will cover.&lt;/p&gt;&lt;hr&gt;
&lt;p&gt;&lt;a name="note1" href="#ref-note1"&gt;1&lt;/a&gt; - A casual observer will notice that 
&lt;span class="code"&gt;Expr&lt;/span&gt; is a bit wasteful in that it allocates 
room for a value for every node instead of only for literals. It also takes up 
space for &lt;span class="code"&gt;Left&lt;/span&gt; and &lt;span class="code"&gt;Right&lt;/span&gt; for literals. In C#, removing this waste is a bit awkward 
to express and makes the &lt;span class="code"&gt;Evaluate()&lt;/span&gt; method more 
complicated, so I ignored the waste in favor of simplicity.&lt;/p&gt;
&lt;p&gt;In C++, this is a bit less awkward, and might look like,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;struct&lt;/b&gt; Expr {
       Oper            oper;
       &lt;b&gt;union&lt;/b&gt; {
            &lt;b&gt;struct&lt;/b&gt; {
                Expr   *left;
                Expr   *right;
            };
            &lt;b&gt;double&lt;/b&gt;      value;
        };
        Expr(Oper oper, Expr *left, Expr *right) { ... }
        Expr(&lt;b&gt;double&lt;/b&gt; value) { ... }
    };&lt;/pre&gt;
&lt;p&gt;with a very similar evaluation function, but for now we will stick with C#. &lt;a href="#ref-note1"&gt;&amp;lt;&amp;lt; back &amp;lt;&amp;lt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a name="note2" href="#ref-note2"&gt;2&lt;/a&gt; - For simplicity, I ignored operator precedence. Later I will present a version of 
this routine that handles precedence correctly. &lt;a href="ref-note2"&gt;&amp;lt;&amp;lt; back &amp;lt;&amp;lt;&lt;/a&gt;&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/e6fb6ded-a66f-4707-97e7-0edaa04b30d9</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>More Cider at the PDC</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/c7cad822-4635-4a4d-b07f-b20559bacfd9</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/c7cad822-4635-4a4d-b07f-b20559bacfd9</link>
      <pubDate>Fri, 28 Oct 2005 01:36:47 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Yet more Cider stuff. Brian and Mark tag teamed together at the PDC to 
present how to add design-time behavior to WPF (Avalon) controls. You can find 
their presentation
&lt;a href="http://microsoft.sitestream.com/PDC05/TLN/TLN319_files/Default.htm#nopreload=1&amp;autostart=1"&gt;
here...&lt;/a&gt; (Maybe &lt;a href="http://www.corbinstreehouse.com/blog"&gt;Corbin&lt;/a&gt; 
will be able to
&lt;a href="http://www.removingalldoubt.com/commentview.aspx/f63c1229-365e-4fba-9765-d21d6a18f9b9"&gt;
view this one&lt;/a&gt; ;-).&lt;/p&gt;
&lt;p&gt;I seem to not be in any of the recent videos. I am really not that bashful. 
Here I am in the audience (Mark points to me). I wasn't on stage because I had 
to leave early to catch a plane. I will probably show up sooner or later in one 
of these.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/c7cad822-4635-4a4d-b07f-b20559bacfd9</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Cider on MSDN</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/f63c1229-365e-4fba-9765-d21d6a18f9b9</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/f63c1229-365e-4fba-9765-d21d6a18f9b9</link>
      <pubDate>Tue, 25 Oct 2005 21:21:43 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Mike Harsh and Mark Boulter demo'ed Cider for MSDN.
&lt;a href="http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20051020CiderMB/manifest.xml"&gt;
Check it out...&lt;/a&gt;&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Mike Harsh and Mark Boulter demo'ed Cider for MSDN.
<a href="http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20051020CiderMB/manifest.xml">
Check it out...</a></p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/f63c1229-365e-4fba-9765-d21d6a18f9b9</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Cider on Channel 9</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/813160b4-a0f5-4392-93ef-45c2c6528f20</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/813160b4-a0f5-4392-93ef-45c2c6528f20</link>
      <pubDate>Tue, 25 Oct 2005 20:14:00 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Mark Boulter and Brian Pepin make an appearance on Channel 9 to explain and 
demo Cider.
&lt;a href="http://channel9.msdn.com/showpost.aspx?postid=129619"&gt;Check 
it out...&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Mark Boulter and Brian Pepin make an appearance on Channel 9 to explain and 
demo Cider.
<a href="http://channel9.msdn.com/showpost.aspx?postid=129619">Check 
it out...</a></p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/813160b4-a0f5-4392-93ef-45c2c6528f20</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Cider architecture</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/25cd872f-3772-404e-8f48-15d9c48f1a68</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/25cd872f-3772-404e-8f48-15d9c48f1a68</link>
      <pubDate>Tue, 25 Oct 2005 09:28:39 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Brian Pepin has started to blog about Cider's architecture.
&lt;a href="http://www.urbanpotato.net/Default.aspx/document/2224"&gt;Check it out...&lt;/a&gt;&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Brian Pepin has started to blog about Cider's architecture.
<a href="http://www.urbanpotato.net/Default.aspx/document/2224">Check it out...</a></p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/25cd872f-3772-404e-8f48-15d9c48f1a68</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>A Tour of XAML - Part III - Type converters</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/504e93e0-6edb-46bc-922c-8d919a04a830</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/504e93e0-6edb-46bc-922c-8d919a04a830</link>
      <pubDate>Sun, 16 Oct 2005 16:38:11 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Fundamentally XAML is an object initialization language. It creates object 
and sets values to properties. XAML, however, is not limit to creating reference types. You can also create instances of any type 
that has an associated type converter. For example, XAML can create an instance of a brush 
with the following code,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Brush&amp;gt;Red&amp;lt;/Brush&amp;gt;&lt;/pre&gt;
&lt;p&gt;which creates a red solid color brush by calling the type converter 
associated with Brush. This means that,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button&amp;gt;
    &amp;lt;Button.Background&amp;gt;
      &amp;lt;Brush&amp;gt;Red&amp;lt;/Brush&amp;gt;
    &amp;lt;Button.Background&amp;gt;
  &amp;lt;/Button&amp;gt;&lt;/pre&gt;
&lt;p&gt;is equivilent to,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button Background=&amp;quot;Red&amp;quot; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;XAML can be used to create value types, such as an integer, through its type 
converter as in, &lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;s:Int32&amp;gt;27&amp;lt;/s:Int32&amp;gt;&lt;/pre&gt;
&lt;p&gt;or a string,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;s:String&amp;gt;It is the time for all good men...&amp;lt;/s:String&amp;gt;&lt;/pre&gt;
&lt;p&gt;by using string's type converter. Note that XAML always refers to the CLR 
name for the type, not a language specific name such as &amp;quot;int&amp;quot; in C# or &amp;quot;Integer&amp;quot; 
in Pascal. Both of these types refer to the System.Int32 class in the CLR and 
XAML uses the CLR name, Int32. Note also that neither the XAML nor the WPF (Avalon) namespaces refer to the System 
namespace in mscorlib.dll where these types live. This mean that somewhere in the document 
you need to declare the prefix. This might look something like:&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;?Mapping ClrNamespace=&amp;quot;System&amp;quot; XmlNamespace=&amp;quot;System&amp;quot; 
  Assembly=&amp;quot;mscorlib&amp;quot;?&amp;gt;
  &amp;lt;Window
    xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;
    xmlns:s="System"&amp;gt;
      &amp;lt;Button&amp;gt;
        &amp;lt;s:String&amp;gt;It is the time for all good men...&amp;lt;/s:String&amp;gt;
      &amp;lt;/Button&amp;gt;
  &amp;lt;/Window&amp;gt;&lt;/pre&gt;
  
&lt;p&gt;Of course, for string, it is easier to write it,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Window xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;Button&amp;gt;It is the time for all good men...&amp;lt;/Button&amp;gt;
  &amp;lt;/Window&amp;gt;&lt;/pre&gt;
&lt;p&gt;but the string for is useful when you want multiple strings in a collection, say, for example, as the content of a list box,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;?Mapping ClrNamespace=&amp;quot;System&amp;quot; XmlNamespace=&amp;quot;System&amp;quot; 
  Assembly=&amp;quot;mscorlib&amp;quot;?&amp;gt;
  &amp;lt;Window
    xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;
    xmlns:s="System"&amp;gt;
      &amp;lt;ListBox&amp;gt;
        &amp;lt;s:String&amp;gt;It is the time for all good men...&amp;lt;/s:String&amp;gt;
        &amp;lt;s:String&amp;gt;to come to the aid of their country.&amp;lt;/s:String&amp;gt;
      &amp;lt;/ListBox&amp;gt;
  &amp;lt;/Window&amp;gt;&lt;/pre&gt;
&lt;p&gt;Note that if this had been written,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Window xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;ListBox&amp;gt;
      It is the time for all good men...
      to come to the aid of their country.
    &amp;lt;/ListBox&amp;gt;
  &amp;lt;/Window&amp;gt;&lt;/pre&gt;
&lt;/body&gt;
&lt;p&gt;the list box would only contain one string, not two. This is because all 
continuous text content is considered one string and not two. If you load this 
in WPF you will also notice that the string get treated as &amp;quot;It is time for all 
good men... to come to the aid of their country&amp;quot; where the spaces and line 
breaks have been collapsed. I will discuss the rules for whitespace 
normalization (collapsing) in a subsequent post. For now, if you are familiar 
with HTML, what XAML does shouldn't come as any surprise.&lt;/p&gt;&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/504e93e0-6edb-46bc-922c-8d919a04a830</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>OOPSLA '05</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/d741b5a4-77d3-47e4-abc1-3b564baea995</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/d741b5a4-77d3-47e4-abc1-3b564baea995</link>
      <pubDate>Fri, 14 Oct 2005 13:21:54 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Next week I will be attending
&lt;a href="http://www.oopsla.org:8080/2005/ShowPage.do?id=Home&amp;referrer=www.removingalldoubt.com"&gt;OOPSLA&lt;/a&gt;. This 
will be my first technical conference where I will just be a regular attendee. I 
have been to more conferences than I can count but I was always there on some 
official reason either as a presenter or booth worker, or there for some special 
event such as to launch a product or attend some award presentation. If you are 
there too, feel free to stop me in the hall.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/d741b5a4-77d3-47e4-abc1-3b564baea995</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Cider demo'ed at the PDC</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/a38162d2-2558-41d5-a6f1-725c781d381c</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/a38162d2-2558-41d5-a6f1-725c781d381c</link>
      <pubDate>Tue, 04 Oct 2005 00:34:22 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;If you missed the PDC and Eric Rudder's keynote address where Cider was 
demonstrated you can watch it &lt;a href="http://msdn.microsoft.com/events/pdc/"&gt;
here&lt;/a&gt;. Mark Boulter demonstrates it with Joe Marini demonstrating Sparkle. 
Their part begins around 37 minutes into the keynote.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>If you missed the PDC and Eric Rudder's keynote address where Cider was 
demonstrated you can watch it <a href="http://msdn.microsoft.com/events/pdc/">
here</a>. Mark Boulter demonstrates it with Joe Marini demonstrating Sparkle. 
Their part begins around 37 minutes into the keynote.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/a38162d2-2558-41d5-a6f1-725c781d381c</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>A Tour of XAML - Part II: Property Elements?</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/aad29f7c-e615-430d-8015-f19eaceb051e</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/aad29f7c-e615-430d-8015-f19eaceb051e</link>
      <pubDate>Wed, 28 Sep 2005 20:36:44 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;XAML provides two ways to set a property, either through a &lt;i&gt;Property 
Attribute&lt;/i&gt; or through a &lt;i&gt;Property Element&lt;/i&gt;. We covered &lt;i&gt;Property 
Attribute&lt;/i&gt;s last time, this time we will focus on the &lt;i&gt;Property Element&lt;/i&gt;.&lt;/p&gt;
&lt;p&gt;A &lt;i&gt;Property Element&lt;/i&gt; is an element that, instead of creating an object 
instance, set the value of a property. The following is equivalent to the 
example given in Part I but uses &lt;i&gt;Property Element&lt;/i&gt;s instead of &lt;i&gt;Property 
Attribute&lt;/i&gt;s.&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;Button.Content&amp;gt;
      Hello, World!
    &amp;lt;/Button.Content&amp;gt;
  &amp;lt;/Button&amp;gt;&lt;/pre&gt;
&lt;p&gt;The loader distinguishes a &lt;i&gt;Object Element&lt;/i&gt; from a &lt;i&gt;Property Element&lt;/i&gt; 
by the presents of the '.' in the name. The first part of the name is a 
reference to a type and the second part, after the dot, refers to the property 
name (we will discuss exactly why this is when we discuss &lt;i&gt;Attached Properties&lt;/i&gt;). Here we use Button in both &lt;i&gt;Property Element&lt;/i&gt;s. &lt;i&gt;Property Element&lt;/i&gt;s 
are necessary when the value of the property cannot be expressed as a string. 
For example, you can use a &lt;i&gt;Property Element&lt;/i&gt; to set the content of a Button 
to be another Button (not sure why you would want that, but suspend disbelieve for 
a second) as in,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;Button.Content&amp;gt;
      &amp;lt;Button Content=&amp;quot;Hello, World!&amp;quot; /&amp;gt;
    &amp;lt;/Button.Content&amp;gt;
  &amp;lt;/Button&amp;gt;&lt;/pre&gt;
&lt;p&gt;This can be written more explicitly as,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;Button.Content&amp;gt;
      &amp;lt;Button&amp;gt;
        &amp;lt;Button.Content&amp;gt;
          Hello, World!
        &amp;lt;/Button.Content&amp;gt;
      &amp;lt;/Button&amp;gt;
    &amp;lt;/Button.Content&amp;gt;
  &amp;lt;/Button&amp;gt;&lt;/pre&gt;
&lt;p&gt;As you can see, using &lt;i&gt;Property Element&lt;/i&gt;s can become a bit repetitive. 
To mitigate this, one of the properties of a class can be designated as 
the &lt;i&gt;Content Property&lt;/i&gt; which tells the load to assign direct content of the element to 
that property. In the case of Button (and all ContentControls) 
the &lt;i&gt;Content Property&lt;/i&gt; is, oddly enough, set to the property named 
Content. This allows us to write something like,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    Hello, World!
  &amp;lt;/Button&amp;gt;&lt;/pre&gt;
&lt;p&gt;for the first example above, and,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;Button&amp;gt;Hello, World!&amp;lt;/Button&amp;gt;
  &amp;lt;/Button&amp;gt;&lt;/pre&gt;
&lt;p&gt;for the second. Most Avalon classes have a &lt;i&gt;Content Property&lt;/i&gt; defined. 
For Panel's, such as DockPanel, Grid, and Canvas, their &lt;i&gt;Content Property&lt;/i&gt; 
is set to their Children collection. Any direct content of a Panel is assumed to 
be content intended for the Children property. This means the following,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;StackPanel xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;Button&amp;gt;OK&amp;lt;/Button&amp;gt;
    &amp;lt;Button&amp;gt;Cancel&amp;lt;/Button&amp;gt;
  &amp;lt;/StackPanel&amp;gt;&lt;/pre&gt;
&lt;p&gt;is an abbreviated version of,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;StackPanel xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;&amp;gt;
    &amp;lt;StackPanel.Children&amp;gt;
      &amp;lt;Button&amp;gt;
        &amp;lt;Button.Content&amp;gt;
          OK
        &amp;lt;/Button.Content&amp;gt;
      &amp;lt;/Button&amp;gt;
      &amp;lt;Button&amp;gt;
        &amp;lt;Button.Content&amp;gt;
          Cancel
        &amp;lt;/Button.Content&amp;gt;
      &amp;lt;/Button&amp;gt;
    &amp;lt;/StackPanel.Children&amp;gt;
  &amp;lt;/StackPanel&amp;gt;&lt;/pre&gt;
&lt;p&gt;Now, with &lt;i&gt;Property Element&lt;/i&gt;s and &lt;i&gt;Content Property Attribute&lt;/i&gt;s and&lt;i&gt; 
Object Element&lt;/i&gt; and &lt;i&gt;Property Attribute&lt;/i&gt; from Part I, we have covered 
the fundamentals of XAML. &lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>XAML provides two ways to set a property, either through a <i>Property 
Attribute</i> or through a <i>Property Element</i>. We covered <i>Property 
Attribute</i>s last time, this time we will focus on the <i>Property Element</i>.</p>
        <p>A <i>Property Element</i> is an element that, instead of creating an object 
instance, set the value of a property. The following is equivalent to the 
example given in Part I but uses <i>Property Element</i>s instead of <i>Property 
Attribute</i>s.</p>
        <pre class="code">  &lt;Button xmlns="http://schemas.microsoft.com/winfx/avalon/2005"&gt;
    &lt;Button.Content&gt;
      Hello, World!
    &lt;/Button.Content&gt;
  &lt;/Button&gt;</pre>
        <p>The loader distinguishes a <i>Object Element</i> from a <i>Property Element</i> 
by the presents of the '.' in the name. The first part of the name is a 
reference to a type and the second part, after the dot, refers to the property 
name (we will discuss exactly why this is when we discuss <i>Attached Properties</i>). Here we use Button in both <i>Property Element</i>s. <i>Property Element</i>s 
are necessary when the value of the property cannot be expressed as a string. 
For example, you can use a <i>Property Element</i> to set the content of a Button 
to be another Button (not sure why you would want that, but suspend disbelieve for 
a second) as in,</p>
        <pre class="code">  &lt;Button xmlns="http://schemas.microsoft.com/winfx/avalon/2005"&gt;
    &lt;Button.Content&gt;
      &lt;Button Content="Hello, World!" /&gt;
    &lt;/Button.Content&gt;
  &lt;/Button&gt;</pre>
        <p>This can be written more explicitly as,</p>
        <pre class="code">  &lt;Button xmlns="http://schemas.microsoft.com/winfx/avalon/2005"&gt;
    &lt;Button.Content&gt;
      &lt;Button&gt;
        &lt;Button.Content&gt;
          Hello, World!
        &lt;/Button.Content&gt;
      &lt;/Button&gt;
    &lt;/Button.Content&gt;
  &lt;/Button&gt;</pre>
        <p>As you can see, using <i>Property Element</i>s can become a bit repetitive. 
To mitigate this, one of the properties of a class can be designated as 
the <i>Content Property</i> which tells the load to assign direct content of the element to 
that property. In the case of Button (and all ContentControls) 
the <i>Content Property</i> is, oddly enough, set to the property named 
Content. This allows us to write something like,</p>
        <pre class="code">  &lt;Button xmlns="http://schemas.microsoft.com/winfx/avalon/2005"&gt;
    Hello, World!
  &lt;/Button&gt;</pre>
        <p>for the first example above, and,</p>
        <pre class="code">  &lt;Button xmlns="http://schemas.microsoft.com/winfx/avalon/2005"&gt;
    &lt;Button&gt;Hello, World!&lt;/Button&gt;
  &lt;/Button&gt;</pre>
        <p>for the second. Most Avalon classes have a <i>Content Property</i> defined. 
For Panel's, such as DockPanel, Grid, and Canvas, their <i>Content Property</i> 
is set to their Children collection. Any direct content of a Panel is assumed to 
be content intended for the Children property. This means the following,</p>
        <pre class="code">  &lt;StackPanel xmlns="http://schemas.microsoft.com/winfx/avalon/2005"&gt;
    &lt;Button&gt;OK&lt;/Button&gt;
    &lt;Button&gt;Cancel&lt;/Button&gt;
  &lt;/StackPanel&gt;</pre>
        <p>is an abbreviated version of,</p>
        <pre class="code">  &lt;StackPanel xmlns="http://schemas.microsoft.com/winfx/avalon/2005"&gt;
    &lt;StackPanel.Children&gt;
      &lt;Button&gt;
        &lt;Button.Content&gt;
          OK
        &lt;/Button.Content&gt;
      &lt;/Button&gt;
      &lt;Button&gt;
        &lt;Button.Content&gt;
          Cancel
        &lt;/Button.Content&gt;
      &lt;/Button&gt;
    &lt;/StackPanel.Children&gt;
  &lt;/StackPanel&gt;</pre>
        <p>Now, with <i>Property Element</i>s and <i>Content Property Attribute</i>s and<i> 
Object Element</i> and <i>Property Attribute</i> from Part I, we have covered 
the fundamentals of XAML. </p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/aad29f7c-e615-430d-8015-f19eaceb051e</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>A Tour of XAML - Part I: What is XAML?</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/e19e14e5-5c03-4385-90a7-d18c4756bd8d</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/e19e14e5-5c03-4385-90a7-d18c4756bd8d</link>
      <pubDate>Sat, 24 Sep 2005 15:25:33 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
Today I begin a tour of XAML. As &lt;a href="http://www.simplegeek.com"&gt;Chris&lt;/a&gt; said, I have been part of 
development of XAML. I came fairly late to the game, however, more closely to the end of 
the Avalon development cycle than at the beginning, and XAML was already fairly 
well defined when I arrived. I did work to push some changes into the language, primarily 
driving consistency and regularity in the language as well as put developing 
features that support versioning and extensibility. We will cover some of those 
things in our tour, but lets start at the beginning.&lt;/p&gt;
&lt;p&gt;The first question we will cover in our tour is what is XAML anyway? Simply, 
XAML is an XML based object initialization language. Its job in life is to 
create a tree of objects. For example, consider the following XAML file,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button Content=&amp;quot;Hello, world!&amp;quot; 
    xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;  This creates an instance of &lt;span class="code"&gt;System.Windows.Controls.Button&lt;/span&gt; and
sets the &lt;span class="code"&gt;Content&lt;/span&gt; property to the sting value
&lt;span class="code"&gt;&amp;quot;Hello, world!&amp;quot;&lt;/span&gt;. The reason &lt;span class="code"&gt;System.Windows.Button&lt;/span&gt; 
is selected and not, say &lt;span class="code"&gt;System.Windows.Forms.Button&lt;/span&gt;,
is because of the &lt;span class="code"&gt;xmlns&lt;/span&gt; declaration in the
&lt;span class="code"&gt;Button&lt;/span&gt; tag. The magic behind the URI &amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot; 
is hidden in the Avalon assemblies themselves. They contain an assembly 
attribute that looks like,&lt;/p&gt;
&lt;pre class="code"&gt;  [assembly: XmlnDefinition(
	&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot;,
	&amp;quot;System.Windows.Controls&amp;quot;)]&lt;/pre&gt;

&lt;p&gt;It actually has several more definitions like this to associate several other CLR 
namespaces with the Avalon XML namespace, but this is the one used above. Because 
&lt;span class="code"&gt;PresentationFramework.dll&lt;/span&gt; is in the GAC or referenced 
by the project if the XAML is compiled into assembly, the Avalon
loader will find the &lt;span class="code"&gt;XmlnsDefinition&lt;/span&gt; in the assembly
and it is able to determine that it is Avalon's button we want to create.&lt;/p&gt;
&lt;p&gt;Now lets take a look at the phrase 
&lt;span class="code"&gt;Content=&amp;quot;Hello, world!&amp;quot;&lt;/span&gt;. This causes the 
loader to look up the property called &lt;span class="code"&gt;Content&lt;/span&gt; and 
sets its value. The &lt;span class="code"&gt;Content&lt;/span&gt; property is introduced in 
&lt;span class="code"&gt;Button&lt;/span&gt;'s &lt;span class="code"&gt;ContentControl&lt;/span&gt; base class and is of type 
&lt;span class="code"&gt;System.Object&lt;/span&gt;. Since there is no applicable type 
converter for &lt;span class="code"&gt;System.Object&lt;/span&gt;, the loader uses the default type of an 
attribute, string, and 
calls the setter method for &lt;span class="code"&gt;Content&lt;/span&gt;. 
Things are slightly more complicated than this, but this should give you the 
basic idea. This gives us an instance of the 
&lt;span class="code"&gt;System.Windows.Controls.Button&lt;/span&gt;
class with its &lt;span class="code"&gt;Content&lt;/span&gt; property set to the value 
&lt;span class="code"&gt;&amp;quot;Hello, world!&amp;quot;&lt;/span&gt;, which is, hopefully, what 
we wanted.&lt;/p&gt;
&lt;p&gt;If we change the XAML to,&lt;/p&gt;
&lt;pre class="code"&gt;  &amp;lt;Button Content=&amp;quot;Hello, world!&amp;quot; IsDefault=&amp;quot;True&amp;quot;
    xmlns=&amp;quot;http://schemas.microsoft.com/winfx/avalon/2005&amp;quot; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;adding the phrase &lt;span class="code"&gt;IsDefault=&amp;quot;True&amp;quot;&lt;/span&gt; which causes 
the loader to find the &lt;span class="code"&gt;IsDefault&lt;/span&gt; property introduced on 
the &lt;span class="code"&gt;Button&lt;/span&gt; class itself. The &lt;span class="code"&gt;IsDefault&lt;/span&gt;
property is of type &lt;span class="code"&gt;System.Boolean&lt;/span&gt; which has a type converter, 
&lt;span class="code"&gt;System.ComponentModel.BooleanConverter&lt;/span&gt;, associated with it. 
The loader will pass the string, &lt;span class="code"&gt;&amp;quot;True&amp;quot;&lt;/span&gt;, to the type
converter associated with the property (or, as in this case, the property's type) prior to setting the property's 
value; after which we will have an instance of the 
&lt;span class="code"&gt;System.Windows.Controls.Button&lt;/span&gt;
class with its &lt;span class="code"&gt;Content&lt;/span&gt; property set to the value 
&lt;span class="code"&gt;&amp;quot;Hello, world!&amp;quot;&lt;/span&gt;, and its &lt;span class="code"&gt;IsDefault&lt;/span&gt; 
property set to &lt;span class="code"&gt;True&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;This time we covered an &lt;i&gt;Object Element&lt;/i&gt;, an XML element used to create 
an object, and we used a &lt;i&gt;Property Attribute&lt;/i&gt;, an XML element used to set 
the value of an object instance's property. Next time we will get use a &lt;i&gt;
Property Element&lt;/i&gt; and take advantage of the &lt;i&gt;Content Property Attribute&lt;/i&gt;.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/e19e14e5-5c03-4385-90a7-d18c4756bd8d</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Cider is Announced</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/7c401e08-3ec1-4e8a-8a87-56f526192a0b</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/7c401e08-3ec1-4e8a-8a87-56f526192a0b</link>
      <pubDate>Sun, 18 Sep 2005 23:07:12 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Cider is now announced! In case you missed it at the PDC, Cider is the code 
name for the Visual Studio Designer for WPF (&lt;a href="http://www.simplegeek.com/PermaLink.aspx/848ef1d4-f694-43ee-92f7-047478b6b894"&gt;pronounced 
Avalon&lt;/a&gt; according to Chris) that will be delivered in Orcas. We also 
announced the Expression product line that includes a different designer called
&lt;a href="http://www.eweek.com/category2/0,1874,1361732,00.asp"&gt;Sparkle&lt;/a&gt;. 
Other than the obvious difference between Sparkle and Cider, Cider is in VS, 
Sparkle is a stand-alone product, Cider will be a designer for developers, 
Sparkle will be a designer targeted at professional designers.&lt;/p&gt;
&lt;p&gt;For those that were asking about what I was working on, I wasn't trying to be 
coy, I just didn't want to spill the beans early. &lt;/p&gt;
&lt;p&gt;I will be more forthcoming in the months ahead and try to keep you up-to-date 
with our progress.&lt;/p&gt;
&lt;p&gt;If I missed you at the PDC, I am sorry about that. Feel free to ask your 
questions here or via e-mail (chuckj directed through microsoft.com).&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Cider is now announced! In case you missed it at the PDC, Cider is the code 
name for the Visual Studio Designer for WPF (<a href="http://www.simplegeek.com/PermaLink.aspx/848ef1d4-f694-43ee-92f7-047478b6b894">pronounced 
Avalon</a> according to Chris) that will be delivered in Orcas. We also 
announced the Expression product line that includes a different designer called
<a href="http://www.eweek.com/category2/0,1874,1361732,00.asp">Sparkle</a>. 
Other than the obvious difference between Sparkle and Cider, Cider is in VS, 
Sparkle is a stand-alone product, Cider will be a designer for developers, 
Sparkle will be a designer targeted at professional designers.</p>
        <p>For those that were asking about what I was working on, I wasn't trying to be 
coy, I just didn't want to spill the beans early. </p>
        <p>I will be more forthcoming in the months ahead and try to keep you up-to-date 
with our progress.</p>
        <p>If I missed you at the PDC, I am sorry about that. Feel free to ask your 
questions here or via e-mail (chuckj directed through microsoft.com).</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/7c401e08-3ec1-4e8a-8a87-56f526192a0b</comments>
      <category>PDC05</category>
    </item>
    <item>
      <title>Off to the PDC</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/23308026-33df-46a1-b084-87ffc686f919</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/23308026-33df-46a1-b084-87ffc686f919</link>
      <pubDate>Fri, 09 Sep 2005 20:54:56 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I am off to PDC. This will be my first PDC as an &amp;quot;insider&amp;quot; instead of a 
regular attendee, I am looking forward to it. We are announcing some very 
exciting things! I am not going to be presenting but I will be available to 
chat. I plan to spend most of my time in the &amp;quot;Big Room&amp;quot;. If you don't know what 
that is now, you will once you get there. I should be easy to spot, I will be 
the guy in a blue Microsoft shirt and tan pants... ;-).&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>I am off to PDC. This will be my first PDC as an "insider" instead of a 
regular attendee, I am looking forward to it. We are announcing some very 
exciting things! I am not going to be presenting but I will be available to 
chat. I plan to spend most of my time in the "Big Room". If you don't know what 
that is now, you will once you get there. I should be easy to spot, I will be 
the guy in a blue Microsoft shirt and tan pants... ;-).</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/23308026-33df-46a1-b084-87ffc686f919</comments>
      <category>PDC05</category>
    </item>
    <item>
      <title>Comment Toggle</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/95840736-15cb-47f7-9079-75cf72236fbc</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/95840736-15cb-47f7-9079-75cf72236fbc</link>
      <pubDate>Sat, 03 Sep 2005 10:48:34 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;When writing a prototype for a syntax highlighter, 
more years ago than I care to admit, I came across an interesting property of 
the two character comment delimiters found in the C family of 
languages as well as Pascal. I have shown this to several people and many had never seen it before 
so I thought I would share it more widely. &lt;/p&gt;
&lt;p&gt;Take C# for example, you can quickly toggle between 
two blocks of code by using the three characters &lt;span class="code"&gt;/*/&lt;/span&gt; 
in the middle. These three characters act as a comment toggle. If you are in a 
block comment, it will terminate the comment, if not, it starts one. This combined 
with the unconditional comment terminator sequence &lt;span class="code"&gt;
/* */&lt;/span&gt; which ensures that the characters follow are not in a block 
comment,&amp;nbsp; but is still a legal sequence of characters outside a comment, you can toggle between 
blocks of code. For example,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;font color="#808080"&gt;/* */&lt;/font&gt;
    Console.WriteLine("Option 1");
    &lt;font color="#808080"&gt;/*/
    Console.WriteLine("Option 2");
    /* */&lt;/font&gt;
&lt;/pre&gt;
&lt;p&gt;This will print “Option 1” to the console. The second
&lt;span class="code"&gt;WriteLine()&lt;/span&gt; is commented out. With a simple 
one character change, removing the trailing “/” in the first comment, will cause 
“Option 2” to print instead.&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;font color="#808080"&gt;/* *
    Console.WriteLine("Option 1");
    /*/&lt;/font&gt;
    Console.WriteLine("Option 2");
    &lt;font color="#808080"&gt;/* */&lt;/font&gt;
&lt;/pre&gt;
&lt;p&gt;The first &lt;span class="code"&gt;WriteLine()&lt;/span&gt; is commented out and the 
second is now not. I use this sometimes to quickly switch between two optional 
implementations of routines when I am rewriting code, or when constructing test 
applications.&lt;/p&gt;
&lt;p&gt;You can use the unconditional comment terminator to alternate between several 
versions such as,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;font color="#808080"&gt;/* */&lt;/font&gt;
    Console.WriteLine("Option 1");
    &lt;font color="#808080"&gt;/* *
    Console.WriteLine("Option 2");
    /* *
    Console.WriteLine("Option 3");
    /* */&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;To select a different option you need to change two characters, such as removing the
trailing "/" of the first comment and adding one to the third, as in,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;font color="#808080"&gt;/* *
    Console.WriteLine("Option 1");
    /* *
    Console.WriteLine("Option 2");
    /* */&lt;/font&gt;
    Console.WriteLine("Option 3");
    /* */&lt;/pre&gt;
&lt;p&gt;which will cause "Option 3" to print instead of "Option 1".&lt;/p&gt;
&lt;p&gt;Pascal can do the same thing with the its block comment as 
in,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;font color="#808080"&gt;(* *)&lt;/font&gt;
    Writeln('Option 1');
    &lt;font color="#808080"&gt;(*)
    Writeln('Option 2');
    (* *)&lt;/font&gt;
&lt;/pre&gt;
&lt;p&gt;Note that some implementations of C and C++ support nested 
comments and, therefore, the sequence &lt;span class="code"&gt;/*/&lt;/span&gt;
 always starts a comment instead of toggling, so this sequence is not as useful.&lt;/p&gt;
&lt;p&gt;The reason this was important to my prototype is a bit hard 
to explain and is not nearly as interesting as the toggle itself.&lt;/p&gt;&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/95840736-15cb-47f7-9079-75cf72236fbc</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Sorting IV - Radix Sort</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/32d21181-1038-4987-b7fe-e073a11a5e0d</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/32d21181-1038-4987-b7fe-e073a11a5e0d</link>
      <pubDate>Sat, 27 Aug 2005 10:01:02 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;So far we have learned a couple things about making algorithms faster from 
sorting,&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Look for relationships in the data (or relationships between the 
	operations performed on the data) you are not taking advantage of. In our 
	case this was the transitive property of comparisons.&lt;/li&gt;
	&lt;li&gt;Try organizing the data differently that might better take advantage of 
	a relationship. In our case, this was a tree instead an array.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To make the sort any faster we need something that can get performing better than an O(N log N). For this we need to take advantage of some 
property of the data we have been ignoring. We have examined some general 
sorting techniques that can be applied to any type of array element as long as 
any two elements can be compared. If, on the other hand, we assume we are sorting 
integers we can get a bit more clever.&lt;/p&gt;
&lt;p&gt;If we have an array of size &lt;i&gt;N&lt;/i&gt; and knew that we that the array contained 
values from &lt;i&gt;1&lt;/i&gt; to &lt;i&gt;N&lt;/i&gt;, we could trivially sort the array by filling 
it with values &lt;i&gt;1&lt;/i&gt; to &lt;i&gt;N&lt;/i&gt;, in order, such as,&lt;/p&gt;
&lt;pre class="code"&gt;  &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; FillArray(&lt;b&gt;int&lt;/b&gt;[] a) {
      &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &lt; a.Length; i++)
          a[i] = i;
  }&lt;/pre&gt;

&lt;p&gt;Even though this isn't very useful, since such a case rarely, if ever, occurs, 
it tells us that if we can make assumptions about the data we are dealing with, 
we can make a radical improvement on the sort. Can we take a similar approach 
with an array that can contain any value of integer? An integer is actually made 
up of 4 bytes (in C#, in other languages your mileage may vary). Each byte 
ranges in value from 0 to 255. If you had 256 buckets, you could put all the 
integers into one of the 256 buckets based on the most significant byte of the 
integer. You could then take one of these buckets and do the same thing each of 
its values using instead the second most significant digits. You can then repeat 
the whole thing 4 times for each of the bytes and you can see you would have the 
array completely sorted but an enormous cost of memory. You could take a 
recursive approach but you would still wind up with at least 1024 (4 * 256) 
buckets active at the same time, but it looks promising since this appears O(N).&lt;/p&gt;
&lt;p&gt;It turns out that we can reduce the bucket count to 256 by starting with the 
least significant byte and ensuring that for subsequent bytes we distribute to 
their buckets in order. Before I explain why this works, lets at some code that 
implements it,&lt;/p&gt;
&lt;pre class="code"&gt;    &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; RadixSort(&lt;b&gt;int&lt;/b&gt;[] a) {
        List&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;[] buckets = &lt;b&gt;new&lt;/b&gt; List&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt[256];

        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; buckets.Length; i++)
            buckets[i] = &lt;b&gt;new&lt;/b&gt; List&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt();

        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; j = 0; j &amp;lt; 4; j++) {

            &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &lt; a.Length; i++) {
                &lt;b&gt;int&lt;/b&gt; index = (a[i] &amp;gt;&amp;gt; j * 8) &amp; 0xFF;
                buckets[index].Add(a[i]);
            }

            &lt;b&gt;int&lt;/b&gt; idx = 0;

            &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; buckets.Length; i++) {
                List&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt; bucket = buckets[i];
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; k = 0; k &amp;lt; bucket.Count; k++)
                    a[idx++] = bucket[k];
                bucket.Clear();
            }
        }
    }&lt;/pre&gt;
&lt;p&gt;This works because after the first pass the entire array is ordered by the 
lowest order byte. This is because we rebuild the array in bucket order, all the 
0 bytes first, 1 bytes after them, etc. The second pass removes the values from the 
array in order and places them in the buckets. Since they are inserted into the 
buckets in sorted order, if we extract them from the buckets in order they will 
still be sorted; therefore, after the second pass we will have an array sorted 
by the lowest two significant digits. The third pass gives us an array sorted by 
the lowest three significant digits, and finally, the last pass gives us a 
sorted array.&lt;/p&gt;
&lt;p&gt;The above algorithm still takes up quite a bit more memory than the original 
array we are sorting. Even though the buckets are not that big they are still a 
lot bigger than the elements themselves (each only 4 bytes). To further reduce 
the size we can take advantage of the fact that the total number of elements in 
all the buckets will be &lt;i&gt;N&lt;/i&gt;. We could use a temporary array the same size 
as the original array for our buckets. The trick with this is to know where each 
bucket should start. To know this we need to know how many items will be in each 
bucket. If we take an additional pass on the data we can use one pass to figure 
out how many items are in each bucket and then, in the second pass, distribute 
the data into each bucket. The following version of the &lt;i&gt;radix sort&lt;/i&gt; takes 
this approach,&lt;/p&gt;
&lt;pre code="class"&gt;        &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; RadixSort(&lt;b&gt;int&lt;/b&gt;[] a) {
            &lt;b&gt;int&lt;/b&gt;[] source = a;
            &lt;b&gt;int&lt;/b&gt;[] destination = &lt;b&gt;new&lt;/b&gt; &lt;b&gt;int&lt;/b&gt;[a.Length];
            &lt;b&gt;int&lt;/b&gt;[] indexes = &lt;b&gt;new&lt;/b&gt; &lt;b&gt;int&lt;/b&gt;[257];

            &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; j = 0; j &amp;lt; 4; j++) {
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; indexes.Length; i++)
                    indexes[i] = 0;
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; a.Length; i++) {
                    &lt;b&gt;int&lt;/b&gt; index = (source[i] &amp;gt;&amp;gt; j * 8) &amp; 0xFF;
                    indexes[index + 1]++;
                }
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 1; i &amp;lt; indexes.Length; i++)
                    indexes[i] += indexes[i - 1];
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; a.Length; i++) {
                    int index = (source[i] &amp;gt;&amp;gt; j * 8) &amp; 0xFF;
                    destination[indexes[index]++] = source[i];
                }
                &lt;b&gt;int&lt;/b&gt;[] temp = source;
                source = destination;
                destination = temp;
            }
        }&lt;/pre&gt;
&lt;p&gt;This algorithm has one overly clever trick; to avoid copies it
uses the original array as the bucket storage for the even passes by swapping 
&lt;span class="code"&gt;source&lt;/span&gt; and &lt;span class="code"&gt;destination&lt;/span&gt;. 
Since it does this, after the last pass the original array will contain the fully sorted 
data. If the key length is odd, the final array would need to be copied from the 
bucket storage array.&lt;/p&gt;
&lt;p&gt;This looks O(N), but is it? As it turns out, for non-duplicate values, it is 
still O(N log N) because it takes O(log N) digits to represent each integer 
value uniquely (here our digits where 0-256 but the above would work with 2 
buckets where we used bits instead of bytes). For each digit we need a pass over 
the data giving us O(N log N). In practice, such as above, the arrays are not 
totally filed to capacity (and if they were, as we also noted above, we could 
use an O(N) algorithm) so the &lt;i&gt;radix sort&lt;/i&gt; tends to perform better than O(N 
log N). Some of the problems with the &lt;i&gt;radix sort&lt;/i&gt; is that it consumes memory proportional to 
the size of the data where a &lt;i&gt;QuickSort&lt;/i&gt; only takes O(log N) amount of data 
(consumed as stack space in my example) and the &lt;i&gt;HeapSort&lt;/i&gt; and &lt;i&gt;Selection 
Sort&lt;/i&gt; take a fixed size of data. Also my naive implementation of the &lt;i&gt;radix 
sort&lt;/i&gt; above doesn't handle negative integers correctly. I will leave why and 
how to correct it as an exercise to the reader ;-).&lt;/p&gt;
&lt;p&gt;Here we have learned a third useful tool to help us make our algorithms 
faster, see if there is some characteristic of the data itself you can take 
advantage of. You will end up with a less reusable algorithm but it might be 
much faster.&amp;nbsp; In my tests, on array sizes of 4,000,000 integers of random 
data, the &lt;i&gt;radix sort&lt;/i&gt; above is about twice as fast as an optimized version 
of a &lt;i&gt;QuickSort&lt;/i&gt;.&lt;/p&gt;&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/32d21181-1038-4987-b7fe-e073a11a5e0d</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Sorting Part III - HeapSort</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/3e3eb1fa-d3c3-4b28-a2a0-c6fa75008555</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/3e3eb1fa-d3c3-4b28-a2a0-c6fa75008555</link>
      <pubDate>Thu, 18 Aug 2005 09:55:29 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;Last time we looked at the QuickSort and found that it was much better, in most cases, 
than the selection sort, but there was still a pathological case where the QuickSort wasn’t 
better. Can we guarantee we &lt;i&gt;are&lt;/i&gt; better than the O(N&lt;span style="font-size: 8pt"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/span&gt;) 
of the selection sort? Can we guarantee O(N log N)? To do this we need to find something in 
QuickSort we can do better. The Achilles’ heal for the QuickSort is selecting the median value 
of the partition. Several techniques have been developed to avoid the worst case 
scenarios (like selecting three values 
and taking the median; in other words, median of three, or just picking a random item in the 
partition) but none of these guarantee O(N log N). We need a more radical approach.&lt;/p&gt;

&lt;p&gt;We need a way of preserving the comparisons; much like QuickSort does, but 
that doesn’t use 
partitions. As is often the case, when you need a radical new approach, you 
should try a different data structure (much like choosing a different coordinate system in calculus). 
If we organize the array into a binary tree, we can find the largest element in the array 
in O(N log N) comparisons. This is because each element only needs to be compared with its 
parents, which is O(log N) comparisons, and we need to do this for every element in the in 
the array, O(N), giving us O(N log N). This sounds promising, but how do you organize an 
array into a binary tree? This is easier than it sounds. If you number an array from &lt;i&gt;1&lt;/i&gt; 
to &lt;i&gt;n&lt;/i&gt;, where each number is the index of the elements in the array, you can treat the 
array as a binary tree by defining the left node of any element &lt;i&gt;i&lt;/i&gt; to be at index 
&lt;i&gt;2i&lt;/i&gt; and the right node to be at &lt;i&gt;2i+1&lt;/i&gt; (or the other way around, if you must, 
but I like to think of the odd children as right). To create the desired tree, we need 
to ensure that for every element in the array at index &lt;i&gt;i&lt;/i&gt;, it is the greater than its 
children. In other words, for all elements of array &lt;i&gt;a&lt;/i&gt;, &lt;i&gt;a&lt;sub&gt;i&lt;/sub&gt; &amp;#8805; 
a&lt;sub&gt;2i&lt;/sub&gt;&lt;/i&gt; for &lt;i&gt;2i &amp;#8804; n&lt;/i&gt; and &lt;i&gt;a&lt;sub&gt;i&lt;/sub&gt; &amp;#8805; a&lt;sub&gt;2i+1&lt;/sub&gt;&lt;/i&gt; 
for &lt;i&gt;2i+1 &amp;#8804; n&lt;/i&gt;. An array that obeys this constraint is called a heap (hence the 
name HeapSort).&lt;/p&gt;

&lt;p&gt;Forming a &lt;i&gt;heap&lt;/i&gt; is fairly straight forward and follows the informal description given 
above; you swap each element, from &lt;i&gt;2&lt;/i&gt; to &lt;i&gt;n&lt;/i&gt;, with its parent until you come across 
a parent that is greater than the element. The algorithm for this might look something like,&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;b&gt;static void&lt;/b&gt; FormHeap(&lt;b&gt;int&lt;/b&gt;[] a) {
        &lt;font color="gray"&gt;// form the heap&lt;/font&gt;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 1; i &lt; a.Length; i++) {
            &lt;b&gt;int&lt;/b&gt; j = i;
            &lt;b&gt;while&lt;/b&gt; (j &gt; 0) {
                &lt;b&gt;int&lt;/b&gt; k = (j + 1) / 2 - 1;
                &lt;b&gt;if&lt;/b&gt; (a[k] &lt; a[j])
                    Swap(a, j, k);
                &lt;b&gt;else&lt;/b&gt;
                    &lt;b&gt;break&lt;/b&gt;;
                j = k;
            }
        }
    }&lt;/pre&gt;

&lt;p&gt;Note, that since C# numbers the array from &lt;i&gt;0&lt;/i&gt; to &lt;i&gt;n-1&lt;/i&gt; instead of from &lt;i&gt;1&lt;/i&gt;
to &lt;i&gt;n&lt;/i&gt;, we need to subtract add one to the index &lt;i&gt;j&lt;/i&gt; and then subtract it again 
while calculating the parent’s index.&lt;/p&gt;

&lt;p&gt;Now that we have the have the greatest element in the array, we know which element should 
be at the end of the array. We need only swap it with the last element of the array to put 
it there, but doing so will violate the &lt;i&gt;heap&lt;/i&gt; constraint above since 
&lt;i&gt;a&lt;sub&gt;n&lt;/sub&gt;&lt;/i&gt; is guaranteed to be less than or equal to both &lt;i&gt;a&lt;sub&gt;2&lt;/sub&gt;&lt;/i&gt; and 
&lt;i&gt;a&lt;sub&gt;3&lt;/sub&gt;&lt;/i&gt;. To restore order back to the &lt;i&gt;heap&lt;/i&gt; we must push the new first 
element down in the heap until it is greater than or equal to both of its children 
or it is childless. This can 
be done by selecting the greatest child and swapping positions with it then repeating until 
it is greater than the children or it has no children. Since we are following a single line 
of succession, an element will only have, at most &lt;i&gt;log&lt;sub&gt;2&lt;/sub&gt;n&lt;/i&gt; generations (or 
levels, as it is more traditional called) below it. This means we can restore order to the 
&lt;i&gt;heap&lt;/i&gt; in O(log N) comparisons.  This might look like,&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;b&gt;static void&lt;/b&gt; ReformHeap(&lt;b&gt;int&lt;/b&gt;[] a, &lt;b&gt;int&lt;/b&gt; i) {
        &lt;b&gt;int&lt;/b&gt; j = 0;
        &lt;b&gt;while&lt;/b&gt; (&lt;b&gt;true&lt;/b&gt;) {
            &lt;b&gt;int&lt;/b&gt; k = (j + 1) * 2 - 1;
            &lt;b&gt;if&lt;/b&gt; (k &gt;= i)
                 &lt;b&gt;break&lt;/b&gt;;
            &lt;b&gt;if&lt;/b&gt; (k + 1 &gt;= i || a[k] &gt; a[k + 1]) {
                &lt;b&gt;if&lt;/b&gt; (a[j] &gt; a[k])
                    &lt;b&gt;break&lt;/b&gt;;
                Swap(a, k, j);
                j = k;
            }
            &lt;b&gt;else&lt;/b&gt; {
                &lt;b&gt;if&lt;/b&gt; (a[j] &gt; a[k + 1])
                    &lt;b&gt;break&lt;/b&gt;;
                Swap(a, k + 1, j);
                j = k + 1;
            }
        }
    }&lt;/pre&gt;

&lt;p&gt;We now need to do this &lt;i&gt;n&lt;/i&gt; times to completely sort the array, meaning that we 
are guaranteed to sort a &lt;i&gt;heap&lt;/i&gt; in O(N log N) comparisons. This gives us O(N log N) 
operations to form a &lt;i&gt;heap&lt;/i&gt; and O(N log N) operations to sort a &lt;i&gt;heap&lt;/i&gt; which means 
that we can sort any array, using a &lt;i&gt;heap&lt;/i&gt; in O(N log N) (since big O notation throws 
away the constant 2 in 2N log N). Putting this together gives us the &lt;i&gt;HeapSort&lt;/i&gt; invented 
by J.W.J. Williams,&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;b&gt;static void&lt;/b&gt; HeapSort(&lt;b&gt;int&lt;/b&gt;[] a) {
        &lt;font color="gray"&gt;// form the heap&lt;/font&gt;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 1; i &lt; a.Length; i++) {
            &lt;b&gt;int&lt;/b&gt; j = i;
            &lt;b&gt;while&lt;/b&gt; (j &gt; 0) {
                &lt;b&gt;int&lt;/b&gt; k = (j + 1) / 2 - 1;
                &lt;b&gt;if&lt;/b&gt; (a[k] &lt; a[j])
                    Swap(a, j, k);
                &lt;b&gt;else&lt;/b&gt;
                    &lt;b&gt;break&lt;/b&gt;;
                j = k;
            }
        }

        &lt;font color="gray"&gt;// Pick the top of the heap and place it last, reform the 
        // heap, then take the new top and place it next to last.&lt;/font&gt;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = a.Length - 1; i &gt; 0; i--) {
            &lt;font color="gray"&gt;// The top of the heap contains the highest value, swap
            // it the last member&lt;/font&gt;
            Swap(a, 0, i);
            &lt;font color="gray"&gt;// Reform the heap it. It contains a relatively low
            // value on top. Replace it with the greatest child.&lt;/font&gt;
            &lt;b&gt;int&lt;/b&gt; j = 0;
            &lt;b&gt;while&lt;/b&gt; (&lt;b&gt;true&lt;/b&gt;) {
                &lt;b&gt;int&lt;/b&gt; k = (j + 1) * 2 - 1;
                &lt;b&gt;if&lt;/b&gt; (k &gt;= i)
                    &lt;b&gt;break&lt;/b&gt;;
                &lt;b&gt;if&lt;/b&gt; (k + 1 &gt;= i || a[k] &gt; a[k + 1]) {
                    &lt;b&gt;if&lt;/b&gt; (a[j] &gt; a[k])
                        &lt;b&gt;break&lt;/b&gt;;
                    Swap(a, k, j);
                    j = k;
                }
                &lt;b&gt;else&lt;/b&gt; {
                    &lt;b&gt;if&lt;/b&gt; (a[j] &gt; a[k + 1])
                        &lt;b&gt;break&lt;/b&gt;;
                    Swap(a, k + 1, j);
                    j = k + 1;
                }
            }
        }
    }&lt;/pre&gt;

&lt;p&gt;Here we have it. An algorithm that is guaranteed to perform on the order of O(N log N) 
operations to sort an array! And here, you are apt to say, “Why doesn’t everyone use a 
HeapSort instead of a QuickSort if HeapSort is so much better?” Good question, I am glad you 
asked. There are several reasons why, but I will save that for another time.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/3e3eb1fa-d3c3-4b28-a2a0-c6fa75008555</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Sorting Part II - QuickSort</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/b7b8e6b0-7ce9-49cb-9a8f-3e0c1ba9e405</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/b7b8e6b0-7ce9-49cb-9a8f-3e0c1ba9e405</link>
      <pubDate>Sat, 13 Aug 2005 10:53:15 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;As we noted in Part I, a selection sort is an easy sort to write but 
unfortunately it performs on the order of &lt;i&gt;n&lt;span style="font-size: 8pt"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/span&gt;&lt;/i&gt; 
comparisons.  To produce an improved version we need to find a piece of information 
that the selection sort is throwing away and take advantage of it.&lt;/p&gt;

&lt;p&gt;Selection sort will compare a value of the array with all of the other values of 
the array to determine which is the smallest. It doesn’t take advantage to the fact that 
comparing say, &lt;i&gt;a&lt;span style="font-size: 8pt"&gt;&lt;sub&gt;10&lt;/sub&gt;&lt;/span&gt;&lt;/i&gt; to 
&lt;i&gt;a&lt;span style="font-size: 8pt"&gt;&lt;sub&gt;20&lt;/sub&gt;&lt;/span&gt;&lt;/i&gt; and comparing 
&lt;i&gt;a&lt;span style="font-size: 8pt"&gt;&lt;sub&gt;20&lt;/sub&gt;&lt;/span&gt;&lt;/i&gt; to, say, 
&lt;i&gt;a&lt;span style="font-size: 8pt"&gt;&lt;sub&gt;40&lt;/sub&gt;&lt;/span&gt;&lt;/i&gt; could tell us something about 
the relationship between &lt;i&gt;a&lt;span style="font-size: 8pt"&gt;&lt;sub&gt;10&lt;/sub&gt;&lt;/span&gt;&lt;/i&gt; and 
&lt;i&gt;a&lt;span style="font-size: 8pt"&gt;&lt;sub&gt;40&lt;/sub&gt;&lt;/span&gt;&lt;/i&gt;. What we could do is take some 
element of &lt;i&gt;a&lt;/i&gt; and compare it to every other element in &lt;i&gt;a&lt;/i&gt; and partition the array into two 
pieces, one containing all the elements less than the selected element and all elements 
greater than or equal to the selected element. By transitivity, we would know that each 
element in the first partition is less than all elements in the second partition even if 
we don’t compare them directly. We could then partition the partitions again and again, in Xeno-esque fashion, until the array only contains partitions of one element in length. Since 
each partition will be less than its successor, the array will be sorted.&lt;/p&gt;

&lt;p&gt;An algorithm that takes this very approach is the QuickSort, invented by C.A.R. Hoare. A 
version of which looks like the following,&lt;/p&gt;
&lt;pre&gt;    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Sorts {

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; QuickSort(&lt;b&gt;int&lt;/b&gt;[] a) {
            QSort(a, 0, a.Length - 1);
        }

        &lt;b&gt;private&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; QSort(&lt;b&gt;int&lt;/b&gt;[] a, &lt;b&gt;int&lt;/b&gt; l, &lt;b&gt;int&lt;/b&gt; r) {
            &lt;font color="#808080"&gt;// Partition the array into two parts, one with all values 
            // greater than a certain value in the array, one with all 
            // less.&lt;/font&gt;
            &lt;b&gt;int&lt;/b&gt; v = a[(l + r) / 2];
            &lt;b&gt;int&lt;/b&gt; i = l;
            &lt;b&gt;int&lt;/b&gt; j = r;
            &lt;b&gt;while&lt;/b&gt; (i &lt; j) {
                &lt;font color="#808080"&gt;// Find the first values that don't belong and swap 
                // them. Repeat until all values are in the right 
                // partitions.&lt;/font&gt;
                &lt;b&gt;while&lt;/b&gt; (a[i] &lt; v)
                    i++;
                &lt;b&gt;while&lt;/b&gt; (a[j] &gt; v)
                    j--;
                &lt;b&gt;if&lt;/b&gt; (i &lt;= j) {
                    &lt;b&gt;if&lt;/b&gt; (j &gt; i)
                        Swap(a, i, j);
                    i++;
                    j--;
                }
            }
            &lt;font color="#808080"&gt;// Recursively partition the array until we can't any 
            // longer. When this happens, the array is sorted.&lt;/font&gt;
            &lt;b&gt;if&lt;/b&gt; (j &gt; l)
                QSort(a, l, j);
            &lt;b&gt;if&lt;/b&gt; (r &gt; i)
                QSort(a, i, r);
        }
    }&lt;/pre&gt;
    
&lt;p&gt;If we get lucky and always guess the median value of each of the partitions we will only perform 
O(N log N) comparisons. The worst thing we can do is select a value that, given an &lt;i&gt;n&lt;/i&gt; length 
partition will give us two partitions one of length &lt;i&gt;n-1&lt;/i&gt; and the other of length 1. This would 
put us back where we started; with the selection sort. This would happen if we selected the first 
(or last) element in the partition and the array was already sorted. To avoid this, the above code 
selects an element from the middle of the partition, so, if the array is sorted, it will be the 
median. If the array is in random order, it is not better or worse than the first element.&lt;/p&gt;

&lt;p&gt;This, however, doesn’t guarantee we will get the elusive O(N log N) performance. Many cases we 
will be less than O(N log N), those cases where we don’t magically pick the median. In some 
pathological cases, we could arrive very close to O(N&lt;span style="font-size: 8pt"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/span&gt;). 
An example of which is an array ordered 1..&lt;i&gt;m&lt;/i&gt;,1..&lt;i&gt;m&lt;/i&gt; where &lt;i&gt;m&lt;/i&gt; is &lt;i&gt;n/2&lt;/i&gt;. Next 
we will examine an algorithm that guarantees O(N log N) performance.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/b7b8e6b0-7ce9-49cb-9a8f-3e0c1ba9e405</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Sorting Part I - Selection Sort</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/8fbe8b14-f163-48e5-afc7-ac3390ce3b84</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/8fbe8b14-f163-48e5-afc7-ac3390ce3b84</link>
      <pubDate>Thu, 11 Aug 2005 23:49:38 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;When I run across a particularly fast elegant algorithm I often find 
myself asking, “Why it is fast?” How can I make my algorithms fast like the 
author of this one did? I have found that the answer usually is found in how the 
algorithm manages data. How does the algorithm preserve work and prevent 
recalculating information? To step back a bit, there are only three ways to make 
some code go faster, find a way to make what it is doing faster, find a way to 
do less, find some other time to do it. The most elegant algorithms do the 
second well; they do less. For a few entries I want to look at various 
algorithms to see what makes them fast (or not so fast).&lt;/p&gt;
&lt;p&gt;The first set of algorithms I want to investigate are some of the most 
fundamental, sorting. The simplest sort to write is the selection sort. In C# it 
looks like,&lt;/p&gt;
&lt;pre class="code"&gt;
  &lt;b&gt;static void&lt;/b&gt; SelectionSort(&lt;b&gt;int&lt;/b&gt;[] a) {
         &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; a.Length - 1; i++)
             &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; j = i + 1; j &amp;lt; a.Length; j++)
                 &lt;b&gt;if&lt;/b&gt; (a[i] &amp;gt; a[j])
                     Swap(a, i, j);
  }&lt;/pre&gt;
&lt;p&gt;where Swap looks like,&lt;/p&gt;
&lt;pre class="code"&gt;  &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Swap&amp;lt;T&amp;gt;(T[] a, &lt;b&gt;int&lt;/b&gt; i, &lt;b&gt;int&lt;/b&gt; j) {
      T v = a[i];
      a[i] = a[j];
      a[j] = v;
  }&lt;/pre&gt;
&lt;p&gt;This sort finds the smallest item in the list and puts it first, and then it 
finds the second smallest and puts it second, etc. Even though it is very easy 
to write and relatively easy to verify, it isn’t very fast. We could improve 
this by in-lining the Swap() method. Additionally, we can limit the number of 
swaps to a.Length by only swapping the value we know is the smallest. A version 
that includes both optimizations is,&lt;/p&gt;
&lt;pre class="code"&gt;  &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; ImprovedSelectionSort(&lt;b&gt;int&lt;/b&gt;[] a) {
      &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; a.Length - 1; i++) {
          &lt;b&gt;int&lt;/b&gt; min = i;
          &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; j = i + 1; j &amp;lt; a.Length; j++)
              &lt;b&gt;if&lt;/b&gt; (a[min] &amp;gt; a[j])
                  min = j;
          &lt;b&gt;if&lt;/b&gt; (i == min) &lt;b&gt;continue&lt;/b&gt;;
          &lt;b&gt;int&lt;/b&gt; v = a[i];
          a[i] = a[min];
          a[min] = v;
      }
  }&lt;/pre&gt;
&lt;p&gt;These optimizations are examples of making what we are doing faster. 
Unfortunately, we still with do on the order of O(N&lt;span style="font-size: 8pt"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/span&gt;) 
comparisons even though we reduced the number of moves to O(N) and removed any overhead of doing a call in 
the middle of the loop. What we really want to do is less. To do less we need to 
come up with information we are not using or information we are throwing away.&lt;/p&gt;
&lt;p&gt;Since we are trying to optimize the number of comparisons (since we got the 
moves down to O(N)) we should examine them closely. We need to come up with a 
way to make each comparison do more. One thing we should notice is the above 
algorithm totally ignores the transitive nature of a compare. That is if A &amp;gt; B 
and B &amp;gt; C then A &amp;gt; C. If we know that a[10] &amp;gt; a[11] and a[11] &amp;gt; a[12] we don’t 
need to physically do the comparison between a[10] and a[12] to know at a[10] &amp;gt; 
a[12], but how do we take advantage of that? In my next &amp;quot;sorting&amp;quot; post I will investigate 
an algorithm that takes advantage of this.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>When I run across a particularly fast elegant algorithm I often find 
myself asking, “Why it is fast?” How can I make my algorithms fast like the 
author of this one did? I have found that the answer usually is found in how the 
algorithm manages data. How does the algorithm preserve work and prevent 
recalculating information? To step back a bit, there are only three ways to make 
some code go faster, find a way to make what it is doing faster, find a way to 
do less, find some other time to do it. The most elegant algorithms do the 
second well; they do less. For a few entries I want to look at various 
algorithms to see what makes them fast (or not so fast).</p>
        <p>The first set of algorithms I want to investigate are some of the most 
fundamental, sorting. The simplest sort to write is the selection sort. In C# it 
looks like,</p>
        <pre class="code">
          <b>static void</b> SelectionSort(<b>int</b>[] a) {
         <b>for</b> (<b>int</b> i = 0; i &lt; a.Length - 1; i++)
             <b>for</b> (<b>int</b> j = i + 1; j &lt; a.Length; j++)
                 <b>if</b> (a[i] &gt; a[j])
                     Swap(a, i, j);
  }</pre>
        <p>where Swap looks like,</p>
        <pre class="code">
          <b>static</b>
          <b>void</b> Swap&lt;T&gt;(T[] a, <b>int</b> i, <b>int</b> j) {
      T v = a[i];
      a[i] = a[j];
      a[j] = v;
  }</pre>
        <p>This sort finds the smallest item in the list and puts it first, and then it 
finds the second smallest and puts it second, etc. Even though it is very easy 
to write and relatively easy to verify, it isn’t very fast. We could improve 
this by in-lining the Swap() method. Additionally, we can limit the number of 
swaps to a.Length by only swapping the value we know is the smallest. A version 
that includes both optimizations is,</p>
        <pre class="code">
          <b>static</b>
          <b>void</b> ImprovedSelectionSort(<b>int</b>[] a) {
      <b>for</b> (<b>int</b> i = 0; i &lt; a.Length - 1; i++) {
          <b>int</b> min = i;
          <b>for</b> (<b>int</b> j = i + 1; j &lt; a.Length; j++)
              <b>if</b> (a[min] &gt; a[j])
                  min = j;
          <b>if</b> (i == min) <b>continue</b>;
          <b>int</b> v = a[i];
          a[i] = a[min];
          a[min] = v;
      }
  }</pre>
        <p>These optimizations are examples of making what we are doing faster. 
Unfortunately, we still with do on the order of O(N<span style="font-size: 8pt"><sup>2</sup></span>) 
comparisons even though we reduced the number of moves to O(N) and removed any overhead of doing a call in 
the middle of the loop. What we really want to do is less. To do less we need to 
come up with information we are not using or information we are throwing away.</p>
        <p>Since we are trying to optimize the number of comparisons (since we got the 
moves down to O(N)) we should examine them closely. We need to come up with a 
way to make each comparison do more. One thing we should notice is the above 
algorithm totally ignores the transitive nature of a compare. That is if A &gt; B 
and B &gt; C then A &gt; C. If we know that a[10] &gt; a[11] and a[11] &gt; a[12] we don’t 
need to physically do the comparison between a[10] and a[12] to know at a[10] &gt; 
a[12], but how do we take advantage of that? In my next "sorting" post I will investigate 
an algorithm that takes advantage of this.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/8fbe8b14-f163-48e5-afc7-ac3390ce3b84</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>My Life as a GUI Builder Builder</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/fe06fae0-3fb8-483f-8b27-f9361c60d022</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/fe06fae0-3fb8-483f-8b27-f9361c60d022</link>
      <pubDate>Sat, 30 Jul 2005 23:42:12 GMT</pubDate>
      <description>A response to Hacknot's "Beware the GUI Builder" by a Builder of GUI Builders</description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/fe06fae0-3fb8-483f-8b27-f9361c60d022</comments>
      <category>Programming</category>
    </item>
  </channel>
</rss>