<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Aspiring Craftsman</title>
	
	<link>http://www.aspiringcraftsman.com</link>
	<description>pursuing well-crafted software</description>
	<lastBuildDate>Fri, 13 Aug 2010 15:22:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/AspiringCraftsman" /><feedburner:info uri="aspiringcraftsman" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Windows-Friendly Cygwin Paths</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/_6GE-Y5xxm8/</link>
		<comments>http://www.aspiringcraftsman.com/2010/07/windows-friendly-cygwin-paths/#comments</comments>
		<pubDate>Fri, 09 Jul 2010 16:29:20 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=383</guid>
		<description><![CDATA[Not too long ago, I ventured into using Rake for my .Net project builds.&#160; Given that my shell preference on Windows is Cygwin’s bash port (via the excellent mintty terminal), I tend to prefer installing the Cygwin ruby package rather than using the RubyInstaller for Windows. One issue I ran into, however, was that the [...]]]></description>
			<content:encoded><![CDATA[<p>Not too long ago, I ventured into using Rake for my .Net project builds.&#160; Given that my shell preference on Windows is Cygwin’s bash port (via the excellent <a href="http://code.google.com/p/mintty/">mintty</a> terminal), I tend to prefer installing the Cygwin ruby package rather than using the <a href="http://rubyinstaller.org/">RubyInstaller for Windows</a>.</p>
<p>One issue I ran into, however, was that the absolute paths generated under rake resolve to /cygdrive/c/ by default.&#160; This isn’t an issue when calling applications compiled for Cygwin, but they pose a problem if you need to pass an absolute path as a parameter to commands like MSBuild.&#160; One way to resolve this problem is to create an NTFS mount point which mirrors a path that Windows executables can resolve.&#160; Here’s how:<br />
  </p>
<p>Open up the file /etc/fstab which configures the mount table under Cygwin.&#160; Add a line similar to the following:</p>
<pre class="brush: bash;">
C:/projects /projects ntfs binary,posix=0,user 0 0
</pre>
<p>This mounts the C:/projects folder (where I do all of my project development) as /projects.&#160; Note that the mount point must be named the same as the actual physical NTFS path.&#160; After restarting the shell, the new mount point will be available.&#160; This can be verified by issuing the mount command:</p>
<pre >
> mount
C:/cygwin/bin on /usr/bin type ntfs (binary,auto)
C:/cygwin/lib on /usr/lib type ntfs (binary,auto)
C:/projects on /projects type ntfs (binary,posix=0,user)
C:/cygwin on / type ntfs (binary,auto)
C: on /cygdrive/c type ntfs (binary,posix=0,user,noumount,auto)
D: on /cygdrive/d type iso9660 (binary,posix=0,user,noumount,auto)
F: on /cygdrive/f type iso9660 (binary,posix=0,user,noumount,auto)
G: on /cygdrive/g type ntfs (binary,posix=0,user,noumount,auto)
H: on /cygdrive/h type ntfs (binary,posix=0,user,noumount,auto)
I: on /cygdrive/i type vfat (binary,posix=0,user,noumount,auto)</pre>
<p></p>
<p>Since Windows accepts the forward slash as a directory delimiter and considers drive letters to be optional, expanding a relative path under the NTFS mount point will render a path that can be correctly interpreted by Windows executables.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/_6GE-Y5xxm8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/07/windows-friendly-cygwin-paths/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/07/windows-friendly-cygwin-paths/</feedburner:origLink></item>
		<item>
		<title>NCommons Rules Engine</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/FVVBLmUNfhw/</link>
		<comments>http://www.aspiringcraftsman.com/2010/06/ncommons-rules-engine/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 12:01:26 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[NCommons]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=360</guid>
		<description><![CDATA[I recently decided to invest some time to learn how my team might leverage the MvcContrib rules engine for our projects at work. I discovered this feature after browsing the CodeCampServer source which seems to be the only publicly available example of the rules engine in use. I was impressed at how clean the controller [...]]]></description>
			<content:encoded><![CDATA[<p>I recently decided to invest some time to learn how my team might leverage the <a href="http://mvccontrib.codeplex.com/" target="_blank">MvcContrib</a> rules engine for our projects at work. I discovered this feature after browsing the <a href="http://codecampserver.codeplex.com/" target="_blank">CodeCampServer</a> source which seems to be the only publicly available example of the rules engine in use. I was impressed at how clean the controller actions were as a result of leveraging this feature in conjunction with some additional infrastructure sugar the CodeCampServer adds.</p>
<p>While I liked the capabilities of the MvcContrib rules engine overall, there  were a few aspects I wanted to change.  One of those things was the coupling to  the validation strategy provided by the rules engine and another was the need  for a bit of additional infrastructure code to help parse the results when  mapping validation errors back to their corresponding UI elements.</p>
<p>I also recently became aware of the <a href="http://fluentvalidation.codeplex.com/" target="_blank">Fluent Validation</a> library by Jeremy Skinner and thought to myself: &#8220;<em>I wonder how long it would  take to just create my own rules engine leveraging the Fluent Validation  framework</em>&#8220;, so I sat down last weekend to find out. Well, after getting  something up and going, I thought I might as well share my results. I should  note that given my effort was inspired by the MvcContrib rules engine, some of  the same concepts are reflected in my effort (though perhaps with a more naive  implementation).</p>
<h2>Overview</h2>
<p>The basic rules engine works as follows:</p>
<ol>
<li>A user invokes some Controller action.</li>
<li>The Controller takes the action&#8217;s parameter and invokes the RulesEngine.Process() method.</li>
<li>The RulesEngine invokes an injected implementation of IRuleValidator.Validate() on the object.</li>
<li>The IRulesValidator returns a RuleValidationResult denoting the status of the validation as well as containing any validation error messages.</li>
<li>The RulesEngine uses the Common Service Locator to find implementations of ICommand&lt;T&gt; where T matches the type of the object.</li>
<li>The implementations of ICommand&lt;T&gt; are executed and any results accumulated.</li>
<li>The RulesEngine returns a ProcessResult which contains the process status and any validation messages and return items.</li>
<li>The Controller uses the status to determine which action to display. In the event of a validation failure, the error messages are added to the ModelState with their associated property names.</li>
</ol>
<p>Here is an example usage:</p>
<pre class="brush: csharp;">
[HttpPost]
public ActionResult Create(ProductInput productInput)
{
    ProcessResult results = _rulesEngine.Process(productInput);

    if (!results.Successful)
    {
        CopyValidationErrors(results);
        return View(productInput);
    }

    return RedirectToAction(&quot;Index&quot;);
}

void CopyValidationErrors(ProcessResult results)
{
    foreach (RuleValidationFailure failure in results.ValidationFailures)
    {
        ModelState.AddModelError(failure.PropertyName, failure.Message);
    }
}
</pre>
<p>In an example application I&#8217;ve included with the source, I created an implementation of the IRulesValidator which adapts to the Fluent Validation library:</p>
<pre class="brush: csharp;">
public class FluentValidationRulesValidator : IRulesValidator
{
    public RuleValidationResult Validate(object message)
    {
        var result = new RuleValidationResult();
        Type validatorType = typeof (AbstractValidator&lt;&gt;).MakeGenericType(message.GetType());
        var validator = (IValidator) ServiceLocator.Current.GetInstance(validatorType);
        ValidationResult validationResult = validator.Validate(message);

        if (!validationResult.IsValid)
        {
            foreach (ValidationFailure error in validationResult.Errors)
            {
                var failure = new RuleValidationFailure(error.ErrorMessage, error.PropertyName);
                result.AddValidationFailure(failure);
            }
        }

        return result;
    }
}
</pre>
<p>This uses the Common Service Locator to find types closing the Fluent Validation AbstractValidator generic type, validates the message with the validator, and adds any validation error messages to the RuleValidationResult.</p>
<h2>Mapping</h2>
<p>I also included the ability to map UI types to domain types using a library such as <a href="http://automapper.codeplex.com/" target="_blank">AutoMapper</a>. To express this as an optional feature, I created a MappingRulesEngine which has a dependency on an IMessageMapper. At first I went back and forth between expressing an IMessageMapper as an optional dependency to the RulesEngine, but I don&#8217;t really like property injection and the notion of using constructor injection for optional dependencies was a bit distasteful, so using inheritance felt like the cleanest and most expressive option.</p>
<p>The MappingRulesEngine uses the Common Service Locator to find a type closing AssociationConfiguration&lt;T&gt; which provides the type to be converted to as well as configuration used by the MappingRulesEngine to associate validation error messages on the domain type back to the origin properties on the UI type. The following is an example usage:</p>
<pre class="brush: csharp;">
public class ProductInputAssociationConfiguration : AssociationConfiguration&lt;ProductInput&gt;
{
    public ProductInputAssociationConfiguration()
    {
        ConfigureAssociationsFor&lt;Product&gt;(x =&gt;
            {
                x.For(output =&gt; output.Id).Use(input =&gt; input.Id);
                x.For(output =&gt; output.Description).Use(input =&gt; input.Description);
                x.For(output =&gt; output.Price).Use(input =&gt; input.Price);
            });
    }
}
</pre>
<p>That&#8217;s about it. You can get the source at <a href="http://github.com/derekgreer/ncommons" target="_blank">http://github.com/derekgreer/ncommons</a>.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/FVVBLmUNfhw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/06/ncommons-rules-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/06/ncommons-rules-engine/</feedburner:origLink></item>
		<item>
		<title>The Agile Visitor</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/r3lGL89MI0A/</link>
		<comments>http://www.aspiringcraftsman.com/2010/04/the-agile-visitor/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 13:52:32 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Visitor]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=343</guid>
		<description><![CDATA[When working with object structures, you may at times encounter the need to perform some operation across all the elements within the structure. For instance, given a compound piece of machinery, you may want to perform some operation which requires examining each part to create a parts manifest, compute the total price, or determine which [...]]]></description>
			<content:encoded><![CDATA[<p>When working with object structures, you may at times encounter the need to perform some operation across all the elements within the structure.  For instance, given a compound piece of machinery, you may want to perform some operation which requires examining each part to create a parts manifest, compute the total price, or determine which parts may need special storage or handling needs.</p>
<p>There may also be a need to easily add new cross-cutting operations across the elements which either aren&#8217;t related to the inherent responsibility of each of the elements and/or when no common base object exists allowing inheritance of the new behavior. The <a href="http://en.wikipedia.org/wiki/Visitor_pattern" target="_blank">Visitor</a> pattern is one approach which aids in facilitating these kinds of needs.</p>
<h2>The Visitor Pattern</h2>
<p>The Visitor pattern encapsulates common behavior within a single class which is applied to each of the elements of the object structure. The following diagram depicts the pattern structure:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/VisitorClassDiagram.png"><img class="alignnone size-full wp-image-344" title="VisitorClassDiagram" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/VisitorClassDiagram.png" alt="" width="590" height="548" /></a></p>
<p><a href="$VisitorClassDiagram7.png"><br />
</a></p>
<p>The Visitor pattern is comprised of three main types of participants: the Visitor, the Element, and the Object Structure. The Visitor encapsulates the common behavior needed across different types of elements.  Elements are the types within an object structure for which common behavior is needed.  The Object Structure is the element container and may take the form of a collection or composite.</p>
<p>Each visitor defines methods specific to each type of element within the object structure while elements define a method capable of accepting a Visitor.  When a client desires to apply the visitor behavior to each of the elements, the object structure is used to orchestrate delivery of the visitor to each element.  Upon receiving the visitor, each element calls a corresponding method on the visitor, passing a reference to itself as the method parameter.  Once invoked, the visitor&#8217;s methods are capable of accessing state or invoking behavior specific to each type of element.</p>
<div class="theme-note">
<p><strong>Sidebar</strong></p>
<p>When first encountering the Visitor pattern, some may wonder why each element is implemented with an <em>Accept(Visitor)</em> method as opposed to just having the object structure pass each of the elements directly to the visitor.  At first, this may seem to unnecessarily couple the elements to the visitor.This approach stems from the fact that many programming languages don&#8217;t support dynamic binding for method overloads.  That is to say, the method invoked on an object is determined at compile time based upon the reference type of the method parameters, not at run-time based upon the type of the referenced object.  When implementing the Visitor pattern in such cases, if an object structure were to pass in each element referenced through a common interface then only a Visitor method defined specifically for that interface type could be invoked.</p>
<p>To overcome this limitation, a technique known as <a href="http://www.aspiringcraftsman.com/2010/04/double-dispatch-is-a-code-smell/" target="_blank">Double Dispatch</a> is used to ensure that the correct Visitor method is statically dispatched.</p>
<p>As of C# 4.0, the <a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx" target="_blank">dynamic</a> keyword can be used as an alternate strategy to the traditional double dispatch pattern allowing the elements to be free of any coupling imposed by the classic Visitor pattern implementation.</p>
</div>
<p>The following is an example application which uses the classic Visitor pattern structure to print a parts manifest and a dangerous goods manifest for a thermostat:</p>
<pre class="brush: csharp;">
class Program
    {
        static void Main(string[] args)
        {
            var thermostat = new Thermostat();
            var partsManifestVisitor = new PartsManifestVisitor();
            var dangerousGoodsManifestVisitor = new DangerousGoodsManifestVisitor();
            thermostat.Accept(partsManifestVisitor);
            thermostat.Accept(dangerousGoodsManifestVisitor);

            Console.WriteLine(&quot;Parts List&quot;);
            Console.WriteLine(&quot;----------&quot;);
            partsManifestVisitor.PrintManifest(Console.Out);

            Console.WriteLine(&quot;\nDangerous Goods List&quot;);
            Console.WriteLine(&quot;----------&quot;);
            dangerousGoodsManifestVisitor.PrintManifest(Console.Out);

            Console.ReadLine();
        }
    }

    interface IComponentVisitor
    {
        void Visit(Thermostat thermostat);
        void Visit(ThermostatCover thermostatCover);
        void Visit(CircutBoard circutBoard);
        void Visit(MercurySwitch mercurySwitch);
        void Visit(BimetallicStrip bimetallicStrip);
        void Visit(HeatAnticipator heatAnticipator);
    }

    interface IComponentElement
    {
        void Accept(IComponentVisitor visitor);
    }

    class Thermostat : IComponentElement
    {
        readonly IComponentElement[] _elements;

        public Thermostat()
        {
            _elements = new IComponentElement[]
                           {
                                new ThermostatCover(),
                                new CircutBoard(),
                               new MercurySwitch(),
                               new BimetallicStrip(),
                               new HeatAnticipator()
                           };
        }

        public void Accept(IComponentVisitor visitor)
        {
            visitor.Visit(this);

            foreach (var element in _elements)
            {
                element.Accept(visitor);
            }
        }
    }

    class ThermostatCover : IComponentElement
    {
        public void Accept(IComponentVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    class CircutBoard : IComponentElement
    {
        public void Accept(IComponentVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    class MercurySwitch : IComponentElement
    {
        public void Accept(IComponentVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    class BimetallicStrip : IComponentElement
    {
        public void Accept(IComponentVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    class HeatAnticipator : IComponentElement
    {
        public void Accept(IComponentVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    class PartsManifestVisitor : IComponentVisitor
    {
        IList&lt;string&gt; manifest = new List&lt;string&gt;();

        public void PrintManifest(TextWriter textWriter)
        {
            manifest.ToList().ForEach(x =&gt; textWriter.WriteLine(x));
        }

        public void Visit(Thermostat thermostat)
        {
            manifest.Add(&quot;Thermostat&quot;);
        }

        public void Visit(ThermostatCover thermostatCover)
        {
            manifest.Add(&quot;Thermostat cover&quot;);
        }

        public void Visit(CircutBoard circutBoard)
        {
            manifest.Add(&quot;Circut board&quot;);
        }

        public void Visit(MercurySwitch mercurySwitch)
        {
            manifest.Add(&quot;Mercury switch&quot;);
        }

        public void Visit(BimetallicStrip bimetallicStrip)
        {
            manifest.Add(&quot;Bimetallic strip&quot;);
        }

        public void Visit(HeatAnticipator heatAnticipator)
        {
            manifest.Add(&quot;Heat anticipator&quot;);
        }
    }

    class DangerousGoodsManifestVisitor : IComponentVisitor
    {
        IList&lt;string&gt; manifest = new List&lt;string&gt;();

        public void PrintManifest(TextWriter textWriter)
        {
            manifest.ToList().ForEach(x =&gt; textWriter.WriteLine(x));
        }

        public void Visit(Thermostat thermostat)
        {
        }

        public void Visit(ThermostatCover thermostatCover)
        {
        }

        public void Visit(CircutBoard circutBoard)
        {
        }

        public void Visit(MercurySwitch mercurySwitch)
        {
            manifest.Add(&quot;Mercury switch&quot;);
        }

        public void Visit(BimetallicStrip bimetallicStrip)
        {
        }

        public void Visit(HeatAnticipator heatAnticipator)
        {
        }
    }
</pre>
<p>Running the application produces the following output:</p>
<pre>Parts List
----------
Thermostat
Thermostat cover
Circut board
Mercury switch
Bimetallic strip
Heat anticipator

Dangerous Goods List
----------
Mercury switch</pre>
<p>By using the Visitor pattern, the application was able to print a parts list and a dangerous goods list without adding any specific logic to the thermostat components.  As new cross-cutting operations come up, a new visitor can be created without modification to the components.</p>
<p>The down side of this example is that if any new components are added, each of the visitors will need to be updated.  This violates the <a href="http://en.wikipedia.org/wiki/Open_Closed_Principle" target="_blank">Open/Closed</a> principle. Additionally, depending upon the type of behavior encapsulated by the visitor, the behavior for each element type may change for different reasons.  In such cases, this would violate the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">Single Responsibility</a> principle.  What would be nice is to achieve a visitor implementation that satisfied both of these concerns.</p>
<h2>An Agile Visitor</h2>
<p>What if a visitor allowed us to replace the overloaded methods with <a href="http://en.wikipedia.org/wiki/Strategy_pattern" target="_blank">strategies</a>?  Consider the following example:</p>
<pre class="brush: csharp;">
class Program
    {
        static void Main(string[] args)
        {
            // Declare visitors
            var partsManifestVisitor = new Visitor&lt;IVisitable&gt;();
            var dangerousGoodsManifestVisitor = new Visitor&lt;IVisitable&gt;();

            // Register parts manifest visitor strategies
            partsManifestVisitor.RegisterElementVisitor&lt;Thermostat&gt;(x =&gt; Console.WriteLine(&quot;Thermostat&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;ThermostatCover&gt;(x =&gt; Console.WriteLine(&quot;Thermostat cover&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;CircutBoard&gt;(x =&gt; Console.WriteLine(&quot;Circut board&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;MercurySwitch&gt;(x =&gt; Console.WriteLine(&quot;Mercury switch&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;BimetallicStrip&gt;(x =&gt; Console.WriteLine(&quot;Bimetallic strip&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;HeatAnticipator&gt;(x =&gt; Console.WriteLine(&quot;Heat anticipator&quot;));

            // Register dangerous goods manifest visitor strategies
            partsManifestVisitor.RegisterElementVisitor&lt;MercurySwitch&gt;(x =&gt; Console.WriteLine(&quot;Mercury switch&quot;));

            var thermostat = new Thermostat();

            Console.WriteLine(&quot;Parts List&quot;);
            Console.WriteLine(&quot;----------&quot;);
            thermostat.Accept(partsManifestVisitor);

            Console.WriteLine(&quot;\nDangerous Goods List&quot;);
            Console.WriteLine(&quot;----------&quot;);
            thermostat.Accept(dangerousGoodsManifestVisitor);

            Console.ReadLine();
        }
    }
</pre>
<p>In this example, the methods normally found on the classic visitor implementation have been replaced with lambda expressions registered for each type to be visited.  There are several advantages to this approach:</p>
<p>First, the Visitor type is extensible and thus adheres to the Open/Closed principle.</p>
<p>Second, the Visitor type is generic, thus enabling it to be used for many (all?) types of visitor implementations.</p>
<p>Third, due to the fact that there are no concrete visitors coupled to a given object structure, new elements can be added to a given object structure without requiring that all visitors for that structure be modified to accommodate the new element.</p>
<p>Forth, the behavior associated with each type is encapsulated in a single Visitor strategy, thus adhering to the single responsibility principle.</p>
<p>Fifth, due to the fact that the Visitor isn&#8217;t itself coupled to any particular element type, the element types are likewise not coupled to any object structure specific visitor interface.  This allows a given element to participate in unrelated object structure/visitor pattern implementations.</p>
<p>There are a couple of drawbacks to this approach however:</p>
<p>First, what happens when the behavior is more complex?  For that, we could just add an overloaded RegisterElementVisitor() to accept an IVisitor:</p>
<pre class="brush: csharp;">
class ThermostatVisitor : IVisitor&lt;Thermostat&gt;
    {
        public void Visit(Thermostat element)
        {
            Console.WriteLine(&quot;Thermostat&quot;);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var partsManifestVisitor = new Visitor&lt;IVisitable&gt;();

            partsManifestVisitor.RegisterElementVisitor&lt;Thermostat&gt;(new ThermostatVisitor());

            // snip
        }
    }
</pre>
<p>That addresses the issue of how we might better encapsulate the more complex behaviors, but a second shortcoming is the loss of encapsulated state.  One of the good things the classic Visitor pattern gives us is shared state for accumulating the results of our visitations.  There are a few ways we could address this however.  The first approach would be to just use closures:</p>
<pre class="brush: csharp;">
            // snip

            // Register parts manifest visitor strategies
            var partsManifest = new List&lt;string&gt;();

            partsManifestVisitor.RegisterElementVisitor&lt;Thermostat&gt;(x =&gt; partsManifest.Add(&quot;Thermostat&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;ThermostatCover&gt;(x =&gt; partsManifest.Add(&quot;Thermostat cover&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;CircutBoard&gt;(x =&gt; partsManifest.Add(&quot;Circut board&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;MercurySwitch&gt;(x =&gt; partsManifest.Add(&quot;Mercury switch&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;BimetallicStrip&gt;(x =&gt; partsManifest.Add(&quot;Bimetallic strip&quot;));
            partsManifestVisitor.RegisterElementVisitor&lt;HeatAnticipator&gt;(x =&gt; partsManifest.Add(&quot;Heat anticipator&quot;));

            var thermostat = new Thermostat();
            thermostat.Accept(partsManifestVisitor);

            Console.WriteLine(&quot;Parts List&quot;);
            Console.WriteLine(&quot;----------&quot;);
            partsManifest.ToList().ForEach(x =&gt; Console.WriteLine(x));

            // snip
</pre>
<p>A second approach would be to inject a state service when registering IVisitor strategies:</p>
<pre class="brush: csharp;">
    class Manifest
    {
        public IList&lt;string&gt; Parts { get; private set; }

        public Manifest()
        {
            Parts = new List&lt;string&gt;();
        }

        public void RecordPart(string partName)
        {
            Parts.Add(partName);
        }
    }

    class ThermostatVisitor : IVisitor&lt;Thermostat&gt;
    {
        Manifest _manifest;

        public ThermostatVisitor(Manifest manifest)
        {
            _manifest = manifest;
        }

        public void Visit(Thermostat element)
        {
            _manifest.RecordPart(&quot;Thermostat&quot;);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Declare visitors
            var partsManifestVisitor = new Visitor&lt;IVisitable&gt;();

            // Register parts manifest visitor strategies
            var manifest = new Manifest();
            partsManifestVisitor.RegisterElementVisitor&lt;Thermostat&gt;(new ThermostatVisitor(manifest));

            // other strategies

            var thermostat = new Thermostat();
            thermostat.Accept(partsManifestVisitor);

            Console.WriteLine(&quot;Parts List&quot;);
            Console.WriteLine(&quot;----------&quot;);
            manifest.Parts.ToList().ForEach(x =&gt; Console.WriteLine(x));
        }
    }
</pre>
<p>Things are starting to get strewn about though. Let&#8217;s bundle all of this up into a <a href="http://en.wikipedia.org/wiki/Facade_pattern" target="_blank">facade</a>:</p>
<pre class="brush: csharp;">
    class PartsManifestVisitorFacade : IVisitor&lt;IVisitable&gt;
    {
        Manifest _manifest = new Manifest();
        Visitor&lt;IVisitable&gt; partsManifestVisitor = new Visitor&lt;IVisitable&gt;();

        public PartsManifestVisitorFacade()
        {
            partsManifestVisitor.RegisterElementVisitor&lt;Thermostat&gt;(new ThermostatVisitor(_manifest));

            // Register other strategies  ...
        }

        public IList&lt;string&gt; Manifest
        {
            get
            {
                return _manifest.Parts;
            }
        }

        public void Visit(IVisitable element)
        {
            partsManifestVisitor.Visit(element);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var partsManifestVisitor = new PartsManifestVisitorFacade();
            var thermostat = new Thermostat();
            thermostat.Accept(partsManifestVisitor);

            Console.WriteLine(&quot;Parts List&quot;);
            Console.WriteLine(&quot;----------&quot;);
            partsManifestVisitor.Manifest.ToList().ForEach(x =&gt; Console.WriteLine(x));

            Console.ReadLine();
        }
    }
</pre>
<p>Alternately, we could use some DI registration magic to have an open generic visitor get closed-over, configured, and injected into wherever we are going to use it.  Such an example is a tad bit beyond the intended scope of this article, however, so I&#8217;ll leave that as an exercise for the reader to explore.</p>
<p>By this point, you may be wondering: &#8220;So where&#8217;s the actual Visitor code&#8221;?  While I’m sure a better implementation is possible, here’s my working prototype:</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Defines a visitor.
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;TElement&quot;&gt;the type of element to be visited&lt;/typeparam&gt;
    interface IVisitor&lt;TElement&gt;
    {
        void Visit(TElement element);
    }

    /// &lt;summary&gt;
    /// Defines a visitable element.
    /// &lt;/summary&gt;
    interface IVisitable
    {
        void Accept(IVisitor&lt;IVisitable&gt; visitor);
    }

    /// &lt;summary&gt;
    /// Represents an open/closed visitor.
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;the type of element to visit&lt;/typeparam&gt;
    class Visitor&lt;T&gt; : IVisitor&lt;T&gt;
    {
        readonly IDictionary&lt;Type, IVisitorInfo&gt; _visitorInfoDictionary = new Dictionary&lt;Type, IVisitorInfo&gt;();

        /// &lt;summary&gt;
        /// Visits the specified element.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;element&quot;&gt;element to visit&lt;/param&gt;
        public void Visit(T element)
        {
            if (_visitorInfoDictionary.ContainsKey(element.GetType()))
            {
                IVisitorInfo visitorInfo = _visitorInfoDictionary[element.GetType()];
                object visitor = visitorInfo.Visitor;
                IVisitorInvoker invoker = visitorInfo.Invoker;
                invoker.Invoke(visitor, element);
            }
        }

        /// &lt;summary&gt;
        /// Registers an visitor action delegate for a specific type.
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TElement&quot;&gt;type of element&lt;/typeparam&gt;
        /// &lt;param name=&quot;action&quot;&gt;the visitor action&lt;/param&gt;
        public void RegisterElementVisitor&lt;TElement&gt;(Action&lt;TElement&gt; action)
        {
            RegisterElementVisitor(new VisitorAction&lt;TElement&gt;(action));
        }

        /// &lt;summary&gt;
        /// Registers a &lt;see cref=&quot;IVisitor{TElement}&quot;/&gt; strategy for a specific type.
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TElement&quot;&gt;type of element&lt;/typeparam&gt;
        /// &lt;param name=&quot;visitor&quot;&gt;a visitor&lt;/param&gt;
        public void RegisterElementVisitor&lt;TElement&gt;(IVisitor&lt;TElement&gt; visitor)
        {
            var visitorInfo = new VisitorInfo&lt;TElement&gt;(
                visitor, new DelegateVisitorInvoker&lt;IVisitor&lt;TElement&gt;, TElement&gt;((x, y) =&gt; x.Visit(y)));

            _visitorInfoDictionary.Add(typeof(TElement), visitorInfo);
        }

        /// &lt;summary&gt;
        /// Nested class used to encapsulate a visitor action.
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TVisitor&quot;&gt;the type of visitor action&lt;/typeparam&gt;
        /// &lt;typeparam name=&quot;TElement&quot;&gt;the type of element&lt;/typeparam&gt;
        class DelegateVisitorInvoker&lt;TVisitor, TElement&gt; : IVisitorInvoker
        {
            readonly Action&lt;TVisitor, TElement&gt; _action;

            public DelegateVisitorInvoker(Action&lt;TVisitor, TElement&gt; action)
            {
                _action = action;
            }

            public void Invoke(object action, object instance)
            {
                _action.Invoke((TVisitor)action, (TElement)instance);
            }
        }

        /// &lt;summary&gt;
        /// Nested interface used as the key to the internal dictionary for associating
        /// visitors with their invokers.
        /// &lt;/summary&gt;
        interface IVisitorInfo
        {
            IVisitorInvoker Invoker { get; }
            object Visitor { get; }
        }

        /// &lt;summary&gt;
        /// Nested interface used to encapsulate a visit action invocation.
        /// &lt;/summary&gt;
        interface IVisitorInvoker
        {
            void Invoke(object action, object instance);
        }

        /// &lt;summary&gt;
        /// Nested class used to encapsulate visitor actions.
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TElement&quot;&gt;the type of element to visit&lt;/typeparam&gt;
        class VisitorAction&lt;TElement&gt; : IVisitor&lt;TElement&gt;
        {
            readonly Action&lt;TElement&gt; _action;

            public VisitorAction(Action&lt;TElement&gt; action)
            {
                _action = action;
            }

            public void Visit(TElement element)
            {
                _action.Invoke(element);
            }
        }

        /// &lt;summary&gt;
        /// Nested class used as the key to the internal dictionary for associating
        /// visitors with their invokers.
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TElement&quot;&gt;the type of element to be visited&lt;/typeparam&gt;
        ///
        /// &lt;remarks&gt;
        /// This type is used as the internal dictionary key to associate visitors with
        /// a corresponding invoker and enables the specific type information to be
        /// maintained for each visitor/element pair.
        /// &lt;/remarks&gt;
        class VisitorInfo&lt;TElement&gt; : IVisitorInfo
        {
            public VisitorInfo(IVisitor&lt;TElement&gt; visitor, IVisitorInvoker invoker)
            {
                Visitor = visitor;
                Invoker = invoker;
            }

            public IVisitorInvoker Invoker { get; private set; }
            public object Visitor { get; private set; }
        }
    }
</pre>
<h2>Conclusion</h2>
<p>The structure of the classic Visitor pattern seem to reflect the design sensibilities and capabilities of the mainstream programming languages of its day. While the problem it seeks to address remains relevant, it seems prudent to reconsider such patterns from time to time in light of both the ever-evolving capabilities of mainstream development platforms and design principles of today.</p>
<p>So, is this a better approach?  Let me know what you think.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/r3lGL89MI0A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/04/the-agile-visitor/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/04/the-agile-visitor/</feedburner:origLink></item>
		<item>
		<title>Double Dispatch is a Code Smell</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/DgBGQdcOLOI/</link>
		<comments>http://www.aspiringcraftsman.com/2010/04/double-dispatch-is-a-code-smell/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 02:16:25 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Double Dispatch]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=330</guid>
		<description><![CDATA[If you&#8217;re using Double Dispatch in your code, this may be a symptom of an underlying design issue which may impact the maintainability of your application. Due to the fact that Double Dispatch is at times confused with a form of the Strategy Pattern, an overview may be in order to elaborate on this assertion [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re using <a href="http://en.wikipedia.org/wiki/Double_dispatch">Double Dispatch</a> in your code, this may be a symptom of an underlying design issue which may impact the maintainability of your application.  Due to the fact that Double Dispatch is at times confused with a form of the <a href="http://en.wikipedia.org/wiki/Strategy_Pattern">Strategy Pattern</a>, an overview may be in order to elaborate on this assertion further.</p>
<h2>What is Double Dispatch?</h2>
<p>Technically, Double Dispatch refers to a technique used in the context of a polymorphic method call for mitigating the lack of <a href="http://en.wikipedia.org/wiki/Multimethods">multimethod</a> support in programming languages.  More simply, Double Dispatch is used to invoke an overloaded method where the parameters vary among an inheritance hierarchy.  To explain fully, let&#8217;s start with a review of <a href="http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming">polymorphism</a>.</p>
<h3>Polymorphism</h3>
<p>In the following example, a hierarchy of shapes are defined with each of the derived types overloading a base virtual <code>Draw()</code> method.  Next, a console application is used to define a list of each of the shapes and iterate over each shape in the collection calling the <code>Draw()</code> method of each item in the list:</p>
<pre class="brush: csharp;">
    class Shape
    {
        public virtual void Draw()
        {
            Console.WriteLine(&quot;A shape is drawn.&quot;);
        }
    }

    class Polygon : Shape
    {
        public override void Draw()
        {
            Console.WriteLine(&quot;A polygon is drawn.&quot;);
        }
    }

    class Quadrilateral : Polygon
    {
        public override void Draw()
        {
            Console.WriteLine(&quot;A quadrilateral is drawn.&quot;);
        }
    }

    class Parallelogram : Quadrilateral
    {
        public override void Draw()
        {
            Console.WriteLine(&quot;A parallelogram is drawn.&quot;);
        }
    }

    class Rectangle : Parallelogram
    {
        public override void Draw()
        {
            Console.WriteLine(&quot;A rectangle is drawn.&quot;);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var shapes = new List&lt;Shape&gt;
                             {
                                 new Shape(),
                                 new Polygon(),
                                 new Quadrilateral(),
                                 new Parallelogram(),
                                 new Rectangle()
                             };

            foreach (Shape shape in shapes)
            {
                shape.Draw();
            }

            Console.ReadLine();
        }
    }
</pre>
<p>The following lines are printed to the console upon running the application:</p>
<pre>A shape is drawn.
A polygon is drawn.
A quadrilateral is drawn.
A parallelogram is drawn.
A rectangle is drawn.
</pre>
<p><br/></p>
<p>Note that the proper <code>Draw()</code> method is called for each item in the collection.  In most object-oriented languages, this polymorphic behavior is achieved through the use of a <a href="http://en.wikipedia.org/wiki/Virtual_table">virtual table</a> consulted at run-time to derive the proper offset address for an object&#8217;s method.  This behavior is referred to as &#8220;<a href="http://en.wikipedia.org/wiki/Dynamic_dispatch">Dynamic Dispatch</a>&#8221; or &#8220;Single Dispatch&#8221;.  So, how does this relate to Double Dispatch?  To answer this question, let&#8217;s next review <a href="http://en.wikipedia.org/wiki/Function_overloading">method overloading</a>.</p>
<h3>Method Overloading</h3>
<p>In the following example, our <code>Shape</code> class is redefined to have two overloaded <code>Draw</code> methods: one with a parameter of type <code>Surface</code> and one with a parameter of type <code>EtchASketch</code>:</p>
<pre class="brush: csharp;">
    class Surface
    {
    }

    class EtchASketch : Surface
    {
    }

    class Shape
    {
        public void Draw(Surface surface)
        {
            Console.WriteLine(&quot;A shape is drawn on the surface with ink.&quot;);
        }

        public void Draw(EtchASketch etchASketch)
        {
            Console.WriteLine(&quot;The knobs are moved in attempt to draw the shape.&quot;);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var shape = new Shape();
            shape.Draw(new Surface());
            shape.Draw(new EtchASketch());

            Console.ReadLine();
        }
    }
</pre>
<p>When executed, the following lines are printed to the console:</p>
<pre>A shape is drawn on the surface with ink.
The knobs are moved in attempt to draw the shape.</pre>
<p><br/></p>
<p>Note that the parameter type determines which <code>Draw()</code> method is invoked.</p>
<p>But what happens if we change the <code>Main()</code> method to the following?</p>
<pre class="brush: csharp;">
    class Program
    {
        static void Main(string[] args)
        {
            var shape = new Shape();
            Surface surface = new Surface();
            Surface etchASketch = new EtchASketch();

            shape.Draw(surface);
            shape.Draw(etchASketch);

            Console.ReadLine();
        }
    }
</pre>
<p>Executing this produces the following:</p>
<pre>A shape is drawn on the surface with ink.
A shape is drawn on the surface with ink.</pre>
<p><br/></p>
<p>What happened?  The issue here is that the method to call was determined statically at compile time based upon the reference type, not at run-time based upon the object type.  To resolve this issue, another technique is needed &#8230; Polymorphic Static Binding.</p>
<h3>Polymorphic Static Binding</h3>
<p>Polymorphic static binding is a technique where static method invocations are determined at run-time through the use of polymorphism.  This can be demonstrated in our example by adding a new <code>Draw(Shape shape)</code> method to the <code>Surface</code> and <code>EtchASketch</code> types which call <code>shape.Draw()</code> with a reference to the current object:</p>
<pre class="brush: csharp;">
    class Surface
    {
        public virtual void Draw(Shape shape)
        {
            shape.Draw(this);
        }
    }

    class EtchASketch : Surface
    {
        public override void Draw(Shape shape)
        {
            shape.Draw(this);
        }
    }
</pre>
<p>To invoke the correct <code>Shape.Draw()</code> method, our console application needs to be modified to call the the method indirectly through a <code>Surface</code> reference:</p>
<pre class="brush: csharp;">
    class Program
    {
        static void Main(string[] args)
        {
            var shape = new Shape();
            Surface surface = new Surface();
            Surface etchASketch = new EtchASketch();

            surface.Draw(shape);
            etchASketch.Draw(shape);

            Console.ReadLine();
        }
    }
</pre>
<p>Upon executing the application again, the following lines are now printed:</p>
<pre>A shape is drawn on the surface with ink.
The knobs are moved in attempt to draw the shape.</pre>
<p><br/></p>
<p>This example achieves the desired result by effectively wrapping the static-dispatched method invocation (i.e. <code>Shape.Draw()</code>) within a virtual-dispatch method invocation (i.e. <code>Surface.Draw()</code> and <code>EtchASketch.Draw()</code>).  This causes the static <code>Shape.Draw()</code> method invocation to be determined by which virtual <code>Surface.Draw()</code> method invocation is executed.</p>
<p>Although the above example now contains a method invocation using a reference to the current object as the method parameter (often seen with Double Dispatch), it should be noted that Double Dispatch has yet to be demonstrated.  Thus far, only one level of virtual dispatching has been used.  To demonstrate Double Dispatch, the techniques from both the polymorphism example and the polymorphic static binding example need to be combined as seen in the next section.</p>
<h3>Double Dispatch</h3>
<p>The following example contains a hierarchy of <code>Surface</code> types and a hierarchy of <code>Shape</code> types.  Each <code>Shape</code> type contains an overloaded virtual <code>Draw()</code> method which contains the logic for how the shape is to be drawn on a particular surface.  The example console application uses the polymorphic static binding technique to ensure the proper overload is called for each surface type:</p>
<pre class="brush: csharp;">
    class Surface
    {
        public virtual void Draw(Shape shape)
        {
            shape.Draw(this);
        }
    }

    class EtchASketch : Surface
    {
        public override void Draw(Shape shape)
        {
            shape.Draw(this);
        }
    }

    class Shape
    {
        public virtual void Draw(Surface surface)
        {
            Console.WriteLine(&quot;A shape is drawn on the surface with ink.&quot;);
        }

        public virtual void Draw(EtchASketch etchASketch)
        {
            Console.WriteLine(&quot;The knobs are moved in attempt to draw the shape.&quot;);
        }
    }

    class Polygon : Shape
    {
        public override void Draw(Surface surface)
        {
            Console.WriteLine(&quot;A polygon is drawn on the surface with ink.&quot;);
        }

        public override void Draw(EtchASketch etchASketch)
        {
            Console.WriteLine(&quot;The knobs are moved in attempt to draw the polygon.&quot;);
        }
    }

    class Quadrilateral : Polygon
    {
        public override void Draw(Surface surface)
        {
            Console.WriteLine(&quot;A quadrilateral is drawn on the surface with ink.&quot;);
        }

        public override void Draw(EtchASketch etchASketch)
        {
            Console.WriteLine(&quot;The knobs are moved in attempt to draw the quadrilateral.&quot;);
        }
    }

    class Parallelogram : Quadrilateral
    {
        public override void Draw(Surface surface)
        {
            Console.WriteLine(&quot;A parallelogram is drawn on the surface with ink.&quot;);
        }

        public override void Draw(EtchASketch etchASketch)
        {
            Console.WriteLine(&quot;The knobs are moved in attempt to draw the parallelogram.&quot;);
        }
    }

     class Rectangle : Parallelogram
    {
        public override void Draw(Surface surface)
        {
            Console.WriteLine(&quot;A rectangle is drawn on the surface with ink.&quot;);
        }

        public override void Draw(EtchASketch etchASketch)
        {
            Console.WriteLine(&quot;The knobs are moved in attempt to draw the rectangle.&quot;);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Surface surface = new Surface();
            Surface etchASketch = new EtchASketch();

            var shapes = new List&lt;Shape&gt;
                             {
                                 new Shape(),
                                 new Polygon(),
                                 new Quadrilateral(),
                                 new Parallelogram(),
                                 new Rectangle()
                             };

            foreach (Shape shape in shapes)
            {
                surface.Draw(shape);
                etchASketch.Draw(shape);
            }

            Console.ReadLine();
        }
    }
</pre>
<p>Executing this example produces the following:</p>
<pre>A shape is drawn on the surface with ink.
The knobs are moved in attempt to draw the shape.
A polygon is drawn on the surface with ink.
The knobs are moved in attempt to draw the polygon.
A quadrilateral is drawn on the surface with ink.
The knobs are moved in attempt to draw the quadrilateral.
A parallelogram is drawn on the surface with ink.
The knobs are moved in attempt to draw the parallelogram.
A rectangle is drawn on the surface with ink.
The knobs are moved in attempt to draw the rectangle.
</pre>
<p><br/></p>
<p>In the above example, virtual dispatch occurs twice for each call to one of the <code>Surface</code> references: Once when the <code>Surface.Draw()</code> virtual method is called and again when either calls the <code>Shape.Draw()</code> overloaded virtual method.  Note again that while the second virtual dispatch is based on the type of <code>Shape</code> instance, the overloaded method called is still determined statically based upon the reference type.</p>
<h2>Consequences</h2>
<p>So, what&#8217;s wrong with Double Dispatch?  The problem isn&#8217;t so much in the technique, but what design choices might be leading to reliance upon the technique.  Consider for instance the hierarchy of shape types in our Double Dispatch example.  What happens if we want to add a new surface?  In this case, each of the shape types will need to be modified to add knowledge of the new Surface type.  This violates the <a href="http://en.wikipedia.org/wiki/Open_Closed_Principle">Open/Closed Principle</a>, and in this case in a particularly egregious way (i.e. Its violation is multiplied by the number of shape types we have).   Additionally, it violates the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a>.  Changes to how shapes are drawn on a particular surface are likely to differ from surface to surface, thereby leading our shape objects to change for different reasons.</p>
<p>The presence of Double Dispatch generally means that each type in a hierarchy has special handling code within another hierarchy of types.  This approach to representing variant behavior leads to code that is less resilient to future changes as well as being more difficult to extend.</p>
<h2>The Matrix: Reloaded</h2>
<p>Let&#8217;s take another stab at modeling our shape/surface intersection matrix.  In the following example, several new concepts have been introduced to facilitate decoupling: line segments, points, and brushes:</p>
<pre class="brush: csharp;">
    interface ISurface
    {
        void Add(LineSegment segment);
    }

    class Paper : ISurface
    {
        readonly IList&lt;LineSegment&gt; _segments = new List&lt;LineSegment&gt;();

        public void Add(LineSegment segment)
        {
            _segments.Add(segment);
        }
    }

    class EtchASketch : ISurface
    {
        readonly IList&lt;LineSegment&gt; _segments = new List&lt;LineSegment&gt;();

        public void Add(LineSegment segment)
        {
            _segments.Add(segment);
        }
    }

    class Point
    {
        public Point(int x, int y)
        {
            X = x;
            Y = y;
        }

        public int X { get; set; }
        public int Y { get; set; }
    }

    class LineSegment
    {
        public LineSegment(Point point1, Point point2)
        {
            Point1 = point1;
            Point2 = point2;
        }

        public Point Point1 { get; set; }
        public Point Point2 { get; set; }
    }

    interface IShape
    {
        IList&lt;LineSegment&gt; GetLineSegments();
    }

    class Polygon : IShape
    {
        public IList&lt;LineSegment&gt; GetLineSegments()
        {
            var segments = new List&lt;LineSegment&gt;();
            segments.Add(new LineSegment(new Point(0, 0), new Point(0, 9)));
            segments.Add(new LineSegment(new Point(0, 9), new Point(3, 6)));
            segments.Add(new LineSegment(new Point(3, 6), new Point(6, 9)));
            segments.Add(new LineSegment(new Point(6, 0), new Point(6, 9)));
            segments.Add(new LineSegment(new Point(6, 0), new Point(3, 3)));
            segments.Add(new LineSegment(new Point(3, 3), new Point(0, 0)));

            return segments;
        }
    }

    class Quadrilateral : IShape
    {
        public IList&lt;LineSegment&gt; GetLineSegments()
        {
            var segments = new List&lt;LineSegment&gt;();
            segments.Add(new LineSegment(new Point(0, 0), new Point(0, 9)));
            segments.Add(new LineSegment(new Point(0, 9), new Point(4, 5)));
            segments.Add(new LineSegment(new Point(4, 0), new Point(0, 4)));
            segments.Add(new LineSegment(new Point(4, 0), new Point(0, 0)));

            return segments;
        }
    }

    class Parallelogram : IShape
    {
        public IList&lt;LineSegment&gt; GetLineSegments()
        {
            var segments = new List&lt;LineSegment&gt;();
            segments.Add(new LineSegment(new Point(0, 4), new Point(0, 9)));
            segments.Add(new LineSegment(new Point(0, 9), new Point(4, 5)));
            segments.Add(new LineSegment(new Point(4, 0), new Point(4, 5)));
            segments.Add(new LineSegment(new Point(4, 0), new Point(0, 4)));

            return segments;
        }
    }

    class Rectangle : IShape
    {
        public IList&lt;LineSegment&gt; GetLineSegments()
        {
            var segments = new List&lt;LineSegment&gt;();
            segments.Add(new LineSegment(new Point(0, 0), new Point(0, 9)));
            segments.Add(new LineSegment(new Point(0, 9), new Point(9, 4)));
            segments.Add(new LineSegment(new Point(4, 0), new Point(9, 4)));
            segments.Add(new LineSegment(new Point(4, 0), new Point(0, 0)));

            return segments;
        }
    }

    class Program
    {
        static readonly IDictionary&lt;Type, IBrush&gt; brushDictionary = new Dictionary&lt;Type, IBrush&gt;();

        static Program()
        {
            brushDictionary.Add(typeof (Paper), new Pencil());
            brushDictionary.Add(typeof (EtchASketch), new EtchASketchKnobs());
        }

        static void Main(string[] args)
        {
            var surfaces = new List&lt;ISurface&gt;
                               {
                                   new Paper(),
                                   new EtchASketch()
                               };

            var shapes = new List&lt;IShape&gt;
                             {
                                 new Polygon(),
                                 new Quadrilateral(),
                                 new Parallelogram(),
                                 new Rectangle()
                             };

            foreach (ISurface surface in surfaces)
                foreach (IShape shape in shapes)
                {
                    Console.WriteLine(string.Format(&quot;Drawing a {0} on the {1} ...&quot;, shape.GetType().Name,
                                                    surface.GetType().Name));
                    brushDictionary[surface.GetType()].Draw(surface, shape.GetLineSegments());
                    Console.WriteLine(Environment.NewLine);
                }

            Console.ReadLine();
        }
    }

    interface IBrush
    {
        void Draw(ISurface surface, IList&lt;LineSegment&gt; segments);
    }

    class Pencil : IBrush
    {
        public void Draw(ISurface surface, IList&lt;LineSegment&gt; segments)
        {
            foreach (LineSegment segment in segments)
            {
                Console.WriteLine(string.Format(&quot;Pencil used to sketch line segment {0},{1} to {2},{3}.&quot;,
                                                segment.Point1.X, segment.Point1.Y,
                                                segment.Point2.X, segment.Point2.Y));
            }
        }
    }

    class EtchASketchKnobs : IBrush
    {
        public void Draw(ISurface surface, IList&lt;LineSegment&gt; segments)
        {
            foreach (LineSegment segment in segments)
            {
                Console.WriteLine(string.Format(&quot;Knobs used to produce line segment {0},{1} to {2},{3}.&quot;,
                                                segment.Point1.X, segment.Point1.Y,
                                                segment.Point2.X, segment.Point2.Y));
            }
        }
    }
</pre>
<p>Executing this example produces the following:</p>
<pre>Drawing a Polygon on the Paper ...
Pencil used to sketch line segment 0,0 to 0,9.
Pencil used to sketch line segment 0,9 to 3,6.
Pencil used to sketch line segment 3,6 to 6,9.
Pencil used to sketch line segment 6,0 to 6,9.
Pencil used to sketch line segment 6,0 to 3,3.
Pencil used to sketch line segment 3,3 to 0,0.

Drawing a Quadrilateral on the Paper ...
Pencil used to sketch line segment 0,0 to 0,9.
Pencil used to sketch line segment 0,9 to 4,5.
Pencil used to sketch line segment 4,0 to 0,4.
Pencil used to sketch line segment 4,0 to 0,0.

Drawing a Parallelogram on the Paper ...
Pencil used to sketch line segment 0,4 to 0,9.
Pencil used to sketch line segment 0,9 to 4,5.
Pencil used to sketch line segment 4,0 to 4,5.
Pencil used to sketch line segment 4,0 to 0,4.

Drawing a Rectangle on the Paper ...
Pencil used to sketch line segment 0,0 to 0,9.
Pencil used to sketch line segment 0,9 to 9,4.
Pencil used to sketch line segment 4,0 to 9,4.
Pencil used to sketch line segment 4,0 to 0,0.

Drawing a Polygon on the EtchASketch ...
Knobs used to produce line segment 0,0 to 0,9.
Knobs used to produce line segment 0,9 to 3,6.
Knobs used to produce line segment 3,6 to 6,9.
Knobs used to produce line segment 6,0 to 6,9.
Knobs used to produce line segment 6,0 to 3,3.
Knobs used to produce line segment 3,3 to 0,0.

Drawing a Quadrilateral on the EtchASketch ...
Knobs used to produce line segment 0,0 to 0,9.
Knobs used to produce line segment 0,9 to 4,5.
Knobs used to produce line segment 4,0 to 0,4.
Knobs used to produce line segment 4,0 to 0,0.

Drawing a Parallelogram on the EtchASketch ...
Knobs used to produce line segment 0,4 to 0,9.
Knobs used to produce line segment 0,9 to 4,5.
Knobs used to produce line segment 4,0 to 4,5.
Knobs used to produce line segment 4,0 to 0,4.

Drawing a Rectangle on the EtchASketch ...
Knobs used to produce line segment 0,0 to 0,9.
Knobs used to produce line segment 0,9 to 9,4.
Knobs used to produce line segment 4,0 to 9,4.
Knobs used to produce line segment 4,0 to 0,0.</pre>
<p><br/></p>
<p>By changing the <code>Shape</code> objects to be defined in terms of line segments, knowledge is removed from the shape concerning how to draw itself on any particular surface.  Additionally, the <code>Surface</code> type now encapsulates a collection of line segments to simulate the lines being drawn onto the surface.  To handle drawing the line segments onto the surfaces, we&#8217;ve introduced a <code>Brush</code> type which &#8220;draws&#8221; the line segments onto a surface in its own peculiar way.  To configure which brushes are to be used with which surface, the console application defines a dictionary matching surfaces to brushes.</p>
<p>In contrast to the Double Dispatch example, none of the existing types need to be modified to add new surfaces, shapes, or brushes.</p>
<h2>Conclusion</h2>
<p>Since Double Dispatch is a technique for calling virtual overloaded methods based upon parameter types which exist within an inheritance hierarchy, its use may be a symptom that the Open/Closed and/or Single responsibility principles are being violated, or that responsibilities may otherwise be misaligned.  This is not to say that every case of Double Dispatch means something is amiss, but only that its use should be a flag to reconsider your design in light of future maintenance needs.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/DgBGQdcOLOI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/04/double-dispatch-is-a-code-smell/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/04/double-dispatch-is-a-code-smell/</feedburner:origLink></item>
		<item>
		<title>Getting Started With Cygwin</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/2fEmSQS7bnI/</link>
		<comments>http://www.aspiringcraftsman.com/2010/04/getting-started-with-cygwin/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 14:58:01 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Cygwin]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=298</guid>
		<description><![CDATA[With the increasing popularity of the Git version control system, many .Net developers are being introduced for the first time to Unix-like tools for Windows by way of two popular Git client platforms: msysgit and Cygwin. The more substantial of the two, Cygwin is a Linux-like environment for Windows and provides a wide range of [...]]]></description>
			<content:encoded><![CDATA[<p>With the increasing popularity of the <a id="b89_" title="Git" href="http://git-scm.com/" target="_blank">Git</a> version control system, many .Net  developers are being introduced for the first time to Unix-like tools  for Windows by way of two popular Git client platforms: <a id="nucy" title="msysgit" href="http://code.google.com/p/msysgit/" target="_blank">msysgit</a> and <a id="tw22" title="Cygwin" href="http://en.wikipedia.org/wiki/Cygwin" target="_blank">Cygwin</a>.  The more substantial of the two, Cygwin is a  Linux-like environment for Windows and provides a wide range of useful  utilities.  The following is a guide for helping newcomers quickly get  up and going with the Cygwin environment.</p>
<h2>Installation</h2>
<p>The  first step is to obtain the installer from the <a id="izx." title="Cygwin home page" href="http://www.cygwin.com/" target="_blank">Cygwin  home page</a>.  Upon running the installer, you&#8217;ll be presented with a  wizard which guides you through the installation process:</p>
<p><img class="alignnone size-full wp-image-302" title="cygwin-step-1-3" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-step-1-3.png" alt="" width="593" height="485" /></p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-step-4-6.png"><img class="alignnone size-full wp-image-303" title="cygwin-step-4-6" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-step-4-6.png" alt="" width="594" height="488" /></a></p>
<p>Upon arriving at the &#8220;Select  Packages&#8221; dialog, you&#8217;ll be presented with all the packages available  from the selected mirror site(s):</p>
<p><img class="alignnone size-full wp-image-300" title="cygwin-packages-1" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-packages-1.png" alt="" width="497" height="324" /></p>
<p>The installer  allows you to install selected packages, or install by category:</p>
<p><img class="alignnone size-full wp-image-301" title="cygwin-packages-2" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-packages-2.png" alt="" width="610" height="213" /></p>
<p>At the package level,  the rotating arrow icon allows you to cycle through the choices of  installing one of the package versions available, skipping the package,  or in the event the package is already installed, keeping, reinstalling,  uninstalling, or obtaining the source code for the package.  At the  category level, the rotating arrow icon allows you to cycle through the  choices of Default, Install, Reinstall, or Uninstall.</p>
<p>It&#8217;s best  to only select the packages you really think you&#8217;ll want to use or  immediately explore.  There&#8217;s quite a bit of applications available and  choosing everything would result in quite a large installation time.   The installer can always be run at a later time to pickup up additional  packages you want to explore.</p>
<p>By default, Cygwin selects the Base  category packages as well as a few other odds &amp; ends.  Among the  packages skipped by default, you may consider also installing the  following:</p>
<div class="theme-table">
<table style="height: 226px;" border="1" cellspacing="0" cellpadding="2" width="100%">
<tbody>
<tr>
<td width="205" valign="top">Category</td>
<td width="244" valign="top">Package</td>
<td width="318" valign="top">Description</td>
</tr>
<tr>
<td width="206" valign="top">Admin</td>
<td width="243" valign="top">cygrunsrv</td>
<td width="318" valign="top">Utility for easily working with Windows services (adding/removing/starting/stopping).  This is beneficial if you&#8217;d like to run git daemon or sshd as a windows service for anonymous or authenticated access.</td>
</tr>
<tr>
<td width="207" valign="top">Archive</td>
<td width="243" valign="top">zip, unzip</td>
<td width="317" valign="top">PKZip compatible zip capabilities.</td>
</tr>
<tr>
<td width="208" valign="top">Editors</td>
<td width="243" valign="top">vim</td>
<td width="317" valign="top">An enhanced VI editor.</td>
</tr>
<tr>
<td width="208" valign="top">Net</td>
<td width="243" valign="top">openssh</td>
<td width="317" valign="top">Secure shell client and server programs.</td>
</tr>
<tr>
<td width="208" valign="top">Utils</td>
<td width="243" valign="top">ncurses</td>
<td width="317" valign="top">Terminal utilities (has a clear command for clearing the screen).</td>
</tr>
<tr>
<td width="208" valign="top">Web</td>
<td width="243" valign="top">curl</td>
<td width="317" valign="top">Multi-protocol file transfer tool.  This tool is useful for scripting HTTP interaction.</td>
</tr>
</tbody>
</table>
</div>
<p>In  addition, I personally always install the X11 category packages.  While  this adds a bit to the download size, it gives you the ability to run  your preferred shell (e.g. bash) in an xterm as opposed to the standard  terminal window.  I&#8217;ll cover a bit of X11 installation and customization  later in this guide.</p>
<p>When  you&#8217;re done selecting your packages, click &#8220;Next&#8221; and the install will  begin:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-step-7.png"><img class="alignnone size-full wp-image-304" title="cygwin-step-7" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-step-7.png" alt="" width="546" height="397" /></a></p>
<p><img class="alignnone size-full wp-image-305" title="cygwin-step-8" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/cygwin-step-8.png" alt="" width="545" height="398" /></p>
<p>Once complete, click the  Finish button and you&#8217;re done with the install.</p>
<h2>Bash Shell  Customization</h2>
<p>If you selected the &#8220;Add icon to Start Menu&#8221; option  during the install then you should have a new shortcut entitled &#8220;Cygwin  Bash Shell&#8221; which will start the bash shell as an interactive login  shell (i.e. bash &#8211;login -i).  If not, you can browse to cygwin.bat file  located within the chosen installation folder.</p>
<p>When bash runs  for the first time, it checks to see if the home directory (denoted in  the /etc/passwd file) exists for your account.  If not, it creates the  directory and copies over some default config files for your shell:</p>
<p><img class="alignnone size-full wp-image-299" title="bash-text" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/bash-text.png" alt="" width="609" height="317" /></p>
<p>The .bash_profile is  used for login shells while the .bashrc file is used for interactive,  non-login shells.  The default .bash_profile configuration sources the  .bashrc file if it exists, so both are sourced for interactive login  shells.  This effectively allows the .bashrc to serve as the core  configuration for both login and non-login shells.  The .inputrc file is  used to set custom key mappings.  Of the three, the .bashrc file will  generally be the one you&#8217;ll deal with most often.</p>
<p>Go ahead and  open up the .bashrc file.  (Note: Microsoft Notepad does not display  Unix-style line endings correctly.  If using a Windows editor, use  Wordpad.)  After opening the file, you&#8217;ll notice that most of the  configuration is commented out.  The only active configuration are  commands to unset the Windows TMP and TEMP variables.  You can keep this  if you like, but I prefer to keep things a bit more tidy and only have  the configuration I actually use.  If you want to view the default  contents of this file, it can always be viewed from its original source  in /etc/skel.  The following is a more minimal configuration you might  wish to start with:</p>
<pre class="brush: bash;">
unset TMP
unset TEMP

PATH=.:~/bin:${PATH}
PATH=${PATH}:c:/Windows/Microsoft.Net/Framework/v3.5/
PATH=${PATH}:c:/Program\  Files/Reflector/
PATH=${PATH}:c:/Program\ Files/Microsoft\  SDKs/Windows/v6.1/Bin/

. ~/.alias
. ~/.functions
</pre>
<p>In  this configuration, several folders have been added to the PATH  environment variable.  The first places a ~/bin folder before the PATH.   This ensures any custom scripts found in the users bin folder occur  first in the path allowing commands to be overridden.  The remaining  three lines are example folders you might want to set if you are doing  .Net development related tasks at the bash command line.</p>
<p>The  remaining two lines assume the existence of two new files, .alias and  .functions.  I find storing aliases and functions separately to be a bit  more tidy, as well as making it easier to share with others.</p>
<p>Now,  let&#8217;s take a look at the .bash_profile configuration.  By default, the  only configuration that exists is the sourcing of the .bashrc file.   Again, normally the .bashrc file is only sourced for non-login shells,  so this ensures the .bashrc settings are picked up for login shells as  well.</p>
<p>In this file, let&#8217;s replace the contents with the  following:</p>
<pre class="brush: bash;">
#  source the system wide bashrc if it exists
if [ -e /etc/bash.bashrc ]  ; then
source /etc/bash.bashrc
fi

# source the users  bashrc if it exists
if [ -e &quot;${HOME}/.bashrc&quot; ] ; then
source  &quot;${HOME}/.bashrc&quot;
fi

PS1='[\h]: ${PWD##*/} &gt; '
set -o vi
export  DISPLAY=127.0.0.1:0.0
</pre>
<p>In  addition to the existing configuration, we&#8217;ve added three additional  settings.  The first customizes how the prompt appears at the command  line by setting the PS1 variable.  This prompt is a bit plain, but you  can spruce it up with a bit of color by replacing it with the following:</p>
<p>PS1=&#8217;\[\033]0;\w\007\033[32m\][\h]:  \[\033[33m ${PWD##*/}\033[0m\] > &#8216;</p>
<p>Next, I&#8217;ve issued: &#8220;set -o  vi&#8221;.  This tells bash to use a vi-style command line editing interface  which let&#8217;s you more efficiently issue and edit commands at the command  line.  You can delete this if you don&#8217;t ever plan on learning vi.</p>
<p>Next,  I&#8217;ve set an X environment variable named &#8220;DISPLAY&#8221; to my localhost.   This tells the xterm and other X applications where to attempt to  display.  You can delete this if you don&#8217;t plan on running an xterm, but  leaving it certainly won&#8217;t hurt.</p>
<p>This should get you  started.  Your config files will likely evolve from here if you find  yourself working at the command line often.</p>
<h2>Aliases</h2>
<p>The  next step you may want to take is to define some command aliases.  The  bash alias command allows you to set up aliases for verbose or otherwise  undesirable commands.  As indicated, I store all of my aliases in a  .alias file in my home directory to segregate them away from the rest of  my .bashrc configuration.  Here is a subset of my current list of  aliases you might find useful:</p>
<pre class="brush: bash;">
alias programfiles=&quot;cd  /cygdrive/c/Program\ Files&quot;
alias projects=&quot;cd /cygdrive/c/projects&quot;
alias  spikes=&quot;cd /cygdrive/c/projects/spikes&quot;
alias vs='cmd /c *.sln'
alias  vs9='/cygdrive/c/Program\ Files/Microsoft\ Visual\ Studio\  9.0/Common7/IDE/devenv.exe *.sln&amp;amp;'
alias  wordpad='/cygdrive/c//Program\ Files/Windows\  NT/Accessories/wordpad.exe'
alias config='cd  /cygdrive/c/Windows/Microsoft.NET/Framework/v2.0.50727/CONFIG'
alias  mydocs='cd /cygdrive/c/Users/${USER}/Documents'
alias myhome='cd  /cygdrive/c/Documents\ and\ Settings/${USER}/'
alias  fusion='fuslogvw.exe'
</pre>
<p>You&#8217;ll be surprised at how fast you&#8217;ll  start zipping around the system once you&#8217;ve got some good navigation  aliases in place.</p>
<h2>Functions</h2>
<p>I don&#8217;t tend to write a lot  of bash functions, but I&#8217;m including this section here for  completeness.  Like the aliases, I like to segregate any functions I do  write away from my main config file to make things a bit cleaner.  As an  example of what you can do, here is the contents of an example  .functions file which allows you to tweet from the command line:</p>
<pre class="brush: bash;">
tweet()
{
read -s -p &quot;Password:&quot; password
curl -u  derekgreer:$password -d status=&quot;$1&quot;  http://twitter.com/statuses/update.xml
}
</pre>
<div class="theme-note">Note: If you want to actually use this function then you&#8217;ll need to  have downloaded the curl package and will need to modify the Twitter id.</div>
<h2>Basic  Commands</h2>
<p>If you&#8217;re completely new to the Unix shells, the following  are some common commands to get you started with navigating around,  creating folders, deleting files, etc.:</p>
<div class="theme-table">
<table style="height: 268px;" border="1" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td width="312"><strong>Command</strong></td>
<td width="386"><strong>Description</strong></td>
</tr>
<tr>
<td width="312">cd</td>
<td width="386">Change to home directory</td>
</tr>
<tr>
<td width="312">cd [directory name]</td>
<td width="386">Change to a specified directory</td>
</tr>
<tr>
<td width="312">cd -</td>
<td width="386">Change to the last directory</td>
</tr>
<tr>
<td width="312">ls</td>
<td width="386">List the contents of the current folder (like dir)</td>
</tr>
<tr>
<td width="312">ls -la</td>
<td width="386">List the contents of the current folder in long format including all hidden files</td>
</tr>
<tr>
<td width="312">cat [filename]</td>
<td width="386">Print the context of a file (like DOS type)</td>
</tr>
<tr>
<td width="312">![command prefix]</td>
<td width="386">Run the last command starting with the specified prefix.</td>
</tr>
<tr>
<td width="312">mkdir [directory name]</td>
<td width="386">Make a new directory</td>
</tr>
<tr>
<td width="312">mkdir -p [directory hierarchy]</td>
<td width="386">Make a all directories listed (e.g. mkdir -p a/b/c/d)</td>
</tr>
<tr>
<td width="312">rm [filename]</td>
<td width="386">Remove a file</td>
</tr>
<tr>
<td width="312">rm -rf [filename]</td>
<td width="386">Remove recursively with force</td>
</tr>
<tr>
<td width="312">find [start folder] -name [regex] -print</td>
<td width="386">Starting at the start folder, find a file matching the given regular expression.</td>
</tr>
<tr>
<td width="312">grep [regex] [filename]</td>
<td width="386">Display all lines matching the regular expression from the given file.</td>
</tr>
</tbody>
</table>
</div>
<h2>Scripts</h2>
<p>Once  you start getting comfortable with the available commands, you may wish  to start writing your own scripts to help with various everyday tasks.   While covering the basics of bash shell scripting is beyond the  intended scope of this article, you can obtain an archive of some  scripts I&#8217;ve written for my own purposes from <a id="cf28" title="Bash Scripts" href="http://www.aspiringcraftsman.com/downloads/bashscripts.zip">here</a>.   Here&#8217;s a list of the contained  scripts along with a brief description:</p>
<div class="theme-table">
<table style="height: 162px;" border="1" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td width="315"><strong>Script</strong></td>
<td width="383"><strong>Description</strong></td>
</tr>
<tr>
<td width="315">clean</td>
<td width="383">Cleans up common temp/generated Visual Studio files.</td>
</tr>
<tr>
<td width="315">detachfromcvs</td>
<td width="383">Removes CVS folders.</td>
</tr>
<tr>
<td width="315">detachfromtfs</td>
<td width="383">Removes TFS bindings from source files.</td>
</tr>
<tr>
<td width="315">diff</td>
<td width="383">Overrides the diff command to call WinMerge</td>
</tr>
<tr>
<td width="315">git-diff-wrapper.sh</td>
<td width="383">Diff wrapper for use with Git.</td>
</tr>
<tr>
<td width="315">replaceinfile</td>
<td width="383">Replaces string patterns in a file.</td>
</tr>
<tr>
<td width="315">replaceinfiles</td>
<td width="383">Wrapper for calling replaceinfile for files matching a given pattern.</td>
</tr>
<tr>
<td width="315">rgrep</td>
<td width="383">Recursive grep (Also greps from .Net assemblies)</td>
</tr>
<tr>
<td width="315">unix2dosall</td>
<td width="477">Recursive unix2dos</td>
</tr>
</tbody>
</table>
</div>
<h2>X11  &#8211; Using an XTerm</h2>
<p>The final portion of this guide is intended for  those who would like to explore the X Windows system provided by  Cygwin.  One of the benefits of running an XServer on Windows is the  ability to use an XTerm over the standard terminal provided by DOS.   XTerm provides more flexibility over the fonts, colors used, and buffers  used, provides dynamic resizing, and provides much more intuitive  cut-n-paste capabilities (highlight = cut, middle mouse button =  paste).  It also displays buffered text which comes in handy when you  want to use the tail -f command to follow a log file and queue up a  bunch of spaces to visually separate new entries.</p>
<p>Assuming you&#8217;ve  already installed the X11 packages, locate the Cygwin-X folder in your  start menu and execute the &#8220;XWin Server&#8221; shortcut.  By default, the  XServer starts a plain white terminal:</p>
<p><img class="alignnone size-full wp-image-306" title="white-xterm" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/white-xterm.png" alt="" width="351" height="265" /></p>
<p>Since this isn&#8217;t  likely the style of terminal you&#8217;ll want to work with, you can prevent  XServer from starting this default xterm by creating an empty  .startxwinrc file in your home directory.  You can do this by using the  touch command:</p>
<p>touch ~/.startxwinrc</p>
<p>Next, you can  modify the XTerm shortcut that was created in your start menu&#8217;s  Cygwin-X folder to start a new xterm with no menu, a custom font,  colors, a scrollbar, etc. using the following Target value:</p>
<p>C:\Cygwin\bin\run.exe  -p /usr/X11R6/bin xterm -display 127.0.0.1:0.0 -ls -vb -fn 10&#215;20 +tb  -bg gray14 -fg ivory -sb -rightbar -sl 400</p>
<p>This command will  launch an xterm similar to the following:</p>
<p><img class="alignnone size-full wp-image-307" title="xterm" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/04/xterm.png" alt="" width="607" height="351" /></p>
<p>From  here, you may consider adding the XWin Server shortcut to your startup.</p>
<p>That  concludes my guide.  Enjoy!</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/2fEmSQS7bnI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/04/getting-started-with-cygwin/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/04/getting-started-with-cygwin/</feedburner:origLink></item>
		<item>
		<title>Git: Anonymous Access Under Windows</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/O20pb84jKDs/</link>
		<comments>http://www.aspiringcraftsman.com/2010/03/git-anonymous-access-under-windows/#comments</comments>
		<pubDate>Sun, 14 Mar 2010 21:28:09 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Git]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=277</guid>
		<description><![CDATA[The Git version control system provides a simple protocol for sharing Git repositories anonymously over a TCP port. This can be useful for providing read-only access to a repository, or for facilitating pull-based collaboration within teams. The following is a guide for setting up and sharing a Git repository anonymously under Windows using Cygwin. Step [...]]]></description>
			<content:encoded><![CDATA[<p>The <a title="Git Version Control" href="http://git-scm.com/" target="_blank">Git </a>version control system provides a simple protocol for sharing Git repositories anonymously over a TCP port.  This can be useful for providing read-only access to a repository, or for facilitating pull-based collaboration within teams.  The following is a guide for setting up and sharing a Git repository anonymously under Windows using <a title="Cygwin" href="http://www.cygwin.com/" target="_blank">Cygwin</a>.</p>
<p><strong>Step 1:</strong> Install <a title="Cygwin" href="http://www.cygwin.com/" target="_blank">Cygwin </a>with the cygrunsrv and desired git packages:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/03/cygwin-search-cygrunsrv-package.png"><img class="alignnone size-full wp-image-278" title="cygwin-search-cygrunsrv-package" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/03/cygwin-search-cygrunsrv-package.png" alt="" width="550" height="208" /></a></p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/03/cygwin-search-git-package.png"><img class="alignnone size-full wp-image-279" title="cygwin-search-git-package" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/03/cygwin-search-git-package.png" alt="" width="722" height="265" /></a></p>
<p><strong>Step 2:</strong> Create a file named <code>gitd</code> in the <code>/usr/sbin</code> directory with the following content:</p>
<pre class="brush: bash;">
#!/bin/bash

git daemon --reuseaddr --base-path=/cygdrive/c/Projects
</pre>
<p><br/></p>
<div class="theme-note">
Notes:</p>
<p>By default, the git daemon only shares folders under the base path which contain a file named <code>git-daemon-export-ok</code>.  If you wish to share all folders under the base path without requiring this file, use the switch <code>--export-all</code>.</p>
<p>This command assumes the base path of all shared git repositories will be <code>/cygdrive/c/Projects/</code> (i.e. <code>C:\Projects\</code> under Windows).  Change this value if your projects are stored in an alternate location.</p>
<p>If you wish to enable anonymous push access to your repositories (not advisable), you can add the switch <code>--enable=receive-pack</code>.</p>
</div>
<p><br/></p>
<div><strong>Step 3:</strong> From a bash shell prompt, run the following <code>cygrunsrv</code> command to install the script as a service (Note: This command assumes Cygwin is installed at <code>C:\Cygwin</code>):</p>
<pre class="brush: bash;">
cygrunsrv   --install gitd                        \
            --path c:/cygwin/bin/bash.exe         \
            --args c:/cygwin/usr/sbin/gitd        \
            --desc &quot;Git Daemon&quot;                   \
            --neverexits                          \
            --shutdown
</pre>
</div>
<p><strong>Step 4:</strong> From a bash shell prompt, run the following command to start the service:</p>
<p><code>cygrunsrv --start gitd</code></p>
<p>The gitd service should now be running.  To verify that everything is setup properly, here is a quick and dirty script which should establish that the desired repositories are remotely accessible:</p>
<pre class="brush: bash;">
#!/bin/bash

BASEDIR=/cygdrive/c/Projects
REPO_NAME=testapp$$
REPO_PATH=${BASEDIR}/${REPO_NAME}
REMOTE_PATH=${BASEDIR}/remote$$/

echo &quot;Creating a local git repo ...&quot;
mkdir -p ${REPO_PATH}
cd ${REPO_PATH}
git init
touch .git/git-daemon-export-ok
echo &quot;Commiting test file ...&quot;
touch testfile
git add -A
git commit -m 'Test message'

echo &quot;Simulate remote clone ...&quot;
mkdir ${REMOTE_PATH}
cd ${REMOTE_PATH}
git clone git://localhost/${REPO_NAME}

echo &quot;Cleaning up test folders ...&quot;
rm -rf ${REPO_PATH}
rm -rf ${REMOTE_PATH}
</pre>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/O20pb84jKDs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/03/git-anonymous-access-under-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/03/git-anonymous-access-under-windows/</feedburner:origLink></item>
		<item>
		<title>Resharper Naming Style for Machine.Specifications</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/IBBmroY_lVc/</link>
		<comments>http://www.aspiringcraftsman.com/2010/02/resharper-naming-style-for-machine-specifications/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 01:59:37 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Machine.Specifications]]></category>
		<category><![CDATA[Resharper]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=222</guid>
		<description><![CDATA[If you&#8217;re doing BDD-style specifications and using underscores within your variable names, the default Resharper settings will warn you about violating the naming style rules as shown below: Fortunately, Machine.Specifications (MSpec) extends Resharper to allow for the creation of custom rules which affect only your MSpec types. To create a custom rule for MSpec, follow [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re doing BDD-style specifications and using underscores within your variable names, the default Resharper settings will warn you about violating the naming style rules as shown below:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperUnconfigured.png"><img class="size-full wp-image-223" title="ResharperUnconfigured" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperUnconfigured.png" alt="" width="661" height="442" /></a></p>
<p>Fortunately, Machine.Specifications (MSpec) extends Resharper to allow for the creation of custom rules which affect only your MSpec types.  To create a custom rule for MSpec, follow these steps:</p>
<p><strong>Step 1</strong>: Open the Resharper Options Dialog.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptions.png"><img class="alignnone size-full wp-image-255" title="ResharperOptions" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptions.png" alt="" width="229" height="453" /></a></p>
<p><strong>Step 2</strong>: Navigate to Languages | Naming Style and under &#8220;User defined naming rules&#8221; click &#8220;Add&#8221;.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyle_add.png"><img class="size-full wp-image-224" title="ResharperOptionsLanguagesNamingStyle_add" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyle_add.png" alt="" width="622" height="599" /></a></p>
<p><strong>Step 3</strong>: This displays the &#8220;Edit Extended Naming Rule dialog.  In the &#8220;Rule Definition:&#8221; text box, give your new rule a name such as &#8220;Machine.Specifications Rules&#8221;.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescription.png"><img class="alignnone size-full wp-image-261" title="ResharperOptionsLanguagesNamingStyleRuleDescription" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescription.png" alt="" width="492" height="446" /></a></p>
<p><strong>Step 4</strong>: Within the Affected entities list, un-check Class and scroll to the bottom to locate the entries starting with Machine.Specifications.  Select all of these entries.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescriptionModified.png"><img class="alignnone size-full wp-image-260" title="ResharperOptionsLanguagesNamingStyleRuleDescriptionModified" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescriptionModified.png" alt="" width="492" height="443" /></a></p>
<p><strong>Step 5</strong>: Select all options under Access rights: and leave options under Static/non-static: selected.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleAccessRights.png"><img class="alignnone size-full wp-image-263" title="ResharperOptionsLanguagesNamingStyleAccessRights" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleAccessRights.png" alt="" width="483" height="190" /></a></p>
<p><strong>Step 6</strong>: Add a new naming style to associate this rule to by clicking the Add icon and selecting the desired naming style (e.g. all_lower).</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleStyle.png"><img class="alignnone size-full wp-image-264" title="ResharperOptionsLanguagesNamingStyleRuleStyle" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleStyle.png" alt="" width="224" height="622" /></a></p>
<p>The following diagram shows the dialog after these steps:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperEditExtendedNamingRuleDialog.png"><img class="size-full wp-image-249" title="ResharperEditExtendedNamingRuleDialog" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperEditExtendedNamingRuleDialog.png" alt="" width="650" height="598" /></a></p>
<p style="padding: 10px;">After selecting OK, Resharper now ignores the naming warnings for the MSpec types:</p>
<div><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperConfigured.png"><img class="size-full wp-image-266" title="ResharperConfigured" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperConfigured.png" alt="" width="648" height="440" /></a></div>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/IBBmroY_lVc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/02/resharper-naming-style-for-machine-specifications/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/02/resharper-naming-style-for-machine-specifications/</feedburner:origLink></item>
		<item>
		<title>Embracing Dependency Injection</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/eh5vu0wR3AE/</link>
		<comments>http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 14:59:00 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Dependency Injection]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/</guid>
		<description><![CDATA[Recently, a fairly notable icon within the software development community posted some thoughts on Twitter which I found surprising. The individual stated: &#8220;What&#8217;s the right number of dependencies to inject? A few. In a very large system, perhaps a few dozen.&#8221; Given that I found this statement to be fairly controversial, I urged the individual [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, a fairly notable icon within the software development community posted some thoughts on Twitter which I found surprising.  The individual stated:</p>
<p style="padding-left: 30px;"><em> &#8220;What&#8217;s the right number of dependencies to inject?  A few.  In a very large system, perhaps a few dozen.&#8221; </em></p>
<p>Given that I found this statement to be fairly controversial, I urged the individual to write an article explaining what had brought them to such a conclusion.  Later that day, an article was published on the subject explaining their position.  After reading the article, it became clear that what was being argued against was the degree of coupling to a dependency injection framework, not dependency injection in general.  While minimizing an application&#8217;s degree of coupling to any given framework is a goal to be encouraged, the argument was partially based upon a lack of familiarity with the conventional use of dependency injection containers.</p>
<p>In an effort to demonstrate that use of a dependency injection framework is usually unnecessary,the article presents two versions of an example billing application with and without relying upon a framework.  The following is a C# version approximating the examples presented within the article:</p>
<p><strong>Dependency Injection Framework Version</strong></p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            IContainer container = new Container().AddConfiguration(BillingConfiguration);
            BillingService billingService = container.Resolve&lt;BillingService&gt;();

            // TODO: do something with the billing service ...
        }
    }

    public class BillingConfiguration : ContainerConfiguration
    {
        protected void Configure()
        {
             Register&lt;ICreditCardService&gt;().As&lt;CreditCardService&gt;();
             Register&lt;ITransactionLog&gt;().As&lt;DatabaseTransactionLog&gt;();
        }
    }
</pre>
<p><strong>Manual Dependency Injection Version</strong></p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            BillingService billingService = new BillingService(new CreditCardProcessor(), new TransactionLog());

            // TODO: do something with the billing service ...
        }
    }
</pre>
<p>Comparing the two examples, the second is obviously the more straight forward and concise of the two approaches.</p>
<p>Foreseeing the concern that one might want to use the billing service in a lower layer of the application, the article proceeds to set forth an example which configures a globally accessible static instance of the service within the main method:</p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            BillingService billingService = new BillingService(new CreditCardProcessor(), new TransactionLog());
            BillingService.Instance = billingService;

            // Now the BillingService.Instance can be accessed anywhere within the application
        }
    }
</pre>
<p>To further address the need to create separate instances of the billing service, the article next presents an example which configures a globally accessible Factory instance which can be accessed from other parts of the application.  Perhaps in an attempt to show some recognition of the benefits of using a framework, the Factory is designed to encapsulate the registration and use of a container for retrieving instances of the billing service:</p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            IContainer container = new Container().AddConfiguration(BillingConfiguration);
            BillingService.Factory = new BillingServiceFactory(container);

            // Now we can make new instances of the billing service anywhere within the application
            BillingService billingService = BillingService.Factory.Create();
        }
    }

    public class BillingServiceFactory : ContainerConfiguration
    {
        IContainer _container;

        public BillingServiceFactory(IContainer container)
        {
            _container = container;
        }

        protected void Configure()
        {
             Register&lt;ICreditCardService&gt;().As&lt;CreditCardService&gt;();
             Register&lt;ITransactionLog&gt;().As&lt;DatabaseTransactionLog&gt;();
        }

        public BillingService Create()
        {
            return _container.Resolve&lt;BillingService&gt;() ;
        }
    }
</pre>
<p>The article concludes by submitting that dependency injection frameworks should only be used for areas of an application that are known extension points, and that in most cases the best course of action is to manually instantiate any needed objects along with their dependencies.</p>
<p>While these examples may seem perfectly sensible to those unfamiliar with using a dependency injection framework, there are several problems with the techniques presented here.</p>
<p>First, the simplicity of these examples fail to highlight the issues involved in real-world applications.  Applications designed with an adherence to low-coupling and preferring composition over inheritance often result in object grafts many levels deep.  That is to say, the dependencies of one object may have dependencies of their own, which in turn have dependencies of their own, and so forth and so on.  While it is possible to use the manual instantiation techniques described in the first example, the resulting code will soon become both unsightly and unwieldy.  Couple that with the reuse of components across multiple types and duplication starts to arise.  The examples above don&#8217;t highlight these issues since they are only working with a simple object graph.</p>
<p>Second, issues arise in the introduction of global variables to access instances of the billing service or the factory.  For one, the design becomes more opaque.  Classes which reference global resources don&#8217;t express their external dependencies through their interface thereby requiring you to look at the code to discover what dependencies are required.  Two, this introduces a responsibility to the billing service which isn&#8217;t an inherent concern.  The responsibility for the creation and lifetime management of the service is a separate concern from the service&#8217;s core responsibilities and one which can change for different reasons.</p>
<p>Third, the encapsulation of the container registration and resolution of the billing service within the factory actually serves to more tightly couple the application to the dependency injection framework.  What&#8217;s been missed in the examples thus far is the fact that the billing service is itself a dependency of other types and they in turn may themselves be dependencies.  By ensuring that all types within the system are using dependency injection, the entire dependency chain can be resolved by one call to the container.  This eliminates the need to produce specialized factories for each type.</p>
<p>Consider the following example:</p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            new Bootstrapper().Run();
        }
    }

    public class Bootstrapper
    {
        public void Run()
        {
            ConfigureContainer();
            Container.Resolve&lt;IShell&gt;().Show();
        }

        void ConfigureContainer()
        {
            // Configure the container
        }
    }

    public interface IBillingService
    {
        // define billing methods
    }

    public class BillingService : IBillingService
    {
        public BillingService(ICreditCardProcessor creditCardProcessor, ITransactionLog transactionLog) { ... }

        // implement IBillingService methods here
    }

    public interface IShell
    {
         void Show();
    }

    public class Shell : IShell
    {
        public Shell(IBillingService billingService) { ... }

        public void Show() { ... }
    }
</pre>
<p>In this example the container is only referenced from within the Bootstrapper and the container is only used to resolve an instance of the type IShell.  Given that all types have been registered, the container traverses the dependency chain, building up the object graph from the bottom up.  This allows the entire application to remain decoupled from the dependency injection framework as well as avoiding the need to create and further maintain type specific factories.  As the application grows in complexity, there may be the need to introduce other entry points or strategies for handling lazy-loading, but coupling to the container would remain minimal.</p>
<p>If you find yourself needing to invert your dependencies on an inversion of control framework then you are doing it wrong.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/eh5vu0wR3AE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/</feedburner:origLink></item>
		<item>
		<title>The Arrow Anti-pattern</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/SH_kzuPdKaY/</link>
		<comments>http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 09:46:00 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Arrow Anti-pattern]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/</guid>
		<description><![CDATA[The Arrow Ani-pattern is a name given to the resulting structure produced by using excessive nested conditional operators. The following pseudo-code demonstrates why the name is apt: if( ... ) { if( ... ) { if( ... ) { if( ... ) { if( ... ) { //--&#62; do something } } } } } [...]]]></description>
			<content:encoded><![CDATA[<p>The Arrow Ani-pattern is a name given to the resulting structure produced by using excessive nested conditional operators.  The following pseudo-code demonstrates why the name is apt:</p>
<pre class="brush: csharp;">
if( ... )
{
    if( ... )
    {
        if( ... )
        {
            if( ... )
            {
                if( ... )
                {
                    //--&gt; do something
                }

            }
        }
    }
}
</pre>
<p>The structure above becomes increasingly problematic as each additional nested condition adds to the cognitive load required to parse the represented logic.  According to studies performed by Noam Chomsky and Gerald Weinberg in 1986, few people can easily understand more than three levels of nested conditional statements.  It is therefore recommended that techniques for restructuring the code be sought out when this pattern begins to emerge.</p>
<h2>Guard Clauses</h2>
<p>One approach to refactoring the arrow anti-pattern is to use guard clauses.  Guard clauses are a form of assertion which makes a tangible contribution to the logic of the method.  By restructuring nested conditional statements to successive conditional exit points, the code becomes easier to understand and eases further refactoring efforts such as method extraction or clause reordering.</p>
<pre class="brush: csharp;">
void SomeProcess()
{
    if( ... )
        return;

    if( ... )
        return;

    if( ... )
        return;

    if( ... )
        return;

    if( ... )
        return;

    // do something
}
</pre>
<h2>Method Extraction</h2>
<p>Another approach especially suited to blocks comprised of nested looping structures is the extraction of segments into separate methods.  For each block forming the body of a loop statement, extract the body into a separate method which can then be examined independently of the containing loop statement:</p>
<p>Before</p>
<pre class="brush: csharp;">
    void SomeProcess()
    {
        while( ... )
        {
            while( ... )
            {
                while( ... )
                {
                    while( ... )
                    {
                    }
                }
            }
        }
    }
</pre>
<p>After</p>
<pre class="brush: csharp;">
    void SomeProcess()
    {
        while( ... )
        {
            MethodA();
        }
    }

    void MethodA()
    {
        while( ... )
        {
            MethodB();
        }
    }

    void MethodB()
    {
        while( ... )
        {
            MethodC();
        }
    }

    void MethodC()
    {
        while( ... )
        {
            MethodD();
        }
    }
</pre>
<h2>Logical And/Or</h2>
<p>In cases where the nested structure is comprised solely of checks against the state of an object, the conditions can be extracted into a collection of Boolean methods and combined to form a more concise and readable guard clause:</p>
<pre class="brush: csharp;">
void SomeProcess()
{
    if(ConditionA() &amp;&amp;
          ConditionB() &amp;&amp;
          ConditionC() &amp;&amp;
          (ConditionD1() || ConditionD2()) &amp;&amp;
          ConditionE())
    {
        // do something
    }
}
</pre>
<h2>Composite Specification Chain</h2>
<p>As a variant to the previous technique, the Specification pattern can be used in the form of a composite specification chain to render a concise and readable guard clause.  Using this technique, specification classes are written to test each case, and the resulting set of specifications are composed into a single composite specification which can evaluate the state of the given object.  Due to the encapsulation of the evaluation logic in the form of separate specification classes, this technique has the added benefit of enabling substitution of the specification implementation via the Strategy pattern for test isolation or other variable composition needs.</p>
<pre class="brush: csharp;">
void SomeProcess()
{
    ISpecification&lt;SomeType&gt; specification = new IsConditionA()
        .And(new IsConditionB())
        .And(new IsConditionC())
        .And(new IsConditionD1().Or(IsConditionD2()))
        .And(new IsConditionE());

    specification.IsSatisfiedBy(this).Then(() =&gt; { /* do something */ });
}
</pre>
<h2>Conclusion</h2>
<p>The techniques presented here are a few approaches to helping achieve more readable and maintainable code by eliminating the arrow anti-pattern.  Through the judicious application of these techniques, developers can in small ways leave their code base cleaner than they found it.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/SH_kzuPdKaY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/</feedburner:origLink></item>
		<item>
		<title>Composite Applications with NHibernate</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/ZlYqveFSJ2U/</link>
		<comments>http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 12:12:00 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Composite Application Development]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/</guid>
		<description><![CDATA[Composite application architecture is an approach to software development which seeks to produce applications which can be constructed from pre-built components, thus allowing a single platform to be more easily customized for end users. The pre-built components, or modules, comprising a composite application often share data access concerns such as the need to access a [...]]]></description>
			<content:encoded><![CDATA[<p>Composite application architecture is an approach to software development which seeks to produce applications which can be constructed from pre-built components, thus allowing a single platform to be more easily customized for end users.</p>
<p>The pre-built components, or modules, comprising a composite application often share data access concerns such as the need to access a central database. The use of object-relational mapping frameworks are an increasingly common strategy for facilitating data access needs. This is due to their ability to minimize much of the repetitive, low-level data access coding often required by more traditional approaches, and their ability to abstract much of the idiosyncrasies of specific database vendors, providing greater potential for portability between vendors.</p>
<p>NHibernate, arguably the leading object-relational mapping framework for the .Net platform, facilitates object-relational mapping through a centrally configured component called the SessionFactory. A SessionFactory is configured with the connection parameters for a specific database along with the mapping meta-data required for associating objects to the relational data within the database.</p>
<p>It is generally advised that a single SessionFactory be created per database. This is both due to the overhead required in its creation, and in order to facilitate various caching strategies such as the caching of generated SQL statements, and of entities across sessions (referred to as the second-level cache).</p>
<p>For composite applications, configuration of the SessionFactory can pose a bit of an obstacle given that any centralization of the mapping configuration would tend to couple otherwise independent and optional modules together. Additionally, a centralized configuration of the mappings for each of the modules precludes encapsulation of the configuration needs within each module, and can introduce maintenance complexity for modules developed by separate development teams or organizations. On the other hand, allowing modules to maintain their own SessionFactory for a shared database instance introduces startup overhead and precludes taking advantage of the caching features of the framework.</p>
<p>As demonstrated in the remainder of this article, one approach to solving these challenges is to create a staged application bootstrapping process which both facilitates decentralized mapping registration and centralized SessionFactory initialization.</p>
<p>While potentially applicable in other usage scenarios, the following approach is based upon the use of Fluent NHibernate, the Prism composite application library, and the staged bootstrapping strategy presented within the article: <a href="2009/05/enhancing-the-prism-module-initialization-lifecycle/">Enhancing the Prism Module Initialization Lifecycle</a>.</p>
<p>Our first step in demonstrating this strategy will be to create a module named DataModule which will serve as an infrastructure-only Prism module for configuring NHibernate. Using the ModuleBase implementation of IModule presented in the aforementioned article, the OnPreInitialization() and OnPostInitialization() methods will be overridden.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Module
{
    public class DataModule : ModuleBase
    {
        readonly IUnityContainer _container;

        public DataModule(IUnityContainer container)
        {
            _container = container;
        }

        protected override void OnPreInitialization()
        {
        }

        protected override void OnPostInitialization()
        {
        }
    }
}
</pre>
<p>The OnPreInitialization() method will be used to register services to be consumed by other modules while the OnPostInitialization phase will be used to perform the final database configuration.</p>
<p>Next, let’s create a CustomerModule which represents a module using NHibernate for its data access needs. This module need only override the OnInitialization() method to gain access to services registered during the Pre-Initialization bootstrapping phase.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Module
{
    public class CustomerModule : ModuleBase
    {
        readonly IUnityContainer _container;

        public DataModule(IUnityContainer container)
        {
            _container = container;
        }

        protected override void OnInitialization()
        {
        }
    }
}
</pre>
<p>Next, we’ll define a mapping service to be used by our CustomerModule for registering which map types and/or assemblies are to be included during the configuration of the SessionFactory.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Services
{
    public interface IMappingRegistryService
    {
        void AddMap() where T : IClassMap;
        void AddMap(Type classMap);
        void AddMapsFromAssemblyOf();
        void AddMapsFromAssembly(Assembly assembly);
    }
}
</pre>
<p>Next, we’ll provide an internal implementation of the mapping service to be contained within t<br />
he DataModule. Two additional properties, Assemblies and Types, are provided to enable the DataModule to access any mapping types and assemblies registered by modules during the Initialization phase.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Module.Services
{
    class MappingRegistryService : IMappingRegistryService
    {
        readonly IList _assemblies;
        readonly List _types;

        public MappingRegistryService()
        {
            _assemblies = new List();
            _types = new List();
        }

        public IEnumerable Assemblies
        {
            get { return _assemblies; }
        }

        public IEnumerable Types
        {
            get { return _types; }
        }

        public void AddMap() where T : IClassMap
        {
            AddMap(typeof (T));
        }

        public void AddMap(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(&quot;type&quot;);
            }

            if (!_types.Contains(type))
            {
                _types.Add(type);
            }
        }

        public void AddMapsFromAssemblyOf()
        {
            AddMapsFromAssembly(typeof (T).Assembly);
        }

        public void AddMapsFromAssembly(Assembly assembly)
        {
            if (!_assemblies.Contains(assembly))
            {
                _assemblies.Add(assembly);
            }
        }
    }
}
</pre>
<p>With the service defined, let’s return to the DataModule and complete the body of the initialization methods.</p>
<p>To ensure the mapping service is available during the initialization phase of the other modules within the application, the IMappingRegistryService and its internal implementation need to be registered as a singleton with the Unity container during the PreInitialization bootstrapping phase:</p>
<pre class="brush: csharp;">
        protected override void OnPreInitialization()
        {
            _container.RegisterType(new ContainerControlledLifetimeManager());
        }
</pre>
<p>After modules have been given an opportunity to register mappings with our service during the Initialization phase, the service can be retrieved and used to supply the class map types and/or assemblies required for the Fluent NHibernate configuration:</p>
<pre class="brush: csharp;">
        protected override void OnPostInitialization()
        {
            var service = _container.Resolve() as MappingRegistryService;

            ISessionFactory sessionFactory = Fluently.Configure()
                .Database(OracleConfiguration.Oracle9
                              .ConnectionString(
                              c =&gt; c.Is(ConfigurationManager.ConnectionStrings[&quot;example&quot;].ConnectionString))
                              .ShowSql())
                .Mappings(m =&gt;
                    {
                        service.Types.ForEach(t =&gt; m.FluentMappings.Add(t));

                        service.Assemblies.ForEach(a =&gt; m.FluentMappings.AddFromAssembly(a));
                    })
                .BuildSessionFactory();

            _container
                .RegisterInstance(new NHibernateDatabaseContext(sessionFactory),
                                  new ContainerControlledLifetimeManager());
        }
</pre>
<p>Our final step is to complete the initialization method within our CustomerModule to register any desired mappings to be used by the DataModule:</p>
<pre class="brush: csharp;">
        protected override void OnInitialization()
        {
            var dataMappingService = _container.Resolve();
            if (dataMappingService != null) dataMappingService.AddMapsFromAssemblyOf();
        }
</pre>
<p>That concludes our example.</p>
<p>By utilizing a mapping service in conjunction with a multi-phased initialization strategy, a proper level of separation of concerns can be maintained for the modules within a composite application while at the same time utilizing NHibernate’s SessionFactory in the prescribed manner.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/ZlYqveFSJ2U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/</feedburner:origLink></item>
	</channel>
</rss>
