<?xml version="1.0" encoding="utf-8"?>
<feed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xml:lang="en-us" xmlns="http://www.w3.org/2005/Atom">
  <title>ploeh blog</title>
  <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/" />
  <link rel="self" href="http://blog.ploeh.dk/SyndicationService.asmx/GetAtom" />
  <icon>favicon.ico</icon>
  <updated>2012-04-24T13:45:41.477122+02:00</updated>
  <author>
    <name>Mark Seemann</name>
  </author>
  <subtitle>Mark Seemann's .NET blog</subtitle>
  <id>http://blog.ploeh.dk/</id>
  <generator uri="http://dasblog.info/" version="2.3.9074.18820">DasBlog</generator>
  <entry>
    <title>Vendor Media Types With the ASP.NET Web API</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/04/24/VendorMediaTypesWithTheASPNETWebAPI.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,29754191-c40d-474a-b063-d00b1154638b.aspx</id>
    <published>2012-04-24T13:45:41.477122+02:00</published>
    <updated>2012-04-24T13:45:41.477122+02:00</updated>
    <category term="ASP.NET MVC" label="ASP.NET MVC" scheme="http://blog.ploeh.dk/CategoryView,category,ASPNETMVC.aspx" />
    <category term="REST" label="REST" scheme="http://blog.ploeh.dk/CategoryView,category,REST.aspx" />
    <category term="Services" label="Services" scheme="http://blog.ploeh.dk/CategoryView,category,Services.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
In RESTful services, media types (e.g. application/xml, application/json) are an important
part of Content Negotiation (<em>conneg</em> in the jargon). This enables an API to
provide multiple <em>representations</em> of the same resource.
</p>
        <p>
Apart from the standard media types such as application/xml, application/json, etc.
an API can (and often should, IMO) expose its resources using specialized media types.
These often take the form of vendor-specific media types, such as application/vnd.247e.catalog+xml
or application/vnd.247e.album+json.
</p>
        <p>
In this article I'll present some initial findings I've made while investigating this
in the <a href="http://www.asp.net/web-api">ASP.NET Web API</a> (beta).
</p>
        <p>
For an introduction to conneg with the Web API, see <a href="http://weblogs.asp.net/gunnarpeipman/default.aspx">Gunnar
Peipman's ASP.NET blog</a>, particularly these two posts:
</p>
        <ul>
          <li>
            <a href="http://weblogs.asp.net/gunnarpeipman/archive/2012/04/19/asp-net-web-api-how-content-negotiation-works.aspx">ASP.NET
Web API: How content negotiation works?</a>
          </li>
          <li>
            <a href="http://weblogs.asp.net/gunnarpeipman/archive/2012/04/20/asp-net-web-api-extending-content-negotiation-with-new-formats.aspx">ASP.NET
Web API: Extending content negotiation with new formats</a>
          </li>
        </ul>
        <p>
          <strong>The Problem</strong>
        </p>
        <p>
In a particular RESTful API, I'd like to enable vendor-specific media types as well
as the standard application/xml and application/json media types.
</p>
        <p>
More specifically, I'd like to add these media types to the API:
</p>
        <ul>
          <li>
application/vnd.247e.album+xml 
</li>
          <li>
application/vnd.247e.artist+xml 
</li>
          <li>
application/vnd.247e.catalog+xml 
</li>
          <li>
application/vnd.247e.search-result+xml 
</li>
          <li>
application/vnd.247e.track+xml 
</li>
          <li>
application/vnd.247e.album+json 
</li>
          <li>
application/vnd.247e.artist+json 
</li>
          <li>
application/vnd.247e.catalog+json 
</li>
          <li>
application/vnd.247e.search-result+json 
</li>
          <li>
application/vnd.247e.track+json</li>
        </ul>
        <p>
However, I can't just add all these media types to GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes
or GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.
If I do that, each and every resource in the API would accept and (claim to) return
all of those media types. That's not what I want. Rather, I want specific resources
to accept and return specific media types.
</p>
        <p>
For example, if a resource (Controller) returns an instance of the SearchResult (Model)
class, it should only accept the media types application/vnd.247e.search-result+xml,
application/vnd.247e.search-result+json (as well as the standard application/xml and
application/json media types).
</p>
        <p>
Likewise, a resource handling the Album (Model) class should accept and return application/vnd.247e.album+xml
and application/vnd.247e.album+json, and so on.
</p>
        <p>
Figuring out how to enable such behavior took me a bit of fiddling (yes, <a href="http://fiddler2.com/fiddler2/">Fiddler</a> was
involved).
</p>
        <p>
          <strong>The Solution</strong>
        </p>
        <p>
The Web API uses a polymorphic collection of <a href="http://msdn.microsoft.com/en-us/library/system.net.http.formatting.mediatypeformatter%28v=vs.108%29.aspx">MediaTypeFormatter</a> classes.
These classes can be extended to be more specifically targeted at a specific Model
class.
</p>
        <p>
For XML formatting, this can be done by deriving from the built-in XmlMediaTypeFormatter
class:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">TypedXmlMediaTypeFormatter</span> : <span style="color: #2b91af">XmlMediaTypeFormatter</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">Type</span> resourceType;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> TypedXmlMediaTypeFormatter(<span style="color: #2b91af">Type</span> resourceType,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">MediaTypeHeaderValue</span> mediaType)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.resourceType
= resourceType;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.SupportedMediaTypes.Clear();</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.SupportedMediaTypes.Add(mediaType);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: blue">bool</span> CanReadType(<span style="color: #2b91af">Type</span> type)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.resourceType
== type;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: blue">bool</span> CanWriteType(<span style="color: #2b91af">Type</span> type)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.resourceType
== type;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The implementation is quite simple. In the constructor, it makes sure to clear out
any existing supported media types and to add only the media type passed in via the
constructor.
</p>
        <p>
The CanReadType and CanWriteType overrides only return true of the type parameter
matches the type targeted by the particular TypedXmlMediaTypeFormatter instance. You
could say that the TypedXmlMediaTypeFormatter provides a specific match between a
media type and a resource Model class.
</p>
        <p>
The JSON formatter is similar:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">TypedJsonMediaTypeFormatter</span> : <span style="color: #2b91af">JsonMediaTypeFormatter</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">Type</span> resourceType;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> TypedJsonMediaTypeFormatter(<span style="color: #2b91af">Type</span> resourceType,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">MediaTypeHeaderValue</span> mediaType)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.resourceType
= resourceType;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.SupportedMediaTypes.Clear();</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.SupportedMediaTypes.Add(mediaType);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: blue">bool</span> CanReadType(<span style="color: #2b91af">Type</span> type)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.resourceType
== type;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: blue">bool</span> CanWriteType(<span style="color: #2b91af">Type</span> type)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.resourceType
== type;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The only difference from the TypedXmlMediaTypeFormatter class is that this one derives
from JsonMediaTypeFormatter instead of XmlMediaTypeFormatter.
</p>
        <p>
With these two classes available, I can now register all the custom media types in
Global.asax like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedXmlMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Album</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.album+xml"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedXmlMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Artist</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.artist+xml"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedXmlMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Catalog</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.catalog+xml"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedXmlMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">SearchResult</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.search-result+xml"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedXmlMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Track</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.track+xml"</span>)));</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedJsonMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Album</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.album+json"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedJsonMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Artist</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.artist+json"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedJsonMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Catalog</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.catalog+json"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedJsonMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">SearchResult</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.search-result+json"</span>)));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.Add(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">TypedJsonMediaTypeFormatter</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">typeof</span>(<span style="color: #2b91af">Track</span>),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"application/vnd.247e.track+json"</span>)));</pre>
        </div>
        <p>
This is rather repetitive code, but I'll leave it as an exercise to the reader to
write a set of conventions that appropriately register the correct media type for
a Model class.
</p>
        <p>
          <strong>Caveats</strong>
        </p>
        <p>
Please be aware that I've only tested this with a read-only API. You may need to tweak
this solution in order to also handle incoming data.
</p>
        <p>
As far as I can tell from the <a href="http://aspnetwebstack.codeplex.com/SourceControl/list/changesets">Web
API source repository</a>, it seems as though there are some breaking changes in the
pipeline in this area, so don't bet the farm on this particular solution.
</p>
        <p>
Lastly, it seems as though this solution doesn't correctly respect opt-out quality
parameters in incoming Accept headers. As an example, if I request a 'Catalog' resource,
but supply the following Accept header, I'd expect the response to be 406 (Not Acceptable).
</p>
        <p>
Accept: application/vnd.247e.search-result+xml; q=1, */*; q=0.0
</p>
        <p>
However, the result is that the service falls back to its default representation,
which is application/json. Whether this is a problem with my approach or a bug in
the Web API, I haven't investigated.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=29754191-c40d-474a-b063-d00b1154638b" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Wiring HttpControllerContext With Castle Windsor</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/04/19/WiringHttpControllerContextWithCastleWindsor.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,1c390f17-cd8a-40bc-8d9c-bad20c6f9880.aspx</id>
    <published>2012-04-19T17:14:30.726554+02:00</published>
    <updated>2012-04-19T17:14:30.726554+02:00</updated>
    <category term="ASP.NET MVC" label="ASP.NET MVC" scheme="http://blog.ploeh.dk/CategoryView,category,ASPNETMVC.aspx" />
    <category term="Castle Windsor" label="Castle Windsor" scheme="http://blog.ploeh.dk/CategoryView,category,CastleWindsor.aspx" />
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Services" label="Services" scheme="http://blog.ploeh.dk/CategoryView,category,Services.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a previous post I demonstrated <a href="http://blog.ploeh.dk/2012/04/17/InjectingHttpControllerContextWithTheASPNETWebAPI.aspx">how
to wire up HttpControllerContext with Poor Man's DI</a>. In this article I'll show
how to wire up HttpControllerContext with Castle Windsor.
</p>
        <p>
This turns out to be remarkably difficult, at least with the constraints I tend to
set for myself:
</p>
        <ul>
          <li>
Readers of this blog may have an inkling that I have an absolute abhorrence of static
state, so anything relying on that is out of the question. 
</li>
          <li>
In addition to that, I also prefer to leverage the container as much as possible,
so I'm not keen on duplicating a responsibility that really belongs to the container. 
</li>
          <li>
No injecting the container into itself. That's just unnatural and lewd (without being
fun). 
</li>
          <li>
If possible, the solution should be thread-safe. 
</li>
          <li>
The overall solution should still adhere to the <a href="http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx">Register
Resolve Release pattern</a>, so registering a captured HttpControllerContext is a
no-go. It's also unlikely to work, since you'd need to somehow scope each registered
instance to its source request. 
</li>
          <li>
That also rules out nested containers.</li>
        </ul>
        <p>
OK, so given these constraints, how can an object graph like this one be created,
only with Castle Windsor instead of Poor Man's DI?
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">return</span>
            <span style="color: blue">new</span>
            <span style="color: #2b91af">CatalogController</span>(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">RouteLinker</span>(</pre>
          <pre style="margin: 0px">        baseUri,</pre>
          <pre style="margin: 0px">        controllerContext));</pre>
        </div>
        <p>
Somehow, the HttpControllerContext instance must be captured and made available for
further resolution of a CatalogController instance.
</p>
        <p>
          <strong>Capturing the HttpControllerContext</strong>
        </p>
        <p>
The first step is to capture the HttpControllerContext instance, as early as possible.
From my previous post it should be reasonably clear that the best place to capture
this instance is from within IHttpControllerActivator.Create.
</p>
        <p>
Here's the requirement: the HttpControllerContext instance must be captured and made
available for further resolution of the object graph – preferably in a thread-safe
manner. Ideally, it should be captured in a thread-safe object that can start out
uninitialized, but then allow exactly one assignment of a value.
</p>
        <p>
At the time I first struggled with this, I was just finishing <a href="http://www.amazon.com/gp/product/1935182641/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1935182641">The
Joy of Clojure</a>, so this sounded to me an awful lot like the description of a <a href="http://clojuredocs.org/clojure_core/clojure.core/promise">promise</a>.
Crowdsourcing on Twitter turned up that the .NET equivalent of a promise is <a href="http://msdn.microsoft.com/en-us/library/dd449174.aspx">TaskCompletionSource&lt;T&gt;</a>.
</p>
        <p>
Creating a custom IHttpControllerActivator with an injected TaskCompletionSource&lt;HttpControllerContext&gt;
sounds like a good approach. If the custom IHttpControllerActivator can be scoped
to a specific request, that would be the solution then and there.
</p>
        <p>
However, as I've <a href="http://blog.ploeh.dk/2012/03/20/RobustDIWithTheASPNETWebAPI.aspx">previously
described</a>, the current incarnation of the ASP.NET Web API has the unfortunate
behavior that all framework Services (such as IHttpControllerActivator) are resolved
once and cached forever (effectively turning them into having the Singleton lifestyle,
despite what you may attempt to configure in your container).
</p>
        <blockquote>
          <p>
With Dependency Injection, the common solution to bridge the gap between a long-lasting
lifestyle and a shorter lifestyle is a factory.
</p>
        </blockquote>
        <p>
Thus, instead of injecting TaskCompletionSource&lt;HttpControllerContext&gt; into
a custom IHttpControllerActivator, a Func&lt;TaskCompletionSource&lt;HttpControllerContext&gt;&gt;
can be injected to bridge the lifestyle gap.
</p>
        <p>
One other thing: the custom IHttpControllerActivator is only required to capture the
HttpControllerContext for further reference, so I don't want to reimplement all the
functionality of DefaultHttpControllerActivator. This is the reason why the custom
IHttpControllerActivator ends up being a <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ContextCapturingControllerActivator</span> :</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IHttpControllerActivator</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IHttpControllerActivator</span> activator;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">TaskCompletionSource</span>&lt;<span style="color: #2b91af">HttpControllerContext</span>&gt;&gt;</pre>
          <pre style="margin: 0px">        promiseFactory;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> ContextCapturingControllerActivator(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">TaskCompletionSource</span>&lt;<span style="color: #2b91af">HttpControllerContext</span>&gt;&gt;
promiseFactory,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">IHttpControllerActivator</span> activator)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.activator
= activator;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.promiseFactory
= promiseFactory;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">IHttpController</span> Create(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">HttpControllerContext</span> controllerContext,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Type</span> controllerType)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.promiseFactory().SetResult(controllerContext);</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.activator.Create(controllerContext,
controllerType);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The ContextCapturingControllerActivator class simply Decorates another IHttpControllerActivator
and does <em>one</em> thing before delegating the call to the inner implementation:
it uses the factory to create a new instance of TaskCompletionSource&lt;HttpControllerContext&gt;
and assigns the HttpControllerContext instance to that <em>promise</em>.
</p>
        <p>
          <strong>Scoping</strong>
        </p>
        <p>
Because the Web API is basically being an ass (I can write this here, because I'm
gambling that the solitary reader making it this far is so desperate that he or she
is not going to care about the swearing) by treating framework Services as Singletons,
it doesn't matter how it's being registered:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">    .For&lt;<span style="color: #2b91af">IHttpControllerActivator</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">ContextCapturingControllerActivator</span>&gt;());</pre>
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">    .For&lt;<span style="color: #2b91af">IHttpControllerActivator</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">DefaultHttpControllerActivator</span>&gt;());</pre>
        </div>
        <p>
Notice that because Castle Windsor is being such an awesome library that it implicitly
understands the Decorator pattern, I can simple register both Decorator and Decoratee
in an ordered sequence.
</p>
        <p>
The factory itself must also be registered as a Singleton (the default in Castle Windsor):
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">    .For&lt;<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">TaskCompletionSource</span>&lt;<span style="color: #2b91af">HttpControllerContext</span>&gt;&gt;&gt;()</pre>
          <pre style="margin: 0px">    .AsFactory());</pre>
        </div>
        <p>
Here, I'm taking advantage of Castle Windsor's <a href="http://stw.castleproject.org/Windsor.Typed-Factory-Facility.ashx">Typed
Factory Facility</a>, so I'm simply asking it to treat a Func&lt;TaskCompletionSource&lt;HttpControllerContext&gt;&gt;
as an <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract Factory</a>.
Doing that means that every time the delegate is being invoked, Castle Windsor will
create an instance of TaskCompletionSource&lt;HttpControllerContext&gt; with the correct
lifetime.
</p>
        <p>
This provides the bridge from Singleton lifestyle to PerWebRequest:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">    .For&lt;<span style="color: #2b91af">TaskCompletionSource</span>&lt;<span style="color: #2b91af">HttpControllerContext</span>&gt;&gt;()</pre>
          <pre style="margin: 0px">    .LifestylePerWebRequest());</pre>
        </div>
        <p>
Notice that TaskCompletionSource&lt;HttpControllerContext&gt; is registered with a
PerWebRequest lifestyle, which means that every time the above delegate is invoked,
it's going to create an instance which is scoped to the current request. This is exactly
the desired behavior.
</p>
        <p>
          <strong>Registering HttpControllerContext</strong>
        </p>
        <p>
The only thing left is registering the HttpControllerContext class itself:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">    .For&lt;<span style="color: #2b91af">HttpControllerContext</span>&gt;()</pre>
          <pre style="margin: 0px">    .UsingFactoryMethod(k =&gt; </pre>
          <pre style="margin: 0px">        k.Resolve&lt;<span style="color: #2b91af">TaskCompletionSource</span>&lt;<span style="color: #2b91af">HttpControllerContext</span>&gt;&gt;()</pre>
          <pre style="margin: 0px">            .Task.Result)</pre>
          <pre style="margin: 0px">    .LifestylePerWebRequest());</pre>
        </div>
        <p>
This defines that HttpControllerContext instances are going to be resolved the following
way: each time an HttpControllerContext instance is requested, the container is going
to look up a TaskCompletionSource&lt;HttpControllerContext&gt; and return the result
from that task.
</p>
        <p>
The TaskCompletionSource&lt;HttpControllerContext&gt; instance is scoped per web request
and previously captured (as you may recall) by the ContextCapturingControllerActivator
class.
</p>
        <p>
That's all (sic!) there's to it :)
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1c390f17-cd8a-40bc-8d9c-bad20c6f9880" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Injecting HttpControllerContext With the ASP.NET Web API</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/04/17/InjectingHttpControllerContextWithTheASPNETWebAPI.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,3015e1f5-8e49-4b0e-84a5-4ccd570a868a.aspx</id>
    <published>2012-04-17T17:17:05.7939792+02:00</published>
    <updated>2012-04-17T17:17:05.7939792+02:00</updated>
    <category term="ASP.NET MVC" label="ASP.NET MVC" scheme="http://blog.ploeh.dk/CategoryView,category,ASPNETMVC.aspx" />
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Services" label="Services" scheme="http://blog.ploeh.dk/CategoryView,category,Services.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
The <a href="http://www.asp.net/web-api">ASP.NET Web API</a> (beta) defines a class
called HttpControllerContext. As the name implies, it provides a context for a Controller.
This article describes how to inject an instance of this class into a Service.
</p>
        <p>
          <strong>The Problem</strong>
        </p>
        <p>
A Service may need an instance of the HttpControllerContext class. For an example,
see the <a href="http://blog.ploeh.dk/2012/04/17/HyperlinkingWithTheASPNETWebAPI.aspx">RouteLinker
class in my previous post</a>. A Controller, on the other hand, may depend on such
a Service:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> CatalogController(<span style="color: #2b91af">IResourceLinker</span> resourceLinker)</pre>
        </div>
        <p>
How can a CatalogController instance be wired up with an instance of RouteLinker,
which again requires an instance of HttpControllerContext? In contrast to the existing
ASP.NET MVC API, there's no easy way to read the current context. There's no HttpControllerContext.Current
method or any other easy way (that I have found) to refer to an HttpControllerContext
as part of the <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">Composition
Root</a>.
</p>
        <p>
True: it's easily available as a property on a Controller, but at the time of composition,
there's no Controller instance (yet). A Controller instance is exactly what the Composition
Root is attempting to create. This sounds like a circular reference problem. Fortunately,
it's not.
</p>
        <p>
          <strong>The Solution</strong>
        </p>
        <p>
For Poor Man's DI, the solution is relatively simple. As <a href="http://blog.ploeh.dk/2012/03/20/RobustDIWithTheASPNETWebAPI.aspx">I've
previously described</a>, by default the responsibility of creating Controller instances
is handled by an instance of IHttpControllerActivator. This is, essentially, the Composition
Root (at least for all Controllers).
</p>
        <p>
The Create method of that interface takes exactly the HttpControllerContext required
by RouteLinker – or, put differently: the framework will supply an instance every
time it invokes the Create method. Thus, a custom IHttpControllerActivator solves
the problem:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">PoorMansCompositionRoot</span> : <span style="color: #2b91af">IHttpControllerActivator</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">IHttpController</span> Create(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">HttpControllerContext</span> controllerContext,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Type</span> controllerType)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (controllerType
== <span style="color: blue">typeof</span>(<span style="color: #2b91af">CatalogController</span>))</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">var</span> url
= <span style="color: #2b91af">HttpContext</span>.Current.Request.Url;</pre>
          <pre style="margin: 0px">            <span style="color: blue">var</span> baseUri
=</pre>
          <pre style="margin: 0px">                <span style="color: blue">new</span><span style="color: #2b91af">UriBuilder</span>(</pre>
          <pre style="margin: 0px">                    url.Scheme,</pre>
          <pre style="margin: 0px">                    url.Host,</pre>
          <pre style="margin: 0px">                    url.Port).Uri;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">            <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">CatalogController</span>(</pre>
          <pre style="margin: 0px">                <span style="color: blue">new</span><span style="color: #2b91af">RouteLinker</span>(</pre>
          <pre style="margin: 0px">                    baseUri,</pre>
          <pre style="margin: 0px">                    controllerContext));</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: green">//
Handle other types here...</span></pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The <em>controllerContext</em> parameter is simply passed on to the RouteLinker constructor.
</p>
        <p>
The only thing left is to register the PoorMansCompositionRoot with the ASP.NET Web
API. This can be done in Global.asax by using the GlobalConfiguration.Configuration.ServiceResolver.SetResolver
method, as described in <a href="http://blog.ploeh.dk/2012/03/20/RobustDIWithTheASPNETWebAPI.aspx">my
previous post</a>. Just resolve IHttpControllerActivator to an instance of PoorMansCompositionRoot.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3015e1f5-8e49-4b0e-84a5-4ccd570a868a" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Hyperlinking With the ASP.NET Web API</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/04/17/HyperlinkingWithTheASPNETWebAPI.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,c49a556c-9fe7-42b7-8b18-2bf7508239b6.aspx</id>
    <published>2012-04-17T16:46:42.458211+02:00</published>
    <updated>2012-04-17T16:46:42.458211+02:00</updated>
    <category term="ASP.NET MVC" label="ASP.NET MVC" scheme="http://blog.ploeh.dk/CategoryView,category,ASPNETMVC.aspx" />
    <category term="REST" label="REST" scheme="http://blog.ploeh.dk/CategoryView,category,REST.aspx" />
    <category term="Services" label="Services" scheme="http://blog.ploeh.dk/CategoryView,category,Services.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
When creating resources with the <a href="http://www.asp.net/web-api">ASP.NET Web
API</a> (beta) it's important to be able to create correct hyperlinks (you know, <a href="http://martinfowler.com/articles/richardsonMaturityModel.html">if
it doesn't have hyperlinks, it's not REST</a>). These hyperlinks may link to other
resources in the same API, so it's important to keep the links consistent. A client
following such a link should hit the desired resource.
</p>
        <p>
This post describes an refactoring-safe approach to creating hyperlinks using the
Web API RouteCollection and Expressions.
</p>
        <p>
          <strong>The Problem</strong>
        </p>
        <p>
Obviously hyperlinks can be hard-coded, but since incoming requests are matched based
on the Web API's RouteCollection, there's a risk that hard-coded links become disconnected
from the API's incoming routes. In other words, hard-coding links is probably not
a good idea.
</p>
        <p>
For reference, the default route in the Web API looks like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">routes.MapHttpRoute(</pre>
          <pre style="margin: 0px">    name: <span style="color: #a31515">"DefaultApi"</span>,</pre>
          <pre style="margin: 0px">    routeTemplate: <span style="color: #a31515">"{controller}/{id}"</span>,</pre>
          <pre style="margin: 0px">    defaults: <span style="color: blue">new</span></pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        controller = <span style="color: #a31515">"Catalog"</span>,</pre>
          <pre style="margin: 0px">        id = <span style="color: #2b91af">RouteParameter</span>.Optional</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">);</pre>
        </div>
        <p>
A sample action fitting that route might look like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">Artist</span> Get(<span style="color: blue">string</span> id)</pre>
        </div>
        <p>
where the Get method is defined by the ArtistController class.
</p>
        <p>
          <strong>Desired Outcome</strong>
        </p>
        <p>
In order to provide a refactoring-safe way to create links to e.g. the artist resource,
the <a href="http://joseoncode.com/2011/03/18/wcf-web-api-strongly-typed-resource-linker/">strongly
typed Resource Linker</a> approach outlined by <a href="http://joseoncode.com/">José
F. Romaniello</a> can be adopted. The IResourceLinker interface looks like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IResourceLinker</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Uri</span> GetUri&lt;T&gt;(<span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Action</span>&lt;T&gt;&gt;
method);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This makes it possible to create links like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> artist
= <span style="color: blue">new</span><span style="color: #2b91af">Artist</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    Name = artistName,</pre>
          <pre style="margin: 0px">    Links = <span style="color: blue">new</span>[]</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">Link</span></pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            Href = <span style="color: blue">this</span>.resourceLinker.GetUri&lt;<span style="color: #2b91af">ArtistController</span>&gt;(r
=&gt;</pre>
          <pre style="margin: 0px">                r.Get(artistsId)).ToString(),</pre>
          <pre style="margin: 0px">            Rel = <span style="color: #a31515">"self"</span></pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    },</pre>
          <pre style="margin: 0px">    <span style="color: green">//
More crap goes here...</span></pre>
          <pre style="margin: 0px">};</pre>
        </div>
        <p>
In this example, the <em>resourceLinker</em> field is an injected instance of IResourceLinker.
</p>
        <p>
Since the input to the GetUri method is an Expression, it's being checked at compile
time. It's refactoring-safe because a refactoring tool will be able to e.g. change
the name of the method call in the Expression if the name of the method changes.
</p>
        <p>
          <strong>Example Implementation</strong>
        </p>
        <p>
It's possible to implement IResourceLinker over a Web API RouteCollection. Here's
an example implementation:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">RouteLinker</span> : <span style="color: #2b91af">IResourceLinker</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: #2b91af">Uri</span> baseUri;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">HttpControllerContext</span> ctx;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> RouteLinker(<span style="color: #2b91af">Uri</span> baseUri, <span style="color: #2b91af">HttpControllerContext</span> ctx)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.baseUri
= baseUri;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.ctx
= ctx;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">Uri</span> GetUri&lt;T&gt;(<span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Action</span>&lt;T&gt;&gt;
method)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (method
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"method"</span>);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> methodCallExp
= method.Body <span style="color: blue">as</span><span style="color: #2b91af">MethodCallExpression</span>;</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (methodCallExp
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentException</span>(<span style="color: #a31515">"The
expression's body must be a MethodCallExpression. The code block supplied should invoke
a method.\nExample: x =&gt; x.Foo()."</span>, <span style="color: #a31515">"method"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> routeValues
= methodCallExp.Method.GetParameters()</pre>
          <pre style="margin: 0px">            .ToDictionary(p =&gt; p.Name, p =&gt; GetValue(methodCallExp, p));</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> controllerName
= methodCallExp.Method.ReflectedType.Name</pre>
          <pre style="margin: 0px">            .ToLowerInvariant().Replace(<span style="color: #a31515">"controller"</span>, <span style="color: #a31515">""</span>);</pre>
          <pre style="margin: 0px">        routeValues.Add(<span style="color: #a31515">"controller"</span>,
controllerName);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> relativeUri
= <span style="color: blue">this</span>.ctx.Url.Route(<span style="color: #a31515">"DefaultApi"</span>,
routeValues);</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">Uri</span>(<span style="color: blue">this</span>.baseUri,
relativeUri);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">static</span><span style="color: blue">object</span> GetValue(<span style="color: #2b91af">MethodCallExpression</span> methodCallExp,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ParameterInfo</span> p)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> arg
= methodCallExp.Arguments[p.Position];</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> lambda
= <span style="color: #2b91af">Expression</span>.Lambda(arg);</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> lambda.Compile().DynamicInvoke().ToString();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This isn't much different from José F. Romaniello's example, apart from the fact that
it creates a dictionary of route values and then uses the UrlHelper.Route method to
create a relative URI.
</p>
        <p>
Please not that this is just an example implementation. For instance, the call to
the Route method supplies the hard-coded string "DefaultApi" to indicate which route
(from Global.asax) to use. I'll leave it as an exercise for the interested reader
to provide a generalization of this implementation.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=c49a556c-9fe7-42b7-8b18-2bf7508239b6" />
      </div>
    </content>
  </entry>
  <entry>
    <title>IQueryable&lt;T&gt; is Tight Coupling</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/03/26/IQueryableIsTightCoupling.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,19280084-d49f-4e7b-a938-f0203db31d9d.aspx</id>
    <published>2012-03-26T15:53:31.0811059+02:00</published>
    <updated>2012-03-26T15:53:31.0811059+02:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
From time to time I encounter people who attempt to express an API in terms of <a href="http://msdn.microsoft.com/en-us/library/bb351562.aspx">IQueryable&lt;T&gt;</a>.
That's almost always a bad idea. In this post, I'll explain why.
</p>
        <p>
In short, the IQueryable&lt;T&gt; interface is one of the best examples of a <a href="http://martinfowler.com/bliki/HeaderInterface.html">Header
Interface</a> that .NET has to offer. It's almost impossible to fully implement it.
</p>
        <blockquote>
          <p>
Please note that this post is about the problematic aspects of designing an API around
the IQueryable&lt;T&gt; interface. It's not an attack on the interface itself, which
has its place in the BCL. It's also not an attack on all the wonderful LINQ methods
available on <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx">IEnumerable&lt;T&gt;</a>.
</p>
        </blockquote>
        <p>
You can say that IQueryable&lt;T&gt; is one big <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov
Substitution Principle</a> (LSP)violation just waiting to happen. In the next two
section, I will apply <a href="http://en.wikipedia.org/wiki/Postel%27s_law">Postel's
law</a> to explain why that is.
</p>
        <p>
          <strong>Consuming IQueryable&lt;T&gt;</strong>
        </p>
        <p>
The first part of Postel's law applied to API design states that an API should be <em>liberal
in what it accepts</em>. In other words, we are talking about input, so an API that
consumes IQueryable&lt;T&gt; would take this generalized shape:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">IFoo</span> SomeMethod(<span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Bar</span>&gt;
q);</pre>
        </div>
        <p>
Is that a <em>liberal</em> requirement? It must certainly is not. Such an interface <em>demands</em> of
any caller that they must be able to supply an implementation of IQueryable&lt;Bar&gt;.
According to the LSP we must be able to supply <em>any</em> implementation without
changing the correctness of the program. That goes for both the implementer of IQueryable&lt;Bar&gt;
as well as the implementation of SomeMethod.
</p>
        <p>
At this point it's important to keep in mind the <em>purpose</em> of IQueryable&lt;T&gt;:
it's <a href="http://msdn.microsoft.com/en-us/library/bb351562.aspx">intended for
implementation by query providers</a>. In other words, this isn't just some sequence
of Bar instances which can be filtered and projected; no, this is a query <em>expression</em> which
is intended to be <em>translated</em> into a query somewhere else – most often some
dialect of SQL.
</p>
        <p>
That's quite a demand to put on the caller.
</p>
        <p>
It's certainly a powerful interface (or so it would seem), but is it really necessary?
Does SomeMethod really need to be able to perform <em>arbitrarily complex</em> queries
against a data source?
</p>
        <p>
In one recent discussion, it turns out that all the developer really wanted to do
was to be able to <a href="https://github.com/ploeh/cqrs-journey-code/commit/7b912136b470b75f418eadae605669c3489f53f9">select
based on a handful of simple criteria</a>. In another case, the developer only wanted
to do simple paging.
</p>
        <p>
Such requirements could be modeled much simpler without making huge demands on the
caller. In both cases, we could provide specialized <a href="http://martinfowler.com/eaaCatalog/queryObject.html">Query
Objects</a> instead, or perhaps even simpler just a set of specialized queries:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">IFoo</span> FindById(<span style="color: blue">int</span> fooId);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">IFoo</span> FindByCorrelationId(<span style="color: blue">int</span> correlationId);</pre>
        </div>
        <p>
Or, in the case of paging:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">IFoo</span>&gt;
GetFoos(<span style="color: blue">int</span> page);</pre>
        </div>
        <p>
This is certainly much more <em>liberal</em> in that it requires the caller to supply
only the required information in order to implement the methods. Designing APIs in
terms of <a href="http://martinfowler.com/bliki/RoleInterface.html">Role Interfaces</a> instead
of Header Interfaces makes the APIs much more flexible. This will enable you to respond
to change.
</p>
        <p>
          <strong>Exposing IQueryable&lt;T&gt;</strong>
        </p>
        <p>
The other part of Postel's law states that an API should be <em>conservative in what
it sends</em>. In other words, a method must guarantee that the data it returns conforms
rigorously to the contract between caller and implementer.
</p>
        <p>
A method returning IQueryable&lt;T&gt; would take this generalized shape:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Bar</span>&gt;
GetBars();</pre>
        </div>
        <p>
When designing APIs, a huge part of the contract is defined by the interface (or base
class). Thus, the return type of a method specifies a conservative guarantee about
the returned data. In the case of returning IQueryable&lt;Bar&gt; the method thus <em>guarantees</em> that
it will return a complete implementation of IQueryable&lt;Bar&gt;.
</p>
        <p>
Is that conservative?
</p>
        <p>
Once again invoking the LSP, a consumer must be able to do <em>anything</em> allowed
by IQueryable&lt;Bar&gt; without changing the correctness of the program.
</p>
        <p>
That's a big honking promise to make.
</p>
        <p>
Who can keep that promise?
</p>
        <p>
          <strong>Current Implementations</strong>
        </p>
        <p>
Implementing IQueryable&lt;T&gt; is a huge undertaking. If you don't believe me, just
take a look at the official <a href="http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx">Building
an IQueryable provider</a> series of blog posts. Even so, the interface is so flexible
and expressive that with a single exception, it's always possible to write a query
that a given provider can't translate.
</p>
        <p>
Have you ever worked with LINQ to Entities or another ORM and received a NotSupportedException? <a href="https://www.google.dk/search?q=linq+notsupportedexception">Lots
of people have</a>. In fact, with a single exception, it's my firm belief that all
existing implementations violate the LSP (in fact, I challenge my readers to refer
me to a real, publicly available implementation of IQueryable&lt;T&gt; that can accept <em>any</em> expression
I throw at it, and I'll ship a free copy of <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my
book</a> to the first reader to do so).
</p>
        <p>
Furthermore, the subset of features that each implementation supports varies from
query provider to query provider. An expression that can be translated by the Entity
framework may not work with Microsoft's OData query provider.
</p>
        <p>
The only implementation that fully implements IQueryable&lt;T&gt; is the <a href="http://msdn.microsoft.com/en-us/library/cc190116.aspx">in-memory
implementation</a> (and referring to this one does not earn you a free book). Ironically,
this implementation can be considered a <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null
Object</a> implementation and goes against the whole purpose of the IQueryable&lt;T&gt;
interface exactly because it <em>doesn't</em> translate the expression to another
language.
</p>
        <p>
          <strong>Why This Matters</strong>
        </p>
        <p>
You may think this is all a theoretical exercise, but it actually does matter. When
writing <a href="http://www.amazon.com/gp/product/0132350882/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0132350882">Clean
Code</a>, it's important to design an API in such a way that it's clear what it does.
</p>
        <p>
An interface like this makes false guarantees:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IRepository</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IQueryable</span>&lt;T&gt;
Query&lt;T&gt;();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
According to the LSP and Postel's law, it would seem to guarantee that you can write <em>any</em> query
expression (no matter how complex) against the returned instance, and it would always
work.
</p>
        <p>
In practice, this is never going to happen.
</p>
        <p>
Programmers who define such interfaces invariably have a specific ORM in mind, and
they implicitly tend to stay within the bounds they know are safe for that specific
ORM. This is a leaky abstraction.
</p>
        <p>
If you have a specific ORM in mind, then be explicit about it. Don't hide it behind
an interface. It creates the illusion that you can replace one implementation with
another. In practice, that's impossible. Imagine attempting to provide an implementation
over an Event Store.
</p>
        <p>
The cake is a lie.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=19280084-d49f-4e7b-a938-f0203db31d9d" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Robust DI With the ASP.NET Web API</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/03/20/RobustDIWithTheASPNETWebAPI.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,073ad508-e007-4b4d-bdff-eb4999e0470d.aspx</id>
    <published>2012-03-20T17:02:51.2906009+01:00</published>
    <updated>2012-03-21T08:13:08.9731776+01:00</updated>
    <category term="ASP.NET MVC" label="ASP.NET MVC" scheme="http://blog.ploeh.dk/CategoryView,category,ASPNETMVC.aspx" />
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="REST" label="REST" scheme="http://blog.ploeh.dk/CategoryView,category,REST.aspx" />
    <category term="Services" label="Services" scheme="http://blog.ploeh.dk/CategoryView,category,Services.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Like the WCF Web API, the new <a href="http://www.asp.net/web-api">ASP.NET Web API</a> supports
Dependency Injection (DI), but the approach is different and the resulting code you'll
have to write is likely to be more complex. This post describes how to enable robust
DI with the new Web API. Since this is based on the beta release, I hope that it will
become easier in the final release.
</p>
        <p>
At first glance, enabling DI on an ASP.NET Web API <a href="http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver">looks
seductively simple</a>. As always, though, the devil is in the details. <a href="http://www.nikosbaxevanis.com/bonus-bits/">Nikos
Baxevanis</a> has already provided a <a href="http://www.nikosbaxevanis.com/bonus-bits/2012/03/using-the-web-api-dependency-resolver-with-castle-windsor.html">more
thorough description</a>, but it's even more tricky than that.
</p>
        <p>
          <strong>Protocol</strong>
        </p>
        <p>
To enable DI, all you have to do is to call the SetResolver method, right? It even
has an overload that enables you to supply two code blocks instead of implementing
an interface (although you can certainly also implement IDependencyResolver). Could
it be any easier than that?
</p>
        <p>
Yes, it most certainly could.
</p>
        <p>
Imagine that you'd like to hook up your DI Container of choice. As a first attempt,
you try something like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.ServiceResolver.SetResolver(</pre>
          <pre style="margin: 0px">    t =&gt; <span style="color: blue">this</span>.container.Resolve(t),</pre>
          <pre style="margin: 0px">    t =&gt; <span style="color: blue">this</span>.container.ResolveAll(t).Cast&lt;<span style="color: blue">object</span>&gt;());</pre>
        </div>
        <p>
This compiles. Does it work? Yes, but in a rather scary manner. Although it satisfies
the interface, it doesn't satisfy the <em>protocol</em> ("an interface describes whether
two components will <em>fit</em> together, while a protocol describes whether they
will <em>work</em> together." (<a href="http://www.amazon.com/gp/product/0321503627/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321503627">GOOS</a>,
p. 58)).
</p>
        <p>
The protocol, in this case, is that if you (or rather the container) can't resolve
the type, you should return null. What's even worse is that <em>if</em> your code
throws an exception (<em>any</em> exception, apparently), DependencyResolver will
suppress it. In case you didn't know, this is strongly frowned upon in the <a href="http://msdn.microsoft.com/en-us/library/ms229005.aspx">.NET
Framework Design Guidelines</a>.
</p>
        <p>
Even so, the official introduction article instead chooses to play along with the
protocol and explicitly handle any exceptions. Something along the lines of this ugly
code:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.ServiceResolver.SetResolver(</pre>
          <pre style="margin: 0px">    t =&gt;</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">try</span></pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">return</span><span style="color: blue">this</span>.container.Resolve(t);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">catch</span> (<span style="color: #2b91af">ComponentNotFoundException</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">return</span><span style="color: blue">null</span>;</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    },</pre>
          <pre style="margin: 0px">    t =&gt;</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">try</span></pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">return</span><span style="color: blue">this</span>.container.ResolveAll(t).Cast&lt;<span style="color: blue">object</span>&gt;();</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">catch</span> (<span style="color: #2b91af">ComponentNotFoundException</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">List</span>&lt;<span style="color: blue">object</span>&gt;();</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">);</pre>
        </div>
        <p>
Notice how try/catch is used for control flow – another <a href="http://msdn.microsoft.com/en-us/library/ms229030.aspx">major
no no in the .NET Framework Design Guidelines</a>.
</p>
        <p>
At least with a good DI Container, we can do something like this instead:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.ServiceResolver.SetResolver(</pre>
          <pre style="margin: 0px">    t =&gt; <span style="color: blue">this</span>.container.Kernel.HasComponent(t)
?</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.container.Resolve(t)
:</pre>
          <pre style="margin: 0px">        <span style="color: blue">null</span>,</pre>
          <pre style="margin: 0px">    t =&gt; <span style="color: blue">this</span>.container.ResolveAll(t).Cast&lt;<span style="color: blue">object</span>&gt;());</pre>
        </div>
        <p>
Still, first impressions don't exactly inspire trust in the implementation...
</p>
        <p>
          <strong>API Design Issues</strong>
        </p>
        <p>
Next, I would like to direct your attention to the DependencyResolver API. At its
core, it looks like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IDependencyResolver</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">object</span> GetService(<span style="color: #2b91af">Type</span> serviceType);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">object</span>&gt;
GetServices(<span style="color: #2b91af">Type</span> serviceType);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
It can create objects, but what about decommissioning? What if, deep in a dependency
graph, a Controller contains an IDisposable object? This is not a particularly exotic
scenario – it might be an instance of an Entity Framework <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx">ObjectContext</a>.
While an ApiController itself implements IDisposable, it may not know that it contains
an injected object graph with one or more IDisposable leaf nodes.
</p>
        <blockquote>
          <p>
It's a fundamental rule of DI that you must <a href="http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx">Release
what you Resolve</a>. That's not possible with the DependencyResolver API. The result
may be memory leaks.
</p>
        </blockquote>
        <p>
Fortunately, it turns out that there's a fix for this (at least for Controllers).
Unfortunately, this workaround leverages another design problem with DependencyResolver.
</p>
        <p>
          <strong>Mixed Responsibilities</strong>
        </p>
        <p>
It turns out that when you wire a custom resolver up with the SetResolver method,
the ASP.NET Web API will query your custom resolver (such as a DI Container) for not
only your application classes, but also for its own infrastructure components. That
surprised me a bit because of the mixed responsibility, but at least this is a useful
hook.
</p>
        <p>
One of the first types the framework will ask for is an instance of IHttpControllerFactory,
which looks like this:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IHttpControllerFactory</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    IHttpController CreateController(HttpControllerContext controllerContext,</pre>
          <pre style="margin: 0px">        <span style="color: blue">string</span> controllerName);</pre>
          <pre style="margin: 0px">    <span style="color: blue">void</span> ReleaseController(IHttpController
controller);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Fortunately, this interface has a Release hook, so at least it's possible to release
Controller instances, which is most important because there will be a lot of them
(one per HTTP request).
</p>
        <p>
          <strong>Discoverability Issues</strong>
        </p>
        <p>
The IHttpControllerFactory looks a lot like the well-known ASP.NET MVC <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.icontrollerfactory%28v=vs.98%29.aspx">IControllerFactory</a> interface,
but there are subtle differences. In ASP.NET MVC, there's a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultcontrollerfactory%28v=vs.98%29.aspx">DefaultControllerFactory</a> with
appropriate virtual methods one can overwrite (it follows the <a href="http://en.wikipedia.org/wiki/Template_method_pattern">Template
Method</a> pattern).
</p>
        <p>
There's also a DefaultControllerFactory in the Web API, but unfortunately no Template
Methods to override. While I <em>could</em> write an algorithm that maps from the <em>controllerName</em> parameter
to a type which can be passed to a DI Container, I'd rather prefer to be able to reuse
the implementation which the DefaultControllerFactory contains.
</p>
        <p>
In ASP.NET MVC, this is possible by overriding the <a href="http://msdn.microsoft.com/en-us/library/ee264052%28v=vs.98%29.aspx">GetControllerInstance</a> method,
but it turns out that the Web API (beta) does this slightly differently. It favors
composition over inheritance (which is actually a good thing, so kudos for that),
so after mapping <em>controllerName</em> to a Type instance, it invokes an instance
of the IHttpControllerActivator interface (did I hear anyone say "FactoryFactory?").
Very loosely coupled (good), but not very discoverable (not so good). It would have
been more discoverable if DefaultControllerFactory had used Constructor Injection
to get its dependency, rather than relying on the <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service
Locator</a> which DependencyResolver really is.
</p>
        <p>
However, this is only an issue if you need to hook into the Controller creation process,
e.g. in order to capture the HttpControllerContext for further use. In normal scenarios,
despite what Nikos Baxevanis describes in his blog post, you don't <em>have</em> to
override or implement IHttpControllerFactory.CreateController. The DependencyResolver
infrastructure will automatically invoke your GetService implementation (or the corresponding
code block) whenever a Controller instance is required.
</p>
        <p>
          <strong>Releasing Controllers</strong>
        </p>
        <p>
The easiest way to make sure that all Controller instances are being properly released
is to derive a class from DefaultControllerFactory and override the ReleaseController
method:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ReleasingControllerFactory</span> : <span style="color: #2b91af">DefaultHttpControllerFactory</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">Action</span>&lt;<span style="color: blue">object</span>&gt;
release;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> ReleasingControllerFactory(<span style="color: #2b91af">Action</span>&lt;<span style="color: blue">object</span>&gt;
releaseCallback,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">HttpConfiguration</span> configuration)</pre>
          <pre style="margin: 0px">        : <span style="color: blue">base</span>(configuration)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.release
= releaseCallback;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">override</span><span style="color: blue">void</span> ReleaseController(<span style="color: #2b91af">IHttpController</span> controller)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.release(controller);</pre>
          <pre style="margin: 0px">        <span style="color: blue">base</span>.ReleaseController(controller);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice that it's not necessary to override the CreateController method, since the
default implementation is good enough – it'll ask the DependencyResolver for an instance
of IHttpControllerActivator, which will again ask the DependencyResolver for an instance
of the Controller type, in the end invoking your custom GetObject implemention.
</p>
        <p>
To keep the above example generic, I just injected an Action&lt;object&gt; into ReleasingControllerFactory
– I really don't wish to turn this into a discussion about the merits and demerits
of various DI Containers. In any case, I'll leave it as an exercise to you to wire
up your favorite DI Container so that the <em>releaseCallback</em> is actually a call
to the container's Release method.
</p>
        <p>
          <strong>Lifetime Cycles of Infrastructure Components</strong>
        </p>
        <p>
Before I conclude, I'd like to point out another <a href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment">POLA</a> violation
that hit me during my investigation.
</p>
        <p>
The ASP.NET Web API utilizes DependencyResolver to resolve its own infrastructure
types (such as IHttpControllerFactory, IHttpControllerActivator, etc.). Any custom
DependencyResolver you supply will also be queried for these types. However:
</p>
        <blockquote>
          <p>
When resolving infrastructure components, the Web API doesn't respect any custom lifecycle
you may have defined for these components.
</p>
        </blockquote>
        <p>
At a certain point while I investigated this, I wanted to configure a custom IHttpControllerActivator
to have a <em>Web Request Context</em> (<a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my
book</a>, section 8.3.4) – in other words, I wanted to create a new instance of IHttpControllerActivator
for each incoming HTTP request.
</p>
        <p>
This is not possible. The framework queries a custom DependencyResolver for an infrastructure
type, but <em>even when it receives an instance</em> (i.e. not null), it doesn't trust
the DependencyResolver to efficiently manage the lifetime of that instance. Instead,
it caches this instance for ever, and never asks for it again. This is, in my opinion,
a mistaken responsibility, and I hope it will be corrected in the final release.
</p>
        <p>
          <strong>Concluding Thoughts</strong>
        </p>
        <p>
Wiring up the ASP.NET Web API with robust DI is possible, but much harder than it
ought to be. Suggestions for improvements are:
</p>
        <ul>
          <li>
A Release hook in DependencyResolver. 
</li>
          <li>
The framework itself should trust the DependencyResolver to efficiently manage lifetime
of all objects it create.</li>
        </ul>
        <p>
As I've described, there are other places were minor adjustments would be helpful,
but these two suggestions are the most important ones.
</p>
        <p>
          <strong>Update</strong> (2012.03.21): I've posted this feedback to the product group
on <a href="http://aspnet.uservoice.com/forums/147201-asp-net-web-api/suggestions/2701848-clean-up-dependency-injection-support">uservoice</a> and <a href="https://connect.microsoft.com/VisualStudio/feedback/details/732337/clean-up-dependency-injection-support-in-asp-net-web-api">Connect</a> –
if you agree, please visit those sites and vote up the issues.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=073ad508-e007-4b4d-bdff-eb4999e0470d" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Migrating from WCF Web API to ASP.NET Web API</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/03/19/MigratingFromWCFWebAPIToASPNETWebAPI.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,3fa91879-8089-4c25-a0a8-25d23d17404e.aspx</id>
    <published>2012-03-19T23:24:47.0835969+01:00</published>
    <updated>2012-03-19T23:24:47.0835969+01:00</updated>
    <category term="ASP.NET MVC" label="ASP.NET MVC" scheme="http://blog.ploeh.dk/CategoryView,category,ASPNETMVC.aspx" />
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="REST" label="REST" scheme="http://blog.ploeh.dk/CategoryView,category,REST.aspx" />
    <category term="Services" label="Services" scheme="http://blog.ploeh.dk/CategoryView,category,Services.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Now that <a href="http://wcf.codeplex.com/wikipage?title=WCF%20Web%20API%20is%20now%20ASP.NET%20Web%20API">the
WCF Web API has ‘become’ the ASP.NET Web API</a>, I’ve had to migrate a semi-complex
code base from the old to the new framework. These are my notes from that process.
</p>
        <p>
          <strong>Migrating Project References</strong>
        </p>
        <p>
As far as I can tell, the ASP.NET Web API isn’t just a port of the WCF Web API. At
a cursory glance, it looks like a complete reimplementation. If it’s a port of the
old code, it’s at least a rather radical one. The assemblies have completely different
names, and so on.
</p>
        <p>
Both old and new project, however, are based on NuGet packages, so it wasn’t particularly
hard to change.
</p>
        <p>
To remove the old project references, I ran this NuGet command:
</p>
        <p>
Uninstall-Package webapi.all –RemoveDependencies
</p>
        <p>
followed by
</p>
        <p>
Install-Package aspnetwebapi
</p>
        <p>
to install the project references for the ASP.NET Web API.
</p>
        <p>
          <strong>Rename Resources to Controllers</strong>
        </p>
        <p>
In the WCF Web API, there was no naming convention for the various resource classes.
In the quickstarts, they were sometimes called <em>Apis</em> (like ContactsApi), and
I called mine <em>Resources</em> (like CatalogResource). Whatever your naming convention
was, the easiest things is to find them all and rename them to end with <em>Controller</em> (e.g.
CatalogController).
</p>
        <p>
AFAICT you <em>can</em> change the naming convention, but I didn’t care enough to
do so.
</p>
        <p>
          <strong>Derive Controllers from ApiController</strong>
        </p>
        <p>
Unless you care to manually implement IHttpController, each Controller should derive
from ApiController:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">CatalogController</span> : <span style="color: #2b91af">ApiController</span></pre>
        </div>
        <p>
          <strong>Remove Attributes</strong>
        </p>
        <p>
The WCF Web API uses the [WebGet] and [WebInvoke] attributes. The ASP.NET Web API,
on the other hand, uses routes, so I removed all the attributes, including their UriTemplates:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: green">//[WebGet(UriTemplate
= "/")]</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">Catalog</span> GetRoot()</pre>
        </div>
        <p>
          <strong>Add Routes</strong>
        </p>
        <p>
As a replacement for attributes and UriTemplates, I added HTTP routes:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">routes.MapHttpRoute(</pre>
          <pre style="margin: 0px">    name: <span style="color: #a31515">"DefaultApi"</span>,</pre>
          <pre style="margin: 0px">    routeTemplate: <span style="color: #a31515">"{controller}/{id}"</span>,</pre>
          <pre style="margin: 0px">    defaults: <span style="color: blue">new</span> {
controller = <span style="color: #a31515">"Catalog"</span>, id = <span style="color: #2b91af">RouteParameter</span>.Optional
}</pre>
          <pre style="margin: 0px">);</pre>
        </div>
        <p>
The MapHttpRoute method is an extension method defined in the System.Web.Http namespace,
so I had to add a using directive for it.
</p>
        <p>
          <strong>Composition</strong>
        </p>
        <p>
Wiring up Controllers with Constructor Injection turned out to be rather painful.
For a starting point, I used <a href="http://www.nikosbaxevanis.com/bonus-bits/">Nikos
Baxevanis'</a><a href="http://www.nikosbaxevanis.com/bonus-bits/2012/03/using-the-web-api-dependency-resolver-with-castle-windsor.html">guide</a>,
but it turns out there are further subtleties which should be addressed (more about
this later, but to prevent a stream of comments about the DependencyResolver API:
yes, I know about that, but it's inadequate for a number of reasons).
</p>
        <p>
          <strong>Media Types</strong>
        </p>
        <p>
In the ASP.NET Web API application/json is now the default media type format if the
client doesn't supply any Accept header. For the WCF Web API I had had to resort to <a href="http://stackoverflow.com/questions/6779254/set-default-response-type-in-wcf-web-api/9002099#9002099">a
hack to change the default</a>, so this was a pleasant surprise.
</p>
        <p>
It's still pretty easy to add more supported media types:
</p>
        <div style="font-family: consolas, 'Courier New'; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.XmlFormatter</pre>
          <pre style="margin: 0px">    .SupportedMediaTypes.Add(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(<span style="color: #a31515">"application/vnd.247e.artist+xml"</span>));</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">GlobalConfiguration</span>.Configuration.Formatters.JsonFormatter</pre>
          <pre style="margin: 0px">    .SupportedMediaTypes.Add(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">MediaTypeHeaderValue</span>(<span style="color: #a31515">"application/vnd.247e.artist+json"</span>));</pre>
        </div>
        <p>
(Talk about a <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a> violation,
BTW...)
</p>
        <p>
However, due to an over-reliance on global state, it's not so easy to figure out how
one would go about mapping certain media types to only a single Controller. This was
much easier in the WCF Web API because it was possible to assign a separate configuration
instance to each Controller/Api/Resource/Service/Whatever... This, I've still to figure
out how to do...
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3fa91879-8089-4c25-a0a8-25d23d17404e" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Implementing an Abstract Factory</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/03/15/ImplementingAnAbstractFactory.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,e0678efd-d233-470d-916a-7a44a1aa1a68.aspx</id>
    <published>2012-03-15T22:01:13.797828+01:00</published>
    <updated>2012-03-15T22:01:13.797828+01:00</updated>
    <category term="Castle Windsor" label="Castle Windsor" scheme="http://blog.ploeh.dk/CategoryView,category,CastleWindsor.aspx" />
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract Factory</a> is
a tremendously useful pattern when used with Dependency Injection (DI). While I’ve <a href="http://stackoverflow.com/questions/2280170/why-do-we-need-abstract-factory-design-pattern/2280289#2280289">repeatedly
described</a> how it can be used to solve various problems in DI, apparently I’ve
never described how to implement one. As a comment to <a href="http://blog.ploeh.dk/2010/01/20/EnablingDIForLazyComponents.aspx">an
older blog post of mine</a>, <a href="http://blogs.codes-sources.com/tja/">Thomas
Jaskula</a> asks how I’d implement the IOrderShipperFactory.
</p>
        <p>
To stay consistent with <a href="http://blog.ploeh.dk/2010/01/20/EnablingDIForLazyComponents.aspx">the
old order shipper scenario</a>, this blog post outlines three alternative ways to
implement the IOrderShipperFactory interface.
</p>
        <p>
To make it a bit more challenging, the implementation should create instances of the
OrderShipper2 class, which itself has a dependency:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">OrderShipper2</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IOrderShipper</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IChannel</font></span> channel;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> OrderShipper2(<span style="color: "><font color="#2b91af">IChannel</font></span> channel)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (channel
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"channel"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.channel
= channel;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Ship(<span style="color: "><font color="#2b91af">Order</font></span> order)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
Ship the order and</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
raise a domain event over this.channel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
In order to be able to create an instance of OrderShipper2, any factory implementation
must be able to supply an IChannel instance.
</p>
        <p>
          <strong>Manually Coded Factory</strong>
        </p>
        <p>
The first option is to manually wire up the OrderShipper2 instance within the factory:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">ManualOrderShipperFactory</font>
              </span> :</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IOrderShipperFactory</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IChannel</font></span> channel;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> ManualOrderShipperFactory(<span style="color: "><font color="#2b91af">IChannel</font></span> channel)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (channel
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"channel"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.channel
= channel;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#2b91af">IOrderShipper</font></span> Create()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">OrderShipper2</font></span>(<span style="color: "><font color="#0000ff">this</font></span>.channel);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This has the advantage that it’s easy to understand. It can be unit tested and implemented
in the same library that also contains OrderShipper2 itself. This means that any client
of that library is supplied with a read-to-use implementation.
</p>
        <p>
The disadvantage of this approach is that if/when the constructor of OrderShipper2
changes, the ManualOrderShipperFactory class must also be corrected. Pragmatically,
this may not be a big deal, but one could successfully argue that this violates the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open/Closed
Principle</a>.
</p>
        <p>
          <strong>Container-based Factory</strong>
        </p>
        <p>
Another option is to make the implementation a thin <a href="http://en.wikipedia.org/wiki/Adapter_pattern">Adapter</a> over
a DI Container – in this example <a href="http://castleproject.org/container/index.html">Castle
Windsor</a>:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">ContainerFactory</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IOrderShipperFactory</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#2b91af">IWindsorContainer</font></span> container;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> ContainerFactory(<span style="color: "><font color="#2b91af">IWindsorContainer</font></span> container)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (container
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"container"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.container
= container;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#2b91af">IOrderShipper</font></span> Create()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.container.Resolve&lt;<span style="color: "><font color="#2b91af">IOrderShipper</font></span>&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
But wait! Isn’t this an application of the <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service
Locator anti-pattern</a>? Not if this class is part of the <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">Composition
Root</a>.
</p>
        <p>
If this implementation was placed in the same library as OrderShipper2 itself, it
would mean that the library would have a hard dependency on the container. In such
a case, it would certainly be a Service Locator.
</p>
        <p>
However, when a Composition Root already references a container, it makes sense to
place the ContainerFactory class there. This changes its <a href="http://blog.ploeh.dk/2011/08/25/ServiceLocatorRolesVsMechanics.aspx">role</a> to
the pure infrastructure component it really ought to be. This seems more SOLID, but
the disadvantage is that there’s no longer a ready-to-use implementation packaged
together with the LazyOrderShipper2 class. All new clients must supply their own implementation.
</p>
        <p>
          <strong>Dynamic Proxy</strong>
        </p>
        <p>
The third option is to basically reduce the principle behind the container-based factory
to its core. Why bother writing even a thin Adapter if one can be automatically generated.
</p>
        <p>
With Castle Windsor, the <a href="http://stw.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx">Typed
Factory Facility</a> makes this possible:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">container.AddFacility&lt;<span style="color: "><font color="#2b91af">TypedFactoryFacility</font></span>&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">container.Register(</font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">Component</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.For&lt;<span style="color: "><font color="#2b91af">IOrderShipperFactory</font></span>&gt;()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.AsFactory());</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> factory
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
container.Resolve&lt;<span style="color: "><font color="#2b91af">IOrderShipperFactory</font></span>&gt;();</font>
          </pre>
        </div>
        <p>
There <em>is no longer</em> any code which implements IOrderShipperFactory. Instead,
a class conceptually similar to the ContainerFactory class above is dynamically generated
and emitted at runtime.
</p>
        <p>
While the code never materializes, conceptually, such a dynamically emitted implementation
is still part of the Composition Root.
</p>
        <p>
This approach has the advantage that it’s very DRY, but the disadvantages are similar
to the container-based implementation above: there’s no longer a ready-to-use implementation.
There’s also the additional disadvantage that out of the three alternative here outlined,
the proxy-based implementation is the most difficult to understand.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=e0678efd-d233-470d-916a-7a44a1aa1a68" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Is Layering Worth the Mapping?</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/02/09/IsLayeringWorthTheMapping.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,94a1c53c-51cd-412e-a520-2bf28d527da3.aspx</id>
    <published>2012-02-09T23:55:44.1153905+01:00</published>
    <updated>2012-02-09T23:55:44.1153905+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
For years, layered application architecture has been a de-facto standard for loosely
coupled architectures, but the question is: does the layering really provide benefit?
</p>
        <p>
In theory, layering is a way to decouple concerns so that UI concerns or data access
technologies don’t pollute the domain model. However, this style of architecture seems
to come at a pretty steep price: there’s a lot of mapping going on between the layers.
Is it really worth the price, or is it OK to define data structures that cut across
the various layers?
</p>
        <p>
The short answer is that if you cut across the layers, it’s no longer a layered application.
However, the price of layering may still be too high.
</p>
        <p>
In this post I’ll examine the problem and the proposed solution and demonstrate why
none of them are particularly good. In the end, I’ll provide a pointer going forward.
</p>
        <p>
          <strong>Proper Layering</strong>
        </p>
        <p>
To understand the problem with layering, I’ll describe a fairly simple example. Assume
that you are building a music service and you’ve been asked to render a top 10 list
for the day. It would have to look something like this in a web page:
</p>
        <p>
          <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Top10Tracks" border="0" alt="Top10Tracks" src="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/04fbdab3357e_11E24/Top10Tracks_1.png" width="494" height="250" />
        </p>
        <p>
As part of rending the list, you must color the <em>Movement</em> values accordingly
using CSS.
</p>
        <p>
A properly layered architecture would look something like this:
</p>
        <p>
          <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ProperLayering" border="0" alt="ProperLayering" src="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/04fbdab3357e_11E24/ProperLayering_3.png" width="385" height="480" />
        </p>
        <p>
Each layer defines some services and some data-carrying classes (<em>Entities</em>,
if you want to stick with the <a href="http://www.amazon.com/gp/product/0321125215/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321125215">Domain-Driven
Design</a> terminology). The Track class is defined by the Domain layer, while the
TopTrackViewModel class is defined in the User Interface layer, and so on. If you
are wondering about why Track is used to communicate both up and down, this is because
the Domain layer should be the most decoupled layer, so the other layers exist to
serve it. In fact, this is just a vertical representation of the Ports and Adapters
architecture, with the Domain Model sitting in the center.
</p>
        <p>
This architecture is very decoupled, but comes at the cost of much mapping and seemingly
redundant repetition. To demonstrate why that is, I’m going to show you some of the
code. This is an ASP.NET MVC application, so the Controller is an obvious place to
start:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">ViewResult</font>
              </span> Index()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> date
= <span style="color: "><font color="#2b91af">DateTime</font></span>.Now.Date;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> topTracks
= <span style="color: "><font color="#0000ff">this</font></span>.trackService.GetTopFor(date);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.View(topTracks);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This doesn’t look so bad. It asks an ITrackService for the top tracks for the day
and returns a list of TopTrackViewModel instances. This is the implementation of the
track service:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IEnumerable</font>
              </span>&lt;<span style="color: "><font color="#2b91af">TopTrackViewModel</font></span>&gt;
GetTopFor(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">DateTime</font></span> date)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> today
= <span style="color: "><font color="#2b91af">DateTime</font></span>.Now.Date;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> yesterDay
= today - <span style="color: "><font color="#2b91af">TimeSpan</font></span>.FromDays(1);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> todaysTracks
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.repository.GetTopFor(today).ToList();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> yesterdaysTracks
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.repository.GetTopFor(yesterDay).ToList();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> length
= todaysTracks.Count;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> positions
= <span style="color: "><font color="#2b91af">Enumerable</font></span>.Range(1, length);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">from</font></span> tt <span style="color: "><font color="#0000ff">in</font></span> todaysTracks.Zip(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
positions, (t, p) =&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                    <span style="color: "><font color="#0000ff">new</font></span> {
Position = p, Track = t })</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">let</font></span> yp
= (<span style="color: "><font color="#0000ff">from</font></span> yt <span style="color: "><font color="#0000ff">in</font></span> yesterdaysTracks.Zip(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                           
positions, (t, p) =&gt; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                                </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">new</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                               
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                                   
Position = p,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                                   
Track = t</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                               
})</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                        <span style="color: "><font color="#0000ff">where</font></span> yt.Track.Id
== tt.Track.Id</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                        <span style="color: "><font color="#0000ff">select</font></span> yt.Position)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                       
.DefaultIfEmpty(-1)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                       
.Single()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">let</font></span> cssClass
= GetCssClass(tt.Position, yp)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">select</font></span><span style="color: "><font color="#0000ff">new</font></span></font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">TopTrackViewModel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
Position = tt.Position,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
Name = tt.Track.Name,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
Artist = tt.Track.Artist,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
CssClass = cssClass</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
};</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">static</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> GetCssClass(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">int</font></span> todaysPosition, <span style="color: "><font color="#0000ff">int</font></span> yesterdaysPosition)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (yesterdaysPosition
&lt; 0)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"new"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (todaysPosition
&lt; yesterdaysPosition)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"up"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (todaysPosition
== yesterdaysPosition)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"same"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"down"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
While that looks fairly complex, there’s really not a lot of mapping going on. Most
of the work is spent getting the top 10 track for today and yesterday. For each position
on today’s top 10, the query finds the position of the same track on yesterday’s top
10 and creates a TopTrackViewModel instance accordingly.
</p>
        <p>
Here’s the only mapping code involved:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">select</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">new</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">TopTrackViewModel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
Position = tt.Position,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
Name = tt.Track.Name,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
Artist = tt.Track.Artist,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
CssClass = cssClass</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">};</font>
          </pre>
        </div>
        <p>
This maps from a Track (a Domain class) to a TopTrackViewModel (a UI class).
</p>
        <p>
This is the relevant implementation of the repository:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IEnumerable</font>
              </span>&lt;<span style="color: "><font color="#2b91af">Track</font></span>&gt;
GetTopFor(<span style="color: "><font color="#2b91af">DateTime</font></span> date)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> dbTracks
= <span style="color: "><font color="#0000ff">this</font></span>.GetTopTracks(date);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">foreach</font></span> (<span style="color: "><font color="#0000ff">var</font></span> dbTrack <span style="color: "><font color="#0000ff">in</font></span> dbTracks)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">yield</font></span><span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Track</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
dbTrack.Id,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
dbTrack.Name,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
dbTrack.Artist);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
You may be wondering about the translation from DbTrack to Track. In this case you
can assume that the DbTrack class is a class representation of a database table, modeled
along the lines of your favorite ORM. The Track class, on the other hand, is a proper
object-oriented class which <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">protects
its invariants</a>:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">Track</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#0000ff">int</font></span> id;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">string</font></span> name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">string</font></span> artist;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> Track(<span style="color: "><font color="#0000ff">int</font></span> id, <span style="color: "><font color="#0000ff">string</font></span> name, <span style="color: "><font color="#0000ff">string</font></span> artist)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (name
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"name"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (artist
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"artist"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.id
= id;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.name
= name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.artist
= artist;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">int</font></span> Id</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.id;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> Name</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.name;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">set</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">if</font></span> (<span style="color: "><font color="#0000ff">value</font></span> == <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"value"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.name
= <span style="color: "><font color="#0000ff">value</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> Artist</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.artist;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">set</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">if</font></span> (<span style="color: "><font color="#0000ff">value</font></span> == <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"value"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.artist
= <span style="color: "><font color="#0000ff">value</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
No ORM I’ve encountered so far has been able to properly address such invariants –
particularly the non-default constructor seems to be a showstopper. This is the reason
a separate DbTrack class is required, even for ORMs with so-called POCO support.
</p>
        <p>
In summary, that’s a lot of mapping. What would be involved if a new field is required
in the top 10 table? Imagine that you are being asked to provide the release label
as an extra column.
</p>
        <ol>
          <li>
A Label column must be added to the database schema and the DbTrack class. 
</li>
          <li>
A Label property must be added to the Track class. 
</li>
          <li>
The mapping from DbTrack to Track must be updated. 
</li>
          <li>
A Label property must be added to the TopTrackViewModel class. 
</li>
          <li>
The mapping from Track to TopTrackViewModel must be updated. 
</li>
          <li>
The UI must be updated.</li>
        </ol>
        <p>
That’s a lot of work in order to add a single data element, and this is even a read-only
scenario! Is it really worth it?
</p>
        <p>
          <strong>Cross-Cutting Entities</strong>
        </p>
        <p>
Is strict separation between layers really so important? What would happen if Entities
were allowed to travel across all layers? Would that really be so bad?
</p>
        <p>
Such an architecture is often drawn like this:
</p>
        <p>
          <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CrossCuttingEntities" border="0" alt="CrossCuttingEntities" src="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/04fbdab3357e_11E24/CrossCuttingEntities_3.png" width="441" height="480" />
        </p>
        <p>
Now, a single Track class is allowed to travel from layer to layer in order to avoid
mapping. The controller code hasn’t really changed, although the model returned to
the View is no longer a sequence of TopTrackViewModel, but simply a sequence of Track
instances:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">ViewResult</font>
              </span> Index()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> date
= <span style="color: "><font color="#2b91af">DateTime</font></span>.Now.Date;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> topTracks
= <span style="color: "><font color="#0000ff">this</font></span>.trackService.GetTopFor(date);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.View(topTracks);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The GetTopFor method also looks familiar:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IEnumerable</font>
              </span>&lt;<span style="color: "><font color="#2b91af">Track</font></span>&gt;
GetTopFor(<span style="color: "><font color="#2b91af">DateTime</font></span> date)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> today
= <span style="color: "><font color="#2b91af">DateTime</font></span>.Now.Date;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> yesterDay
= today - <span style="color: "><font color="#2b91af">TimeSpan</font></span>.FromDays(1);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> todaysTracks
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.repository.GetTopFor(today).ToList();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> yesterdaysTracks
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.repository.GetTopFor(yesterDay).ToList();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> length
= todaysTracks.Count;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> positions
= <span style="color: "><font color="#2b91af">Enumerable</font></span>.Range(1, length);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">from</font></span> tt <span style="color: "><font color="#0000ff">in</font></span> todaysTracks.Zip(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
positions, (t, p) =&gt; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                    <span style="color: "><font color="#0000ff">new</font></span> {
Position = p, Track = t })</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">let</font></span> yp
= (<span style="color: "><font color="#0000ff">from</font></span> yt <span style="color: "><font color="#0000ff">in</font></span> yesterdaysTracks.Zip(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                           
positions, (t, p) =&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                                </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">new</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                               
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                                   
Position = p,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                                   
Track = t</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                               
})</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                        <span style="color: "><font color="#0000ff">where</font></span> yt.Track.Id
== tt.Track.Id</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                        <span style="color: "><font color="#0000ff">select</font></span> yt.Position)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                       
.DefaultIfEmpty(-1)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                       
.Single()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">let</font></span> cssClass
= GetCssClass(tt.Position, yp)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">select</font></span> Enrich(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
tt.Track, tt.Position, cssClass);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">static</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> GetCssClass(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">int</font></span> todaysPosition, <span style="color: "><font color="#0000ff">int</font></span> yesterdaysPosition)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (yesterdaysPosition
&lt; 0)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"new"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (todaysPosition
&lt; yesterdaysPosition)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"up"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (todaysPosition
== yesterdaysPosition)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"same"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#a31515">"down"</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">static</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Track</font>
              </span> Enrich(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Track</font></span> track, <span style="color: "><font color="#0000ff">int</font></span> position, <span style="color: "><font color="#0000ff">string</font></span> cssClass)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
track.Position = position;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
track.CssClass = cssClass;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span> track;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Whether or not much has been gained is likely to be a subjective assessment. While
mapping is no longer taking place, it’s still necessary to assign a CSS Class and
Position to the track before handing it off to the View. This is the responsibility
of the new Enrich method:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">static</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Track</font>
              </span> Enrich(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Track</font></span> track, <span style="color: "><font color="#0000ff">int</font></span> position, <span style="color: "><font color="#0000ff">string</font></span> cssClass)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
track.Position = position;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
track.CssClass = cssClass;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span> track;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
If not much is gained at the UI layer, perhaps the data access layer has become simpler?
This is, indeed, the case:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IEnumerable</font>
              </span>&lt;<span style="color: "><font color="#2b91af">Track</font></span>&gt;
GetTopFor(<span style="color: "><font color="#2b91af">DateTime</font></span> date)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.GetTopTracks(date);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
If, hypothetically, you were asked to add a label to the top 10 table it would be
much simpler:
</p>
        <ol>
          <li>
A Label column must be added to the database schema and the Track class. 
</li>
          <li>
The UI must be updated.</li>
        </ol>
        <p>
This looks good. Are there any disadvantages? Yes, certainly. Consider the Track class:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">Track</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">int</font></span> Id
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> Name
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> Artist
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">int</font></span> Position
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> CssClass
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
It also looks simpler than before, but this is actually not particularly beneficial,
as it doesn’t protect its invariants. In order to play nice with the ORM of your choice,
it must have a <a href="http://blog.ploeh.dk/2011/05/30/DesignSmellDefaultConstructor.aspx">default
constructor</a>. It also has <a href="http://blog.ploeh.dk/2011/05/26/CodeSmellAutomaticProperty.aspx">automatic
properties</a>. However, most insidiously, it also somehow gained the Position and
CssClass properties.
</p>
        <p>
What does the Position property imply outside of the context of a top 10 list? A position
in relation to what?
</p>
        <p>
Even worse, why do we have a property called CssClass? CSS is a very web-specific
technology so why is this property available to the Data Access and Domain layers?
How does this fit if you are ever asked to build a native desktop app based on the
Domain Model? Or a REST API? Or a batch job?
</p>
        <p>
When Entities are allowed to travel along layers, the layers basically collapse. UI
concerns and data access concerns will inevitably be mixed up. You may think you have
layers, but you don’t.
</p>
        <p>
Is that such a bad thing, though?
</p>
        <p>
Perhaps not, but I think it’s worth pointing out:
</p>
        <blockquote>
          <p>
The choice is whether or not you want to build a layered application. If you want
layering, the separation must be strict. If it isn’t, it’s not a layered application.
</p>
        </blockquote>
        <p>
There may be great benefits to be gained from allowing Entities to travel from database
to user interface. Much mapping cost goes away, but you must realize that then you’re
no longer building a layered application – now you’re building a web application (or
whichever other type of app you’re initially building).
</p>
        <p>
          <strong>Further Thoughts</strong>
        </p>
        <p>
It’s a common question: <em>how hard is it to add a new field to the user interface?</em></p>
        <p>
The underlying assumption is that the field must somehow originate from a corresponding
database column. If this is the case, mapping seems to be in the way.
</p>
        <p>
However, if this is the major concern about the application you’re currently building,
it’s a strong indication that you are building a CRUD application. If that’s the case, <a href="http://msdn.microsoft.com/en-us/magazine/ee236415.aspx">you
probably don’t need a Domain Model at all</a>. Go ahead and let your ORM POCO classes
travel up and down the stack, but don’t bother creating layers: you’ll be building
a monolithic application no matter how hard you try not to.
</p>
        <p>
In the end it looks as though none of the options outlined in this article are particularly
good. Strict layering leads to too much mapping, and no mapping leads to monolithic
applications. Personally, I’ve certainly written quite a lot of strictly layered applications,
and while the separation of concerns was good, I was never happy with the mapping
overhead.
</p>
        <p>
At the heart of the problem is the CRUDy nature of many applications. In such applications,
complex object graphs are traveling up and down the stack. The trick is to avoid complex
object graphs.
</p>
        <p>
Move less data around and things are likely to become simpler. This is one of the
many interesting promises of <a href="http://abdullin.com/cqrs">CQRS</a>, and particularly
it’s asymmetric approach to data.
</p>
        <p>
To be honest, I wish I had fully realized this when I started writing <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my
book</a>, but when I finally realized what I’d implicitly felt for long, it was to
late to change direction. Rest assured that nothing in the book is fundamentally flawed.
The patterns etc. still hold, but the examples could have been cleaner if the sample
applications had taken a CQRS-like direction instead of strict layering.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=94a1c53c-51cd-412e-a520-2bf28d527da3" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Loose Coupling and the Big Picture</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/02/02/LooseCouplingAndTheBigPicture.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,45e8361f-bbed-4b7e-8632-ff28a7f11c05.aspx</id>
    <published>2012-02-02T21:37:40.3767934+01:00</published>
    <updated>2012-02-02T21:44:18.6701991+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
A common criticism of loosely coupled code is that it’s harder to understand. How
do you see the big picture of an application when loose coupling is everywhere? When
the entire code base has been programmed against interfaces instead of concrete classes,
how do we understand how the objects are wired and how they interact?
</p>
        <p>
In this post, I’ll provide answers on various levels, from high-level architecture
over object-oriented principles to more nitty-gritty code. Before I do that, however,
I’d like to pose a set of questions you should always be prepared to answer.
</p>
        <p>
          <strong>Mu</strong>
        </p>
        <p>
My first reaction to that sort of question is: <em>you say loosely coupled code is
harder to understand. Harder than what?</em></p>
        <p>
If we are talking about a non-trivial application, odds are that it’s going to take
some time to understand the code base – whether or not it’s loosely coupled. Agreed:
understanding a loosely coupled code base takes some work, but so does understanding
a tightly coupled code base. The question is whether it’s <em>harder</em> to understand
a loosely coupled code base?
</p>
        <p>
Imagine that I’m having a discussion about this subject with Mary Rowan from <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my
book</a>.
</p>
        <p>
          <strong>Mary:</strong> “Loosely coupled code is harder to understand.”
</p>
        <p>
          <strong>Me:</strong> “Why do you think that is?”
</p>
        <p>
          <strong>Mary:</strong> “It’s very hard to navigate the code base because I always
end up at an interface.”
</p>
        <p>
          <strong>Me:</strong> “Why is that a problem?”
</p>
        <p>
          <strong>Mary:</strong> “Because I don’t know what the interface <em>does</em>.”
</p>
        <p>
At this point I’m very tempted to answer <a href="http://en.wikipedia.org/wiki/Mu_%28negative%29">Mu</a>.
An interfaces doesn’t <em>do</em> anything – that’s the whole point of it. According
to the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov
Substitution Principle</a> (LSP), a consumer shouldn’t have to care about what happens
on the other side of the interface.
</p>
        <p>
However, developers used to tightly coupled code aren’t used to think about services
in this way. They are used to navigate the code base from consumer to service to understand
how the two of them interact, and I will gladly admit this: in principle, that’s <em>impossible</em> to
do in a loosely coupled code base. I’ll return to this subject in a little while,
but first I want to discuss some strategies for understanding a loosely coupled code
base.
</p>
        <p>
          <strong>Architecture and Documentation</strong>
        </p>
        <p>
Yes: documentation. Don’t dismiss it. While I agree with Uncle Bob and like-minded
spirits that the code <em>is</em> the documentation, a two-page document that outlines
the Big Picture might save you from many hours of code archeology.
</p>
        <p>
The typical agile mindset is to minimize documentation because it tends to lose touch
with the code base, but even so, it should be possible to maintain a two-page high-level
document so that it stays up to date. Consider the alternative: if you have so much
architectural churn that even a two-page overview regularly falls behind, then you’re
probably having a greater problem than understanding your loosely coupled code base.
</p>
        <p>
Maintaining such a document isn’t adverse to the agile spirit. You’ll find the same
advice in <a href="http://www.amazon.com/gp/product/0470684208/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0470684208">Lean
Architecture</a> (p. 127). Don’t underestimate the value of such a document.
</p>
        <p>
          <strong>See the Forest Instead of the Trees</strong>
        </p>
        <p>
Understanding a loosely coupled code base typically tends to require a shift of mindset.
</p>
        <p>
Recall my discussion with Mary Rowan. The criticism of loose coupling is that it’s
difficult to understand which collaborators are being invoked. A developer like Mary
Rowan is used to learn a code base by understanding all the myriad concrete details
of it. In effect, while there may be ‘classes’ around, there are <em>no</em> abstractions
in place. In order to understand the behavior of a user interface element, it’s necessary
to also understand what’s happening in the database – and everything in between.
</p>
        <p>
A loosely coupled code base shouldn’t be like that.
</p>
        <blockquote>
          <p>
The entire purpose of loose coupling is that we should be able to reason about a part
(a ‘unit’, if you will) without understanding the whole.
</p>
        </blockquote>
        <p>
In a tightly coupled code base, it’s often impossible to see the forest for the trees.
Although we developers are good at relating to details, a tightly coupled code base
requires us to be able to contain <em>the entire</em> code base in our heads in order
to understand it. As the size of the code base grows, this becomes increasingly difficult.
</p>
        <p>
In a loosely coupled code base, on the other hand, it should be possible to understand
smaller parts in isolation. However, I purposely wrote “should be”, because that’s
not always the case. Often, a so-called “loosely coupled” code base violates basic
principles of object-oriented design.
</p>
        <p>
          <strong>RAP</strong>
        </p>
        <p>
The criticism that it’s hard to see “what’s on the other side of an interface” is,
in my opinion, central. It betrays a mindset which is still tightly coupled.
</p>
        <p>
In many code bases there’s often a single implementation of a given interface, so
developers can be forgiven if they think about an interface as only a piece of friction
that prevents them from reaching the concrete class on the other side. However, if
that’s the case with most of the interfaces in a code base, it signifies a violation
of the <a href="http://codemanship.co.uk/parlezuml/blog/?postid=934">Reused Abstractions
Principle</a> (RAP) more than it signifies loose coupling.
</p>
        <p>
Jim Cooper, a reader of my book, put it quite eloquently <a href="http://www.manning-sandbox.com/thread.jspa?threadID=48257">on
the book’s forum</a>:
</p>
        <blockquote>
          <p>
“So many people think that using an interface magically decouples their code. It doesn't.
It only changes the nature of the coupling. If you don't believe that, try changing
a method signature in an interface - none of the code containing method references
or any of the implementing classes will compile. I call that coupled”
</p>
        </blockquote>
        <p>
Refactoring tools aside, I completely agree with this statement. The RAP is a test
we can use to verify whether or not an interface is truly reusable – what better test
is there than to actually reuse your interfaces?
</p>
        <p>
The corollary of this discussion is that if a code base is massively violating the
RAP then it’s going to be hard to understand. It has all the disadvantages of loose
coupling with few of the benefits. If that’s the case, you would gain more benefit
from making it either more tightly coupled or truly loosely coupled.
</p>
        <p>
What does “truly loosely coupled” mean?
</p>
        <p>
          <strong>LSP</strong>
        </p>
        <p>
According to the LSP a consumer <em>must not</em> concern itself with “what’s on the
other side of the interface”. It should be possible to replace any implementation
with any other implementation of the same interface without changing the correctness
of the program.
</p>
        <p>
This is why I previously said that in a truly loosely coupled code base, it isn’t
‘hard’ to understand “what’s on the other side of the interface” – it’s <em>impossible</em>.
At design-time, there’s <em>nothing</em> ‘behind’ the interface. The interface is
what you are programming against. It’s all there is.
</p>
        <p>
Mary has been listening to all of this, and now she protests:
</p>
        <p>
          <strong>Mary:</strong> “At run-time, there’s going to be a concrete class behind the
interface.”
</p>
        <p>
          <strong>Me</strong> (being annoyingly pedantic): “Not quite. There’s going to be an
instance of a concrete class which the consumer invokes via the interface it implements.”
</p>
        <p>
          <strong>Mary:</strong> “Yes, but I still need to know which concrete class is going
to be invoked.”
</p>
        <p>
          <strong>Me:</strong> “Why?”
</p>
        <p>
          <strong>Mary:</strong> “Because otherwise I don’t know what’s going to happen when
I invoke the method.”
</p>
        <p>
This type of answer often betrays a much more fundamental problem in a code base.
</p>
        <p>
          <strong>CQS</strong>
        </p>
        <p>
Now we are getting into the nitty-gritty details of class design. What would you expect
that the following method does?
</p>
        <div style="font-family: ; background: white; color: ">
          <div style="font-family: ; background: white; color: ">
            <pre style="margin: 0px">
              <span style="color: ">
                <font color="#0000ff">
                  <font style="font-size: 10pt">public</font>
                </font>
              </span>
              <font style="font-size: 10pt">
                <span style="color: ">
                  <font color="#2b91af">List</font>
                </span>&lt;<span style="color: "><font color="#2b91af">Order</font></span>&gt;
GetOpenOrders(<span style="color: "><font color="#2b91af">Customer</font></span> customer)</font>
            </pre>
          </div>
        </div>
        <p>
The method name indicates that it gets open orders, and the signature seems to back
it up. A single database query might be involved, since this looks a lot like a read-operation.
A quick glance at the implementation seems to verify that first impression:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">List</font>
              </span>&lt;<span style="color: "><font color="#2b91af">Order</font></span>&gt;
GetOpenOrders(<span style="color: "><font color="#2b91af">Customer</font></span> customer)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> orders
= GetOrders(customer);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">from</font></span> o <span style="color: "><font color="#0000ff">in</font></span> orders</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">where</font></span> o.Status
== <span style="color: "><font color="#2b91af">OrderStatus</font></span>.Open</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">select</font></span> o).ToList();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Is it safe to assume that this is a side-effect-free method call? As it turns out,
this is far from the case in this particular code base:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">List</font>
              </span>&lt;<span style="color: "><font color="#2b91af">Order</font></span>&gt;
GetOrders(<span style="color: "><font color="#2b91af">Customer</font></span> customer)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> gw
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">CustomerGateway</font></span>(<span style="color: "><font color="#0000ff">this</font></span>.ConnectionString);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> orders
= gw.GetOrders(customer);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
AuditOrders(orders);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
FixCustomer(gw, orders, customer);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span> orders;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The devil is in the details. What does AuditOrders do? And what does FixCustomer do?
One method at a time:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> AuditOrders(<span style="color: "><font color="#2b91af">List</font></span>&lt;<span style="color: "><font color="#2b91af">Order</font></span>&gt;
orders)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> user
= <span style="color: "><font color="#2b91af">Thread</font></span>.CurrentPrincipal.Identity.ToString();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> gw
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">OrderGateway</font></span>(<span style="color: "><font color="#0000ff">this</font></span>.ConnectionString);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">foreach</font></span> (<span style="color: "><font color="#0000ff">var</font></span> o <span style="color: "><font color="#0000ff">in</font></span> orders)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> clone
= o.Clone();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> ar
= <span style="color: "><font color="#0000ff">new</font></span></font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">AuditRecord</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
Time = <span style="color: "><font color="#2b91af">DateTime</font></span>.Now,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
User = user</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
};</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
clone.AuditTrail.Add(ar);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
gw.Update(clone);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
We don't want the consumer to see the audit trail.</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
o.AuditTrail.Clear();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
OK, it turns out that this method actually makes a <em>copy</em> of <em>each and every</em> order
and updates that copy, writing it back to the database in order to leave behind an
audit trail. It also <em>mutates</em> each order before returning to the caller. Not
only does this method result in an unexpected N+1 problem, it also <em>mutates its
input</em>, and perhaps even more surprising, it’s leaving the system in a state where
the in-memory object is different from the database. This could lead to some pretty
interesting bugs.
</p>
        <p>
Then what happens in the FixCustomer method? This:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
Fixes the customer status field if there were orders</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
added directly through the database.</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">static</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> FixCustomer(<span style="color: "><font color="#2b91af">CustomerGateway</font></span> gw,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">List</font></span>&lt;<span style="color: "><font color="#2b91af">Order</font></span>&gt;
orders, <span style="color: "><font color="#2b91af">Customer</font></span> customer)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> total
= orders.Sum(o =&gt; o.Total);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (customer.Status
!= <span style="color: "><font color="#2b91af">CustomerStatus</font></span>.Preferred</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
&amp;&amp; total &gt; PreferredThreshold)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
customer.Status = <span style="color: "><font color="#2b91af">CustomerStatus</font></span>.Preferred;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
gw.Update(customer);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Another potential database write operation, as it turns out – complete with <a href="http://butunclebob.com/ArticleS.TimOttinger.ApologizeIncode">an
apology</a>. Now that we’ve learned all about the details of the code, even the GetOpenOrders
method is beginning to look suspect. The GetOrders method returns all orders, with
the side effect that <em>all</em> orders were audited as having been read by the user,
but the GetOpenOrders filters the output. In the end, it turns out that we can’t even
trust the audit trail.
</p>
        <p>
While I must apologize for this contrived example of a <a href="http://martinfowler.com/eaaCatalog/transactionScript.html">Transaction
Script</a>, it’s clear that when code looks like that, it’s no wonder why developers
think that it’s necessary to contain the entire code base in their heads. When this
is the case, interfaces are only in the way.
</p>
        <p>
However, this is not the fault of loose coupling, but rather a failure to adhere to
the very fundamental principle of <a href="http://en.wikipedia.org/wiki/Command-query_separation">Command-Query
Separation</a> (CQS). You should be able to tell from the method signature alone whether
invoking the method will or will not have side-effects. This is one of the key messages
from <a href="http://www.amazon.com/gp/product/0132350882/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0132350882">Clean
Code</a>: the method name and signature is an abstraction. You should be able to reason
about the behavior of the method from its declaration. You shouldn’t have to read
the code to get an idea about what it does.
</p>
        <blockquote>
          <p>
Abstractions always hide details. Method declarations do too. The point is that you
should be able to read just the method declaration in order to gain a basic understanding
of what’s going on. You can always return to the method’s code later in order to understand
detail, but reading the method declaration alone should provide the Big Picture.
</p>
        </blockquote>
        <p>
Strictly adhering to CQS goes a long way in enabling you to understand a loosely coupled
code base. If you can reason about methods at a high level, you don’t need to see
“the other side of the interface” in order to understand the Big Picture.
</p>
        <p>
          <strong>Stack Traces</strong>
        </p>
        <p>
Still, even in a loosely coupled code base with great test coverage, integration issues
arise. While each class works fine in isolation, when you integrate them, sometimes
the interactions between them cause errors. This is often because of incorrect assumptions
about the collaborators, which often indicates that the LSP was somehow violated.
</p>
        <p>
To understand why such errors occur, we need to understand which concrete classes
are interacting. How do we do that in a loosely coupled code base?
</p>
        <p>
That’s actually easy: look at the stack trace from your error report. If your error
report doesn’t include a stack trace, make sure that it’s going to do that in the
future.
</p>
        <blockquote>
          <p>
The stack trace is one of the most important troubleshooting tools in a loosely coupled
code base, because it’s going to tell you exactly which classes were interacting when
an exception was thrown.
</p>
        </blockquote>
        <p>
Furthermore, if the code base also adheres to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> and the ideals from Clean Code, each method should be
very small (under 15 lines of code). If that’s the case, you can often understand
the exact nature of the error from the stack trace and the error message alone. It
shouldn’t even be necessary to attach a debugger to understand the bug, but in a pinch,
you can still do that.
</p>
        <p>
          <strong>Tooling</strong>
        </p>
        <p>
Returning to the original question, I often hear people advocating tools such as IDE
add-ins which support navigation across interfaces. Such tools might provide a menu
option which enables you to “go to implementation”. At this point it should be clear
that such a tool is mainly going to be helpful in code bases that violate the RAP.
</p>
        <p>
(I’m not naming any particular tools here because I’m not interested in turning this
post into a discussion about the merits of various specific tools.)
</p>
        <p>
          <strong>Conclusion</strong>
        </p>
        <p>
It’s the responsibility of the loosely coupled code base to make sure that it’s easy
to understand the Big Picture and that it’s easy to work with. In the end, that responsibility
falls on the developers who <em>write</em> the code – not the developer who’s trying
to understand it.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=45e8361f-bbed-4b7e-8632-ff28a7f11c05" />
      </div>
    </content>
  </entry>
  <entry>
    <title>SOLID is Append-only</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2012/01/03/SOLIDIsAppendonly.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,301fac13-cb4c-4081-9985-559ca8fbe358.aspx</id>
    <published>2012-01-03T15:43:47.6641782+01:00</published>
    <updated>2012-01-03T15:43:47.6641782+01:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29">SOLID</a> is
a set of principles that, if applied consistently, has some surprising effect on code.
In a <a href="http://blog.ploeh.dk/2011/06/07/SOLIDCodeIsnt.aspx">previous post</a> I
provided a sketch of what it means to meticulously apply the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a>. In this article I will describe what happens when you
follow the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open/Closed
Principle</a> (OCP) to its logical conclusion.
</p>
        <p>
In case a refresher is required, the OCP states that a class should be open for extension,
but <em>closed for modification</em>. It seems to me that people often forget the
second part. What does it mean?
</p>
        <p>
It means that once implemented, you <em>shouldn’t touch that piece of code ever again</em> (unless
you need to correct a bug).
</p>
        <p>
Then how can new functionality be added to a code base? This is still possible through
either inheritance or polymorphic recomposition. Since the L in SOLID signifies the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov
Substitution Principle</a>, SOLID code tends to be based on loosely coupled code <em>composed</em> into
an application through copious use of interfaces – basically, <a href="http://en.wikipedia.org/wiki/Strategy_pattern">Strategies</a> injected
into other Strategies and so on (also due to <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency
Inversion Principle</a>). In order to add functionality, you can create new implementations
of these interfaces and redefine the application’s <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">Composition
Root</a>. Perhaps you’d be wrapping existing functionality in a <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a> or
adding it to a <a href="http://en.wikipedia.org/wiki/Composite_pattern">Composite</a>.
</p>
        <p>
Once in a while, you’ll stop using an old implementation of an interface. Should you
then delete this implementation? What would be the point? At a certain point in time,
this implementation was valuable. Maybe it will become valuable again. Leaving it
as an potential building block seems a better choice.
</p>
        <p>
Thus, if we think about working with code as a CRUD endeavor, SOLID code can be Created
and Read, but never Updated or Deleted. In other words, true SOLID code is append-only
code.
</p>
        <p>
          <strong>Example: Changing AutoFixture’s Number Generation Algorithm</strong>
        </p>
        <p>
In early 2011 <a href="http://autofixture.codeplex.com/workitem/4223">an issue was
reported</a> for <a href="http://autofixture.codeplex.com/">AutoFixture</a>: Anonymous
numbers were created in monotonically increasing sequences, but with separate sequences
for each number type:
</p>
        <p>
integers: 1, 2, 3, 4, 5, …
</p>
        <p>
decimals: 1.0, 2.0, 3.0, 4.0, 5.0, …
</p>
        <p>
and so on. However, the person reporting the issue thought it made more sense if all
numbers shared a single sequence. After thinking about it a little while, I agreed.
</p>
        <p>
Because the AutoFixture code base is fairly SOLID we decided to leave the old implementations
in place and implement the new behavior in new classes.
</p>
        <p>
The old behavior was composed from a set of ISpecimenBuilders. As an example, integers
were generated by this class:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Int32SequenceGenerator</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">ISpecimenBuilder</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">int</font></span> i;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">int</font></span> CreateAnonymous()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#2b91af">Interlocked</font></span>.Increment(<span style="color: "><font color="#0000ff">ref</font></span><span style="color: "><font color="#0000ff">this</font></span>.i);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">object</font></span> Create(<span style="color: "><font color="#0000ff">object</font></span> request,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">ISpecimenContext</font></span> context)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (request
!= <span style="color: "><font color="#0000ff">typeof</font></span>(<span style="color: "><font color="#0000ff">int</font></span>))</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">NoSpecimen</font></span>(request);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.CreateAnonymous();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Similar implementations generated decimals, floats, doubles, etc. Instead of modifying
any of these classes, we left them in the code base and created a new ISpecimenBuilder
that generates all numbers from a single sequence:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">NumericSequenceGenerator</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">ISpecimenBuilder</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">int</font></span> value;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">object</font></span> Create(<span style="color: "><font color="#0000ff">object</font></span> request,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">ISpecimenContext</font></span> context)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> type
= request <span style="color: "><font color="#0000ff">as</font></span><span style="color: "><font color="#2b91af">Type</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (type
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">NoSpecimen</font></span>(request);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.CreateNumericSpecimen(type);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">object</font></span> CreateNumericSpecimen(<span style="color: "><font color="#2b91af">Type</font></span> request)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> typeCode
= <span style="color: "><font color="#2b91af">Type</font></span>.GetTypeCode(request);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">switch</font></span> (typeCode)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.Byte:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">byte</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.Decimal:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">decimal</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.Double:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">double</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.Int16:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">short</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.Int32:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.Int64:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">long</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.SByte:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">sbyte</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.Single:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">float</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.UInt16:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">ushort</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.UInt32:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">uint</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">case</font></span><span style="color: "><font color="#2b91af">TypeCode</font></span>.UInt64:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#0000ff">ulong</font></span>)<span style="color: "><font color="#0000ff">this</font></span>.GetNextNumber();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">default</font></span>:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">NoSpecimen</font></span>(request);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">int</font></span> GetNextNumber()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#2b91af">Interlocked</font></span>.Increment(<span style="color: "><font color="#0000ff">ref</font></span><span style="color: "><font color="#0000ff">this</font></span>.value);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Adding a new class in itself has no effect, so in order to recompose the default behavior
of AutoFixture, we changed a class called DefaultPrimitiveBuilders by removing the
old ISpecimenBuilders like Int32SequenceGenerator and instead adding NumericSequenceGenerator:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">yield</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">return</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">new</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">StringGenerator</font>
              </span>(()
=&gt; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Guid</font></span>.NewGuid());</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">yield</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">return</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">new</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">ConstrainedStringGenerator</font>
              </span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">yield</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">return</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">new</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">StringSeedRelay</font>
              </span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">yield</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">return</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">new</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">NumericSequenceGenerator</font>
              </span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">yield</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">return</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">new</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">CharSequenceGenerator</font>
              </span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">yield</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">return</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">new</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">RangedNumberGenerator</font>
              </span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
even more builders...</font>
            </span>
          </pre>
        </div>
        <p>
NumericSequenceGenerator is the fourth class being yielded here. Before we added NumericSequenceGenerator,
this class instead yielded Int32SequenceGenerator and similar classes. These were
removed.
</p>
        <p>
The DefaultPrimitiveBuilders class is part of AutoFixture’s default <a href="http://en.wikipedia.org/wiki/Facade_pattern">Facade</a> and
is the closest we get to a Composition Root for the library. Recomposing this Facade
enabled us to change the behavior of AutoFixture without modifying (other) existing
classes.
</p>
        <p>
As <a href="http://megakemp.wordpress.com/">Enrico</a> (who implemented this change)
points out, the beauty is that the <a href="http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/">previous
behavior is still in the box</a>, and all it takes is a single method call to bring
it back:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>().Customize(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">NumericSequencePerTypeCustomization</font></span>());</font>
          </pre>
        </div>
        <p>
The only class we had to modify was the DefaultPrimitiveBuilders, which is where the
object graph is composed. In applications this corresponds to the Composition Root,
so even in the face of SOLID code, you still need to modify the Composition Root in
order to recompose the application. However, use of a good DI Container and a strong
set of conventions can do much to minimize the required editing of such a class.
</p>
        <p>
          <strong>SOLID versus Refactoring</strong>
        </p>
        <p>
SOLID is a goal I strive towards in the way I write code and design APIs, but I don’t
think I’ve ever written a significant code base which is perfectly SOLID. While I
consider AutoFixture a ‘fairly’ SOLID code base, it’s not perfect, and I’m currently
performing some design work in order to change some abstractions for version 3.0.
This will require changing some of the existing types and thereby violating the OCP.
</p>
        <p>
It’s worth noting that as long as you can stick with the OCP you can avoid introducing
breaking changes. A breaking change is also an OCP violation, so adhering to the OCP
is more than just an academic exercise – particularly if you write reusable libraries.
</p>
        <p>
Still, while none of my code is perfect and I occasionally have to refactor, I don’t
refactor much. By definition, refactoring means violating the OCP, and while I have
nothing against refactoring code when it’s required, I much prefer putting myself
in a situation where it’s rarely necessary in the first place.
</p>
        <p>
I’ve often been derided for my lack of use of <a href="http://www.jetbrains.com/resharper/">Resharper</a>.
When replying that I have little use for Resharper because I write SOLID code and
thus don’t do much refactoring, I’ve been ridiculed for being totally clueless. People
don’t realize the intimate relationship between SOLID and refactoring. I hope this
post has helped highlight that connection.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=301fac13-cb4c-4081-9985-559ca8fbe358" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Testing Container Configurations</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/12/21/TestingContainerConfigurations.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,a4a1141f-94ef-411c-8992-3fa8248ec4e4.aspx</id>
    <published>2011-12-21T14:25:32.8393239+01:00</published>
    <updated>2011-12-21T14:25:32.8393239+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="StructureMap" label="StructureMap" scheme="http://blog.ploeh.dk/CategoryView,category,StructureMap.aspx" />
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Here’s a question I often get:
</p>
        <blockquote>
          <p>
“Should I test my DI Container configuration?”
</p>
        </blockquote>
        <p>
The motivation for asking mostly seems to be that people want to know whether or not
their applications are correctly wired. That makes sense.
</p>
        <p>
A related question I also often get is whether or not a particular container has a
self-test feature? In this post I’ll attempt to answer both questions.
</p>
        <p>
          <strong>Container Self-testing</strong>
        </p>
        <p>
Some DI Containers have a method you can invoke to make it perform a consistency check
on itself. As an example, <a href="http://structuremap.net/structuremap/">StructureMap</a> has
the AssertConfigurationIsValid method that, according to documentation does “a full
environment test of the configuration of [the] container.” It will “try to create
every configured instance [...]”
</p>
        <p>
Calling the method is <em>really</em> easy:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">container.AssertConfigurationIsValid();</font>
          </pre>
        </div>
        <p>
Such a self-test can often be an expensive operation (not only for StructureMap, but
in general) because it’s basically attempting to create an instance of each and every
Service registered in the container. If the configuration is large, it’s going to
take some time, but it’s still going to be faster than performing a manual test of
the application.
</p>
        <p>
Two questions remain: Is it worth invoking this method? Why don’t all containers have
such a method?
</p>
        <blockquote>
          <p>
The quick answer is that such a method is close to worthless, which also explains
why many containers don’t include one.
</p>
        </blockquote>
        <p>
To understand the answer, consider the set of all components contained in the container
in this figure:
</p>
        <p>
          <a href="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/Testing-Container-Configurations_84D9/containersets_2.png">
            <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="containersets" border="0" alt="containersets" src="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/Testing-Container-Configurations_84D9/containersets_thumb.png" width="206" height="480" />
          </a>
        </p>
        <p>
The container contains the set of components IFoo, IBar, IBaz, Foo, Bar, Baz, and
Qux so a self-test will try to create a single instance of each of these seven types.
If all seven instances can be created, the test succeeds.
</p>
        <p>
All this accomplishes is to verify that the configuration is internally <em>consistent.</em> Even
so, an application could require instances of the ICorge, Corge or Grault types which
are completely external to the configuration, in which case resolution would fail.
</p>
        <p>
Even more subtly, resolution would also fail whenever the container is queried for
an instance of IQux, since this interface isn’t part of the configuration, even though
it’s related to the concrete Qux type which <em>is</em> registered in the container.
A self-test only verifies that the concrete Qux class can be resolved, but it never
attempts to create an instance of the IQux interface.
</p>
        <p>
In short, the fact that a container’s configuration is internally consistent doesn’t
guarantee that all services required by an application can be served.
</p>
        <p>
Still, you may think that at least a self-test can constitute an early warning system:
if the self-test fails, surely it must mean that the configuration is invalid? Unfortunately,
that’s not true either.
</p>
        <p>
If a container is being configured using Auto-registration/Convention over Configuration
to scan one or more assemblies and register certain types contained within, chances
are that ‘too many’ types will end up being registered – particularly if one or more
of these assemblies are reusable libraries (as opposed to application-specific assemblies).
Often, the number of redundant types added is negligible, but they <em>may</em> make
the configuration internally <em>inconsistent</em>. However, if the inconsistency
only affects the redundant types, it doesn’t matter. The container will still be able
to resolve <em>everything</em> the current application requires.
</p>
        <p>
Thus, a container self-test method is worthless.
</p>
        <p>
Then how can the container configuration be tested?
</p>
        <p>
          <strong>Explicit Testing of Container Configuration</strong>
        </p>
        <p>
Since a container self-test doesn’t achieve the desired goal, how can we ensure that
an application can be composed correctly?
</p>
        <p>
One option is to write an automated integration test (not a unit test) for each service
that the application requires. Still, if done manually, you run the risk of forgetting
to write a test for a specific service. A better option is to come up with a convention
so that you can identify <em>all</em> the services required by a specific application,
and then write a convention-based test to verify that the container can resolve them
all.
</p>
        <p>
Will this guarantee that the application can be correctly composed?
</p>
        <p>
No, it only guarantees that it can be composed – not that this composition is <em>correct.</em></p>
        <p>
Even when a composed instance can be created for each and every service, many things
may still be wrong:
</p>
        <ul>
          <li>
Composition is just plain wrong: 
<ul><li>
Decorators may be missing 
</li><li>
Decorators may have been added in the wrong order 
</li><li>
The wrong services are injected into consumers (this is more likely to happen when
you follow the <a href="http://codemanship.co.uk/parlezuml/blog/?postid=934">Reused
Abstractions Principle</a>, since there will be multiple concrete implementations
of each interface)</li></ul></li>
          <li>
Configuration values like connection strings and such are incorrect – e.g. while a
connection string is supplied to a constructor, it may not contain the correct values. 
</li>
          <li>
Even if <em>everything</em> is correctly composed, the run-time environment may prevent
the application from working. As an example, even if an injected connection string
is correct, there may not be any connection to the database due to network or security
misconfiguration.</li>
        </ul>
        <p>
In short, a <a href="http://xunitpatterns.com/Layer%20Test.html">Subcutaneous Test</a> or
full System Test is the only way to verify that <em>everything</em> is correctly wired.
However, if you have good test coverage at the unit test level, a series of <a href="http://xunitpatterns.com/Smoke%20Test.html">Smoke
Tests</a> is all that you need at the System Test level because in general you have
good reason to believe that all behavior is correct. The remaining question is whether
all this correct behavior can be correctly connected, and that tends to be an all-or-nothing
proposition.
</p>
        <p>
          <strong>Conclusion</strong>
        </p>
        <p>
While it would be possible to write a set of convention-based integration tests to
verify the configuration of a DI Container, the return of investment is too low since
it doesn’t remove the need for a set of Smoke Tests at the System Test level.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a4a1141f-94ef-411c-8992-3fa8248ec4e4" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Factory Overload</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/12/19/FactoryOverload.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,e942dc33-aa21-4818-85d3-2e5f64aa3977.aspx</id>
    <published>2011-12-19T14:04:55.0296041+01:00</published>
    <updated>2011-12-19T20:18:39.9899609+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Recently I received a question from <a href="http://kellabyte.com/">Kelly Sommers</a> about
good ways to refactor away from Factory Overload. Basically, she’s working in a code
base where there’s an explosion of <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract
Factories</a> which seems to be counter-productive. In this post I’ll take a look
at the example problem and propose a set of alternatives.
</p>
        <p align="left">
An <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract Factory</a> (and
its close relative Product Trader) can serve as a <a href="http://stackoverflow.com/questions/2280170/why-do-we-need-abstract-factory-design-pattern/2280289#2280289">solution
to various challenges</a> that come up when writing loosely coupled code (chapter
6 of <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my book</a> describes
the most common scenarios). However, introducing an Abstract Factory may be a <a href="http://en.wikipedia.org/wiki/Leaky_abstraction">leaky
abstraction</a>, so don’t do it blindly. For example, an Abstract Factory is <a href="http://stackoverflow.com/questions/4648318/dependency-injection-new-instance-required-in-several-of-a-classes-methods/4650050#4650050">rarely
the best approach to address lifetime management concerns</a>. In other words, the
Abstract Factory has to make sense as a pure model element.
</p>
        <p align="left">
That’s not the case in the following example.
</p>
        <p align="left">
          <strong>Problem Statement</strong>
        </p>
        <p align="left">
The question centers around a code base that integrates with a database closely guarded
by DBA police. Apparently, every single database access must happen through a set
of <em>very</em> fine-grained stored procedures.
</p>
        <p align="left">
For example, to update the first name of a user, a set of stored procedures exist
to support this scenario, <em>depending on the context of the current application
user:</em></p>
        <table border="1" cellspacing="0" cellpadding="2" width="400">
          <tbody>
            <tr>
              <td valign="top" width="135">
                <strong>User type</strong>
              </td>
              <td valign="top" width="146">
                <strong>Stored procedure</strong>
              </td>
              <td valign="top" width="117">
                <strong>Parameter name</strong>
              </td>
            </tr>
            <tr>
              <td valign="top" width="135">
Admin</td>
              <td valign="top" width="157">
update_admin_firstname</td>
              <td valign="top" width="148">
adminFirstName</td>
            </tr>
            <tr>
              <td valign="top" width="135">
Guest</td>
              <td valign="top" width="157">
update_guest_firstname</td>
              <td valign="top" width="148">
guestFirstName</td>
            </tr>
            <tr>
              <td valign="top" width="135">
Regular</td>
              <td valign="top" width="157">
update_regular_firstname</td>
              <td valign="top" width="148">
regularFirstName</td>
            </tr>
            <tr>
              <td valign="top" width="135">
Restricted</td>
              <td valign="top" width="157">
update_restricted_firstname</td>
              <td valign="top" width="148">
restrictedFirstName</td>
            </tr>
          </tbody>
        </table>
        <p>
As this table demonstrates, not only is there a stored procedure for each user context,
but the parameter name differs as well. However, in this particular case it <em>seems</em> as
though there’s a pattern to the names.
</p>
        <blockquote>
          <p>
If this pattern is consistent, I think the easiest way to address these variations
would be to algorithmically build the strings from a couple of templates.
</p>
        </blockquote>
        <p>
However, this is not the route taken by Kelly’s team, so I assume that things are
more complicated than that; apparently, a templated approach is not viable, so for
the rest of  this article I’m going to assume that it’s necessary to write at
least <em>some</em> code to address each case individually.
</p>
        <p>
The current solution that Kelly’s team has implemented is to use an Abstract Factory
(Product Trader) to translate the user type into an appropriate IUserFirstNameModifier
instance. From the consuming code, it looks like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> modifier
= factory.Create(<span style="color: "><font color="#2b91af">UserTypes</font></span>.Admin);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">modifier.Commit(<span style="color: "><font color="#a31515">"first"</font></span>);</font>
          </pre>
        </div>
        <p>
where the factory variable is an instance of the IUserFirstNameModifierFactory interface.
This is certainly loosely coupled, but looks like a leaky abstraction. Why is a factory
needed? It seems that its single responsibility is to translate a UserTypes instance
(an enum) into an IUserFirstNameModifier. There’s a code smell buried here – try to
spot it before you read on :)
</p>
        <p>
          <strong>Proposed Solution</strong>
        </p>
        <p>
Kelly herself suggests an alternative involving a concrete Builder which can create
instances of a single concrete UserFirstNameModifier with or without an implicit conversion:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
Implicit conversion.</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">UserFirstNameModifier</font>
              </font>
            </span>
            <font style="font-size: 10pt"> modifier1
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
builder.WithUserType(<span style="color: "><font color="#2b91af">UserTypes</font></span>.Guest);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
Without implicit conversion.</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> modifier2
= builder</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.WithUserType(<span style="color: "><font color="#2b91af">UserTypes</font></span>.Restricted)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.Create();</font>
          </pre>
        </div>
        <p>
While this may seem to reduce the number of classes involved, it has several drawbacks:
</p>
        <ul>
          <li>
First of all, the Fluent Builder pattern implies that you can forgo invoking any of
the WithXyz methods (WithUserType) and just accept all the default values encapsulated
in the builder. This again implies that there’s a default user type, which may or
may not make sense in that particular domain. Looking at Kelly’s code, UserTypes is
an enum (and thus has a default value), so if WithUserType isn’t invoked, the Create
method defaults to UserTypes.Admin. That’s a bit too implicit for my taste. 
</li>
          <li>
Since all involved classes are now concrete, the proposed solution isn’t extensibile
(and by corollary hard to unit test). 
</li>
          <li>
The builder is essentially a big switch statement.</li>
        </ul>
        <p>
Both the current implementation and the proposed solution involves passing an enum
as a method parameter to a different class. If you’ve read and memorized <a href="http://www.amazon.com/gp/product/0201485672/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0201485672">Refactoring</a> you
should by now have recognized both a code smell and the remedy.
</p>
        <p>
          <strong>Alternative 1a: Make UserType Polymorphic</strong>
        </p>
        <p>
The code smell is <a href="http://c2.com/cgi/wiki?FeatureEnvySmell">Feature Envy</a> and
a possible refactoring is to <a href="http://martinfowler.com/refactoring/catalog/replaceTypeCodeWithStateStrategy.html">replace
the enum with a Strategy</a>. In order to do that, an IUserType interface is introduced:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IUserType</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IUserFirstNameModifer</font></span> CreateUserFirstNameModifier();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Usage becomes as simple as this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> modifier
= userType.CreateUserFirstNameModifier();</font>
          </pre>
        </div>
        <p>
Obviously, more methods can be added to IUserType to support other update operations,
but care should be taken to avoid creating a <a href="http://martinfowler.com/bliki/HeaderInterface.html">Header
Interface</a>.
</p>
        <p>
While this solution is much more object-oriented, I’m still not quite happy with it,
because apparently, the context is a <a href="http://abdullin.com/cqrs">CQRS</a> style
architecture. Since an update operation is essentially a Command, then why model the
implementation along the lines of a Query? Both Abstract Factory and Factory Method
patterns represent Queries, so it seems redundant in this case. It should be possible
to apply the <a href="http://en.wikipedia.org/wiki/Hollywood_principle_%28computer_programming%29">Hollywood
Principle</a> here.
</p>
        <p>
          <strong>Alternative 1b: Tell, Don’t Ask</strong>
        </p>
        <p>
Why have the user type <em>return</em> an modifier? Why can’t it perform the update
itself? The IUserType interface should be changed to something like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IUserType</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> CommitUserFirtName(<span style="color: "><font color="#0000ff">string</font></span> firstName);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This makes it easier for the consumer to commit the user’s first name because it can
be done directly on the IUserType instance instead of first creating the modifier.
</p>
        <p>
It also makes it much easier to unit test the consumer because there’s no longer a
mix of Command and Queries within the same method. From <a href="http://www.amazon.com/gp/product/0321503627/ref=as_li_ss_tl?ie=UTF8&amp;tag=ploeh-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321503627">Growing
Object-Oriented Software</a> we know that Queries should be modeled with <a href="http://xunitpatterns.com/Test%20Stub.html">Stubs</a> and
Commands with <a href="http://xunitpatterns.com/Mock%20Object.html">Mocks</a>, and
if you’ve ever tried mixing the two you know that it’s a sort of interaction that
should be minimized.
</p>
        <p>
          <strong>Alternative 2a: Distinguish by Type</strong>
        </p>
        <p>
While I personally like alternative 1b best, it may not be practical in all situations,
so it’s always valuable to examine other alternatives.
</p>
        <p>
The root cause of the problem is that there’s a lot of stored procedures. I want to
reiterate that I still think that the absolutely easiest solution would be to generate
a SqlCommand from a string template, but given that this article assumes that this
isn’t possible or desirable, it follows that code must be written for each stored
procedure.
</p>
        <p>
Why not simply define an interface for each one? As an example, to update the user’s
first name in the context of being an ‘Admin’ user, this <a href="http://martinfowler.com/bliki/RoleInterface.html">Role
Interface</a> can be used:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IUserFirstNameAdminModifier</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Commit(<span style="color: "><font color="#0000ff">string</font></span> firstName);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Similar interfaces can be defined for the other user types, such as IUserFirstNameRestrictedModifier,
IUserFirstNameGuestModifier and so on.
</p>
        <p>
This is a very simple solution; it’s easy to implement, but risks violating the <a href="http://codemanship.co.uk/parlezuml/blog/?postid=934">Reused
Abstractions Principle</a> (RAP).
</p>
        <p>
          <strong>Alternative 2b: Distinguish by Generic Type</strong>
        </p>
        <p>
The problem with introducing interfaces like IUserFirstNameAdminModifier, IUserFirstNameRestrictedModifier,
IUserFirstNameGuestModifier etc. is that they differ only by name. The Commit method
is the same for all these interfaces, so this seems to violate the RAP. It’d be better
to merge all these interfaces into a single interface, which is what Kelly’s team
is currently doing. However, the problem with this is that the type carries no information
about the <em>role</em> that the modifier is playing.
</p>
        <p>
Another alternative is to turn the modifier interface into a generic interface like
this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">IUserFirstNameModifier</font>
              </span>&lt;T&gt; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">where</font></span> T
: </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IUserType</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Commit(<span style="color: "><font color="#0000ff">string</font></span> firstName);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The IUserType is a <a href="http://en.wikipedia.org/wiki/Marker_interface_pattern">Marker
Interface</a>, so .NET purists are not going to like this solution, since <a href="http://msdn.microsoft.com/en-us/library/ms229022.aspx">the
.NET Type Design Guidelines recommend against using Marker Interfaces</a>. However,
it’s impossible to constrain a generic type argument against an attribute, so the
party line solution is out of the question.
</p>
        <p>
This solution ensures that consumers can now have dependencies on IUserFirstNameModifier&lt;AdminUserType&gt;,
IUserFirstNameModifier&lt;RestrictedUserType&gt;, etc.
</p>
        <p>
However, the need for a marker interface gives off another odeur.
</p>
        <p>
          <strong>Alternative 3: Distinguish by Role</strong>
        </p>
        <p>
The problem at the heart of alternative 2 is that it attempts to use the <em>type</em> of
the interfaces as an indicator of the roles that Services play. It’s seems that making
the type distinct works against the RAP, but when the RAP is applied, the type becomes
ambiguous.
</p>
        <p>
However, as <a href="http://www.tedneward.com/">Ted Neward</a><a href="http://msdn.microsoft.com/en-us/magazine/hh205754.aspx">points
out</a> in his excellent series on <a href="http://msdn.microsoft.com/en-us/magazine/ff955611.aspx">Multiparadigmatic
.NET</a>, the type is only one axis of variability among many. Perhaps, in this case,
it may be much easier to use the <em>name</em> of the dependency to communicate its
role instead of the type.
</p>
        <p>
Given a single, ambiguous IUserFirstNameModifier interface (just as in the original
problem statement), a consumer can distinguish between the various roles of modifiers
by their names:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">partial</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">SomeConsumer</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IUserFirstNameModifier</font></span> adminModifier;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IUserFirstNameModifier</font></span> guestModifier;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> SomeConsumer(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">IUserFirstNameModifier</font></span> adminModifier,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">IUserFirstNameModifier</font></span> guestModifier)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.adminModifier
= adminModifier;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.guestModifier
= guestModifier;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> DoSomething()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (<span style="color: "><font color="#0000ff">this</font></span>.UseAdmin)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.adminModifier.Commit(<span style="color: "><font color="#a31515">"first"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">else</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.guestModifier.Commit(<span style="color: "><font color="#a31515">"first"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Now it’s entirely up to the <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">Composition
Root</a> to compose SomeConsumer with the correct modifiers, and while this can be
done manually, it’s an excellent case for a DI Container and a bit of Convention over
Configuration.
</p>
        <p>
          <strong>Conclusion</strong>
        </p>
        <p>
I’m sure that if I’d spent more time analyzing the problem I could have come up with
more alternatives, but this post is becoming long enough already.
</p>
        <p>
Of the alternatives I’ve suggested here, I prefer 1b or 3, depending on the exact
requirements.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=e942dc33-aa21-4818-85d3-2e5f64aa3977" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Polymorphic Consistency</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/12/07/PolymorphicConsistency.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,1c3204f4-a6d3-48f1-aa97-42f4dc1aaec0.aspx</id>
    <published>2011-12-07T09:40:21.2977102+01:00</published>
    <updated>2011-12-07T09:40:21.2977102+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Asynchronous message passing combined with <a href="http://en.wikipedia.org/wiki/Eventual_consistency">eventual
consistency</a> makes it possible to build very scalable systems. However, sometimes
eventual consistency isn’t appropriate in parts of the system, while it’s acceptable
in other parts. How can a consistent architecture be defined to fit both <a href="http://en.wikipedia.org/wiki/ACID">ACID</a> and
eventual consistency? This article provides an answer.
</p>
        <p>
          <strong>The case of an online game</strong>
        </p>
        <p>
Last week I visited <a href="http://pixelpandemic.net/">Pixel Pandemic</a>, a company
that produces browser-based <a href="http://en.wikipedia.org/wiki/Massively_multiplayer_online_role-playing_game">MMORPGs</a>.
Since each game world has lots of players who can all potentially interact with each
other, scalability is very important.
</p>
        <p>
In traditional line of business applications, eventual consistency is often an excellent
fit because the application is a projection of the real world. My favorite example
is an inventory system: it models what’s going on in one or more physical warehouses,
but the real world is the ultimate source of truth. A warehouse worker might accidentally
drop and damage some of the goods, in which case the application must adjust <em>after
the fact</em>.
</p>
        <p>
In other words, the information contained within line of business applications tend
to lag after the real world. It’s impossible to guarantee that the application is
always consistent with the real world, so eventual consistency is a natural fit.
</p>
        <p>
That’s not the case with an online game world. The game world itself is the source
of truth, and it must be internally consistent at all times. As an example, in <a href="http://www.zombiepandemic.com/">Zombie
Pandemic</a>, players fight against zombies and may take damage along the way. Players
can heal themselves, but they would prefer (I gather) that the healing action takes
place immediately, and not some time in the future where the character might be dead.
Similarly, when a player hits a zombie, they’d prefer to apply the damage immediately.
(However, I think that even here, eventual consistency might provide some interesting
game mechanics, but that’s another discussion.)
</p>
        <p>
While discussing these matters with the nice people in Pixel Pandemic, it turned out
that while some parts of the game world have to be internally consistent, it’s perfectly
acceptable to use eventual consistency in other cases. One example is the game’s high
score table. While a single player should have a consistent view of his or her own
score, it’s acceptable if the high score table lags a bit.
</p>
        <p>
At this point it seemed clear that this particular online game could use an appropriate
combination of ACID and eventual consistency, and I think this conclusion can be generalized.
The question now becomes: how can a consistent architecture encompass both types of
consistency?
</p>
        <p>
          <strong>Problem statement</strong>
        </p>
        <p>
With the above example scenario in mind the problem statement can be generalized:
</p>
        <blockquote>
          <p>
Given that an application should apply a mix of ACID and eventual consistency, how
can a consistent architecture be defined?
</p>
        </blockquote>
        <p>
Keep in mind that ACID consistency implies that all writes to a transactional resource
must take place as a blocking method call. This seems to be at odds with the concept
of asynchronous message passing that works so well with eventual consistency.
</p>
        <p>
However, an application architecture where blocking ACID calls are fundamentally different
than asynchronous message passing isn’t really an architecture at all. Developers
will have to decide up-front whether or not a given operation is or isn’t synchronous,
so the ‘architecture’ offers little implementation guidance. The end result is likely
to be a heterogeneous mix of Services, Repositories, Units of Work, Message Channels,
etc. A uniform principle will be difficult to distill, and the whole thing threatens
to devolve into <a href="http://en.wikipedia.org/wiki/Spaghetti_code">Spaghetti Code</a>.
</p>
        <p>
The solution turns out to be not at all difficult, but it requires that we invert
our thinking a bit. Most of us tend to think about synchronous code first. When we
think about code performing synchronous work it seems difficult (perhaps even impossible)
to retrofit asynchrony to that model. On the other hand, the converse isn’t true.
</p>
        <blockquote>
          <p>
Given an asynchronous API, it’s trivial to provide a synchronous, blocking implementation.
</p>
        </blockquote>
        <p>
Adopting an architecture based on asynchronous message passing (the <a href="http://eaipatterns.com/PipesAndFilters.html">Pipes
and Filters</a> architecture) enables both scenarios. Eventual consistency can be
achieved by passing messages around on persistent queues, while ACID consistency can
be achieved by handling a message in a blocking call that enlists a (potentially distributed)
transaction.
</p>
        <p>
An example seems to be in order here.
</p>
        <p>
          <strong>Example: keeping score</strong>
        </p>
        <p>
In the online game world, each player accumulates a score based on his or her actions.
From the perspective of the player, the score should always be consistent. When you
defeat the zombie boss, you want to see the result in your score right away. That
sounds an awful lot like the Player is an Aggregate Root and the score is part of
that Entity. ACID consistency is warranted whenever the Player is updated.
</p>
        <p>
On the other hand, each time a score changes it may influence the high score table,
but this doesn’t need to be ACID consistent; eventual consistency is fine in this
case.
</p>
        <p>
Once again, polymorphism comes to the rescue.
</p>
        <p>
Imagine that the application has a GameEngine class that handles updates in the game.
Using an injected IChannel&lt;PointsChangedEvent&gt; it can update the score for a
player as simple as this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">/*
Lots of other interesting things happen</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">   
* here, like calculating the new score... */</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> cmd
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ScoreChangedEvent</font></span>(<span style="color: "><font color="#0000ff">this</font></span>.playerId,
score);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">this</font>
              </font>
            </span>
            <font style="font-size: 10pt">.pointsChannel.Send(cmd);</font>
          </pre>
        </div>
        <p>
The Send method returns void, so it’s a good example of a naturally asynchronous API.
However, the implementation must do two things:
</p>
        <ul>
          <li>
Update the Player Aggregate Root in a transaction 
</li>
          <li>
Update the high score table (eventually)</li>
        </ul>
        <p>
That’s two different types of consistency within the same method call.
</p>
        <p>
The first step to enable this is to employ the trusty old <a href="http://en.wikipedia.org/wiki/Composite_pattern">Composite</a> design
pattern:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">CompositeChannel</font>
              </span>&lt;T&gt;
: <span style="color: "><font color="#2b91af">IChannel</font></span>&lt;T&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#2b91af">IChannel</font></span>&lt;T&gt;&gt;
channels;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> CompositeChannel(<span style="color: "><font color="#0000ff">params</font></span><span style="color: "><font color="#2b91af">IChannel</font></span>&lt;T&gt;[]
channels)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.channels
= channels;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Send(T
message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">foreach</font></span> (<span style="color: "><font color="#0000ff">var</font></span> c <span style="color: "><font color="#0000ff">in</font></span><span style="color: "><font color="#0000ff">this</font></span>.channels)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
c.Send(message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
With a Composite channel it’s possible to compose a polymorphic mix of IChannel&lt;T&gt;
implementations, some blocking and some asynchronous.
</p>
        <p>
          <strong>ACID write</strong>
        </p>
        <p>
To update the Player Aggregate Root a simple <a href="http://en.wikipedia.org/wiki/Adapter_pattern">Adapter</a> writes
the event to a persistent data store. This could be a relational database, a document
database, a REST resource or something else – it doesn’t really matter exactly which
technology is used.
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">PlayerStoreChannel</font>
              </span> : </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IChannel</font></span>&lt;<span style="color: "><font color="#2b91af">ScoreChangedEvent</font></span>&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IPlayerStore</font></span> store;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> PlayerStoreChannel(<span style="color: "><font color="#2b91af">IPlayerStore</font></span> store)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.store
= store;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Send(<span style="color: "><font color="#2b91af">ScoreChangedEvent</font></span> message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.store.Save(message.PlayerId,
message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The important thing to realize is that the IPlayerStore.Save method will be a blocking
method call – perhaps wrapped in a distributed transaction. This ensures that updates
to the Player Aggregate Root always leave the data store in a consistent state. Either
the operation succeeds or it fails during the method call itself.
</p>
        <p>
This takes care of the ACID consistent write, but the application must also update
the high score table.
</p>
        <p>
          <strong>Asynchronous write</strong>
        </p>
        <p>
Since eventual consistency is acceptable for the high score table, the message can
be transmitted over a persistent queue to be picked up by a background process.
</p>
        <p>
A generic class can server as an Adapter over an IQueue abstraction:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">QueueChannel</font>
              </span>&lt;T&gt;
: <span style="color: "><font color="#2b91af">IChannel</font></span>&lt;T&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IQueue</font></span> queue;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IMessageSerializer</font></span> serializer;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> QueueChannel(<span style="color: "><font color="#2b91af">IQueue</font></span> queue,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">IMessageSerializer</font></span> serializer)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.queue
= queue;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.serializer
= serializer;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Send(T
message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.queue.Enqueue(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.serializer.Serialize(message));</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Obvously, the Enqueue method is another void method. In the case of a persistent queue,
it’ll block while the message is being written to the queue, but that will tend to
be a fast operation.
</p>
        <p>
          <strong>Composing polymorphic consistency</strong>
        </p>
        <p>
Now all the building blocks are available to compose both channel implementations
into the GameEngine via the CompositeChannel. That might look like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> playerConnString
= </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">ConfigurationManager</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.ConnectionStrings[<span style="color: "><font color="#a31515">"player"</font></span>].ConnectionString;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> gameEngine
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">GameEngine</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">CompositeChannel</font></span>&lt;<span style="color: "><font color="#2b91af">ScoreChangedEvent</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">PlayerStoreChannel</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">DbPlayerStore</font></span>(playerConnString)),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">QueueChannel</font></span>&lt;<span style="color: "><font color="#2b91af">ScoreChangedEvent</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">PersistentQueue</font></span>(<span style="color: "><font color="#a31515">"messageQueue"</font></span>),                        </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">JsonSerializer</font></span>())));</font>
          </pre>
        </div>
        <p>
When the Send method is invoked on the channel, it’ll first invoke a blocking call
that ensures ACID consistency for the Player, followed by asynchronous message passing
for eventual consistency in other parts of the application.
</p>
        <p>
          <strong>Conclusion</strong>
        </p>
        <p>
Even when parts of an application must be implemented in a synchronous fashion to
ensure ACID consistency, an architecture based on asynchronous message passing provides
a flexible foundation that enables you to polymorphically mix both kinds of consistency
in a single method call. From the perspective of the application layer, this provides
a consistent and uniform architecture because all mutating actions are modeled as
commands end events encapsulated in messages.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1c3204f4-a6d3-48f1-aa97-42f4dc1aaec0" />
      </div>
    </content>
  </entry>
  <entry>
    <title>TDD improves reusability</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/11/10/TDDImprovesReusability.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,f3355b05-3604-460f-9520-edc1d0384e64.aspx</id>
    <published>2011-11-10T17:55:10.7798465+01:00</published>
    <updated>2011-11-10T17:55:10.7798465+01:00</updated>
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
There’s this meme going around that software <a href="http://www.udidahan.com/2009/06/07/the-fallacy-of-reuse/">reuse
is a fallacy</a>. Bollocks! The <em>reuse is a fallacy meme</em> is a fallacy :) To
be fair, I’m not claiming that everything can and should be reused, but my claim is
that all code produced by Test-Driven Development (TDD) is being reused. Here’s why:
</p>
        <p>
When tests are written first, they act as a kind of <a href="http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop">REPL</a>.
Tests tease out the API of the <a href="http://xunitpatterns.com/SUT.html">SUT</a>,
as well as its behavior. In this point in the development process, the tests serve
as a feedback mechanism. Only later, when the tests and the SUT stabilize, will the
tests be repurposed (dare I say ‘reused’?) as regression tests. In other words: over
time, tests written during TDD have more than one role:
</p>
        <ol>
          <li>
Feedback mechanism 
</li>
          <li>
Regression test</li>
        </ol>
        <p>
Each test plays one of these roles at a time, but not both.
</p>
        <p>
While the purpose of TDD is to evolve the SUT, the process produces two types of artifacts:
</p>
        <ol>
          <li>
Tests 
</li>
          <li>
Production code</li>
        </ol>
        <p>
Notice how the tests appear <em>before</em> the production code, which is an artifact
of the test code.
</p>
        <blockquote>
          <p>
The unit tests are the <em>first</em> client of the production API.
</p>
        </blockquote>
        <p>
When the production code is composed into an application, that application becomes
the <em>second</em> client, so it <em>reuses</em> the API. This is a very beneficial
effect of TDD, and probably one of the main reasons why TDD, if done correctly, produces
code of high quality.
</p>
        <p>
A colleague once told me (when referring to scale-out) that the hardest step is to
go from one server to two servers, and I’ve later found that principle to apply much
more broadly. Generalizing from a single case to two distinct cases is often the hardest
step, and it becomes much easier to generalize further from two to an arbitrary number
of cases.
</p>
        <p>
This explains why TDD is such an efficient process. Apart from the beneficial side
effect of producing a regression test suite, it also ensures that at the time the
API goes into production, it’s already being shared (or reused) between at least two
distinct clients. If, at a later time, it becomes necessary to add a third client,
the hard part is already done.
</p>
        <p>
TDD produces reusable code because the production application reuses the API which
were realized by the tests.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f3355b05-3604-460f-9520-edc1d0384e64" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Independency</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/11/08/Independency.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,b8651f8b-647f-4769-bdb1-22965b5bb719.aspx</id>
    <published>2011-11-08T16:29:05.5439755+01:00</published>
    <updated>2011-11-08T16:29:05.5439755+01:00</updated>
    <category term="Miscellaneous" label="Miscellaneous" scheme="http://blog.ploeh.dk/CategoryView,category,Miscellaneous.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Now that <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my book</a> about
Dependency Injection is out, it’s only fitting that I also invert my own dependencies
by striking out as an independent consultant/advisor. In the future I’m hoping to
combine my writing and speaking efforts, as well as my open source interests, with
helping out clients write better code.
</p>
        <p>
If you’d like to get help with Dependency Injection or Test-Driven Development, SOLID,
API design, application architecture or one of the other topics I regularly cover
here on my blog, I’m available as a consultant worldwide.
</p>
        <p>
When it comes to Windows Azure, I’ll be renewing my alliance with my penultimate employer <a href="http://www.commentor.dk/">Commentor</a>,
so you can also hire me as part of larger deal with Commentor.
</p>
        <p>
In case you are wondering what happened to <a href="http://blog.ploeh.dk/2011/08/01/JoiningAppHarbor.aspx">my
employment with AppHarbor</a>, I resigned from my position there because I couldn’t
make it work with all the other things I also would like to do. I still think <a href="http://appharbor.com">AppHarbor</a> is
a very interesting project, and I wish my former employers the best of luck with their
endeavor.
</p>
        <p>
This has been a message from the blog’s sponsor (myself). Soon, regular content will
resume.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b8651f8b-647f-4769-bdb1-22965b5bb719" />
      </div>
    </content>
  </entry>
  <entry>
    <title>SOLID concrete</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/10/25/SOLIDConcrete.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,d3e2aaa7-be82-4755-a646-dbd18965f2cb.aspx</id>
    <published>2011-10-25T17:01:15.1034902+02:00</published>
    <updated>2011-10-25T17:01:15.1034902+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="https://twitter.com/#!/gregyoung">Greg Young</a> gave a talk at <a href="http://gotocon.com//aarhus-2011/">GOTO
Aarhus 2011</a> titled <a href="http://gotocon.com/aarhus-2011/presentation/Developers%20have%20a%20mental%20disorder">Developers
have a mental disorder</a>, which was (semi-)humorously meant, but still addressed
some very real concerns about the cognitive biases of software developers as a group.
While I have no intention to provide a complete resume of the talk, Greg said one
thing that made me think a bit (more) about SOLID code. To paraphrase, it went something
like this:
</p>
        <blockquote>
          <p>
Developers have a tendency to attempt to solve specific problems with general solutions.
This leads to coupling and complexity. Instead of being general, code should be specific.
</p>
        </blockquote>
        <p>
This sounds correct at first glance, but once again I think that SOLID code offers
a solution. Due to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> each SOLID concrete (pardon the pun) class will tend
to very specifically address a very narrow problem.
</p>
        <p>
Such a class may <em>implement</em> one (or more) general-purpose interface(s), but
the concrete type is specific.
</p>
        <p>
The difference between the generality of an interface and the specificity of a concrete
type becomes more and more apparent the better a code base applies the <a href="http://codemanship.co.uk/parlezuml/blog/?postid=934">Reused
Abstractions Principle</a>. This is best done by defining an API in terms of <a href="http://martinfowler.com/bliki/RoleInterface.html">Role
Interfaces</a>, which makes it possible to define a few core abstractions that apply
very broadly, while implementations are very specific.
</p>
        <p>
As an example, consider <a href="http://autofixture.codeplex.com/">AutoFixture</a>’s
ISpecimenBuilder interface. This is a very central interface in AutoFixture (in fact,
I don’t even know just how many implementations it has, and I’m currently too lazy
to count them). As an API, it has proven to be very generally useful, but each concrete
implementation is still very specific, like the CurrentDateTimeGenerator shown here:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">CurrentDateTimeGenerator</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">ISpecimenBuilder</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">object</font></span> Create(<span style="color: "><font color="#0000ff">object</font></span> request, </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">ISpecimenContext</font></span> context)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (request
!= <span style="color: "><font color="#0000ff">typeof</font></span>(<span style="color: "><font color="#2b91af">DateTime</font></span>))</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">NoSpecimen</font></span>(request);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#2b91af">DateTime</font></span>.Now;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This is, literally, the entire implementation of the class. I hope we can agree that
it’s very specific.
</p>
        <p>
In my opinion, SOLID is a set of principles that can help us keep an API general while
each implementation is very specific.
</p>
        <p>
In SOLID code all concrete types are specific.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d3e2aaa7-be82-4755-a646-dbd18965f2cb" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Checking for exactly one item in a sequence using C# and F#</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/10/11/CheckingForExactlyOneItemInASequenceUsingCAndF.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,976bd91f-008d-46c7-90b7-080f76d07be2.aspx</id>
    <published>2011-10-11T16:36:03.4282983+02:00</published>
    <updated>2011-10-11T16:36:03.4282983+02:00</updated>
    <category term="Languages" label="Languages" scheme="http://blog.ploeh.dk/CategoryView,category,Languages.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Here’s a programming issue that comes up from time to time. A method takes a sequence
of items as input, like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> Route(<span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;
args)</font>
          </pre>
        </div>
        <p>
While the signature of the method may be given, the <em>implementation</em> may be
concerned with finding out whether there is exactly <em>one</em> element in the sequence.
(I’d argue that this would be a violation of the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov
Substitution Principle</a>, but that’s another discussion.) By corollary, we might
also be interested in the result sets on each side of that single element: no elements
and multiple elements.
</p>
        <p>
Let’s assume that we’re required to raise the appropriate event for each of these
three cases.
</p>
        <p>
          <strong>Naïve approach in C#</strong>
        </p>
        <p>
A naïve implementation would be something like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> Route(<span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;
args)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> countCategory
= args.Count();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">switch</font></span> (countCategory)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">case</font></span> 0:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.RaiseNoArgument();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">case</font></span> 1:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.RaiseSingleArgument(args.Single());</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">default</font></span>:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.RaiseMultipleArguments(args);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
However, the problem with that is that IEnumerable&lt;string&gt; carries no guarantee
that the sequence will ever end. In fact, there’s a whole category of implementations
that keep iterating forever – these are called <a href="http://en.wikipedia.org/wiki/Generator_%28computer_science%29">Generators</a>.
If you pass a Generator to the above implementation, it will never return because
the Count method will block forever.
</p>
        <p>
          <strong>Robust implementation in C#</strong>
        </p>
        <p>
A better solution comes from the realization that we’re only interested in knowing
about which of the three categories the input matches: No elements, a single element,
or multiple elements. The last case is covered if we find at least two elements. In
other words, we don’t have to read more than <em>at most two</em> elements to figure
out the category. Here’s a more robust solution:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> Route(<span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;
args)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> countCategory
= args.Take(2).Count();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">switch</font></span> (countCategory)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">case</font></span> 0:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.RaiseNoArgument();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">case</font></span> 1:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.RaiseSingleArgument(args.Single());</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">default</font></span>:</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.RaiseMultipleArguments(args);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Notice the inclusion of the Take(2) method call, which is the only difference from
the first attempt. This will give us <em>at most two</em> elements that we can then
count with the Count method.
</p>
        <p>
While this is better, it still annoys me that it’s necessary with a secondary LINQ
call (to the Single method) to extract that single element. Not that it’s particularly
inefficient, but it still <em>feels</em> like I’m repeating myself here.
</p>
        <p>
(We could also have converted the Take(2) iterator into an array, which would have
enabled us to query its Length property, as well as index into it to get the single
value, but it basically amounts to the same work.)
</p>
        <p>
          <strong>Implementation in F#</strong>
        </p>
        <p>
In F# we can implement the same functionality in a much more compact manner, taking
advantage of pattern matching against native F# lists:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">member</font>
              </font>
            </span>
            <font style="font-size: 10pt"> this.Route
args =</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">let</font></span> atMostTwo
= args |&gt; Seq.truncate 2 |&gt; Seq.toList</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">match</font></span> atMostTwo </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">with</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
| [] <span style="color: "><font color="#0000ff">-&gt;</font></span> onNoArgument.Trigger(Unit.Default)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
| [arg] <span style="color: "><font color="#0000ff">-&gt;</font></span> onSingleArgument.Trigger(arg)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
| _ <span style="color: "><font color="#0000ff">-&gt;</font></span> onMultipleArguments.Trigger(args)</font>
          </pre>
        </div>
        <p>
The first thing happening here is that the input is being piped through a couple of
functions. The truncate method does the same thing as the Take LINQ method does, and
the toList method subsequently converts that sequence of at most two elements into
a native F# list.
</p>
        <p>
The beautiful thing about native F# lists is that they support pattern matching, so
instead of first figuring out in which category the input belongs, and then subsequently
extract the data in the single element case, we can match and forward the element
in a single statement.
</p>
        <p>
Why is this important? I don’t know… it’s just satisfying on an aesthetic level :)
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=976bd91f-008d-46c7-90b7-080f76d07be2" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Weakly-typed versus Strongly-typed Message Channels</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/09/23/WeaklytypedVersusStronglytypedMessageChannels.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,c256a22e-65a5-430a-9166-0d5619811236.aspx</id>
    <published>2011-09-23T11:08:53.5648702+02:00</published>
    <updated>2011-09-23T11:08:53.5648702+02:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Soon after I posted my previous blog post on <a href="http://blog.ploeh.dk/2011/09/19/MessageDispatchingWithoutServiceLocation.aspx">message
dispatching without Service Location</a> I received an email from Jeff Saunders with
some great observations. Jeff has been so kind to allow me to quote his email here
on the blog, so here it is:
</p>
        <blockquote>
          <p>
“I enjoyed your latest blog post about message dispatching. I have to ask, though:
why do we want weakly-typed messages? Why can't we just inject an appropriate IConsumer&lt;T&gt;
into our services - they know which messages they're going to send or receive.
</p>
          <p>
“A really good example of this is ISubject&lt;T&gt; from Rx. It implements both IObserver&lt;T&gt;
(a message consumer) and IObservable&lt;T&gt; (a message producer) and the default
implementation Subject&lt;T&gt; routes messages directly from its IObserver side to
its IObservable side. 
</p>
          <p>
“We can use this with DI quite nicely - I have written an example in .NET Pad: <a href="http://dotnetpad.net/ViewPaste/woTkGk6_GEq3P9xTVEJYZg#c9,c26,">http://dotnetpad.net/ViewPaste/woTkGk6_GEq3P9xTVEJYZg#c9,c26,</a></p>
          <p>
“The good thing about this is that we now have access to all of the standard LINQ
query operators and the new ones added in Rx, so we can use a select query to map
messages between layers, for instance.
</p>
          <p>
“This way we get all the benefits of a weakly-typed IChannel interface, with the added
advantages of strong typing for our messages and composability using Rx.
</p>
          <p>
“One potential benefit of weak typing that could be raised is that we can have just
a single implementation for IChannel, instead of an ISubject&lt;T&gt; for each message
type. I don't think this is really a benefit, though, as we may want different propagation
behaviour for each message type - there are other implementations of ISubject&lt;T&gt;
that call consumers asynchronously, and we could pass any IObservable&lt;T&gt; or
IObserver&lt;T&gt; into a service for testing purposes.”
</p>
        </blockquote>
        <p>
These are great observations and I think that Rx holds much promise in this space.
Basically you can say that in <a href="http://abdullin.com/cqrs">CQRS</a>-style architectures
we’re already pushing events (and commands) around, so why not build upon what the
framework offers?
</p>
        <p>
Even if you find the <a href="http://msdn.microsoft.com/en-us/library/dd783449.aspx">IObserver&lt;T&gt;</a> interface
a bit too clunky with its <a href="http://msdn.microsoft.com/en-us/library/dd782792.aspx">OnNext</a>, <a href="http://msdn.microsoft.com/en-us/library/dd781657.aspx">OnError</a> and <a href="http://msdn.microsoft.com/en-us/library/dd782982.aspx">OnCompleted</a> methods
compared to the strongly typed IConsumer&lt;T&gt; interface, the question still remains:
why do we want weakly-typed messages?
</p>
        <p>
We don’t, necessarily. My previous post wasn’t meant as a particular endorsement of
a weakly typed messaging channel. It was more an observation that I’ve seen many variations
of this IChannel interface:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IChannel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Send&lt;T&gt;(T
message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The most important thing I wanted to point out was that while the generic type argument
may create the illusion that this is a strongly typed method, this is all it is: an
illusion. IChannel isn’t strongly typed because you can invoke the Send method with <em>any</em> type
of message – and the code will still compile. This is no different than the <a href="http://blog.ploeh.dk/2010/11/01/PatternRecognitionAbstractFactoryOrServiceLocator.aspx">mechanical
distinction between a Service Locator and an Abstract Factory</a>.
</p>
        <p>
Thus, when defining a channel interface I normally prefer to make this explicit and
instead model it like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IChannel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Send(<span style="color: "><font color="#0000ff">object</font></span> message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This achieves exactly the same and is more honest.
</p>
        <p>
Still, this doesn’t really answer Jeff’s question: is this preferable to one or more
strongly typed IConsumer&lt;T&gt; dependencies?
</p>
        <p>
Any high-level application entry point that relies on a weakly typed IChannel can
get by with a single IChannel dependency. This is flexible, but (just like with <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service
Locator</a>), it might hide that the client may have (or (d)evolve) too many responsibilities.
</p>
        <p>
If, instead, the client would rely on <a href="http://stackoverflow.com/questions/2420193/dependency-injection-constructor-madness/2420245#2420245">strongly
typed dependencies it becomes much easier to see</a> if/when it violates the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a>.
</p>
        <p>
In conclusion, I’d tend to prefer strongly typed <a href="http://www.eaipatterns.com/DatatypeChannel.html">Datatype
Channels</a> instead of a single weakly typed channel, but one shouldn’t underestimate
the flexibility of a general-purpose channel either.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=c256a22e-65a5-430a-9166-0d5619811236" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Message Dispatching without Service Location</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/09/19/MessageDispatchingWithoutServiceLocation.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,aa13e712-8f85-46d8-8a7f-b0e2da71f439.aspx</id>
    <published>2011-09-19T16:44:47.5707005+02:00</published>
    <updated>2011-09-19T16:44:47.5707005+02:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Once upon a time I wrote a blog post about why <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service
Locator is an anti-pattern</a>, and ever since then, I occasionally receive rebuffs
from people who agree with me in principle, but think that, still: in various special
cases (the argument goes), Service Locator does have its uses.
</p>
        <p>
Most of these arguments actually stem from mistaking the <a href="http://blog.ploeh.dk/2011/08/25/ServiceLocatorRolesVsMechanics.aspx">mechanics
for the role of a Service Locator</a>. Still, once in a while a compelling argument
seems to come my way. One of the <a href="http://smart421.wordpress.com/2011/08/12/to-iservicelocator-or-not/">most
insistent arguments concerns message dispatching</a> – a pattern which is currently
gaining in prominence due to the increasing popularity of <a href="http://abdullin.com/cqrs/">CQRS</a>, <a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/">Domain
Events</a> and kindred architectural styles.
</p>
        <p>
In this article I’ll first provide a quick sketch of the scenario, followed by a typical
implementation based on a ‘Service Locator’, and then conclude by demonstrating why
a Service Locator isn’t necessary.
</p>
        <p>
          <strong>Scenario: Message Dispatching</strong>
        </p>
        <p>
Appropriate use of message dispatching internally in an application can significantly
help decouple the code and make roles explicit. A common implementation utilizes a
messaging interface like this one:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IChannel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Send&lt;T&gt;(T
message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Personally, I find that the generic typing of the Send method is entirely redundant
(not to mention heavily reminiscent of the <a href="http://blog.ploeh.dk/2010/11/01/PatternRecognitionAbstractFactoryOrServiceLocator.aspx">shape
of a Service Locator</a>), but it’s very common and not particularly important right
now (but more about that later).
</p>
        <p>
An application might use the IChannel interface like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> registerUser
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">RegisterUserCommand</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Guid</font></span>.NewGuid(),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#a31515">"Jane
Doe"</font></span>,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#a31515">"password"</font></span>,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#a31515">"jane@ploeh.dk"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">this</font>
              </font>
            </span>
            <font style="font-size: 10pt">.channel.Send(registerUser);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
...</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> changeUserName
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ChangeUserNameCommand</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
registerUser.UserId,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#a31515">"Jane
Ploeh"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">this</font>
              </font>
            </span>
            <font style="font-size: 10pt">.channel.Send(changeUserName);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
...</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> resetPassword
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ResetPasswordCommand</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
registerUser.UserId);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">this</font>
              </font>
            </span>
            <font style="font-size: 10pt">.channel.Send(resetPassword);</font>
          </pre>
        </div>
        <p>
Obviously, in this example, the channel variable is an injected instance of the IChannel
interface.
</p>
        <p>
On the receiving end, these messages must be dispatched to appropriate consumers,
which must all implement this interface:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">IConsumer</font>
              </span>&lt;T&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Consume(T
message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Thus, each of the command messages in the example have a corresponding consumer:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">RegisterUserConsumer</font>
              </span> : <span style="color: "><font color="#2b91af">IConsumer</font></span>&lt;<span style="color: "><font color="#2b91af">RegisterUserCommand</font></span>&gt;</font>
          </pre>
        </div>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">ChangeUserNameConsumer</font>
              </span> : <span style="color: "><font color="#2b91af">IConsumer</font></span>&lt;<span style="color: "><font color="#2b91af">ChangeUserNameCommand</font></span>&gt;</font>
          </pre>
        </div>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">ResetPasswordConsumer</font>
              </span> : <span style="color: "><font color="#2b91af">IConsumer</font></span>&lt;<span style="color: "><font color="#2b91af">ResetPasswordCommand</font></span>&gt;</font>
          </pre>
        </div>
        <p>
This certainly <em>is</em> a very powerful pattern, so it’s often used as an argument
to prove that Service Locator is, after all, not an anti-pattern.
</p>
        <p>
          <strong>Message Dispatching using a DI Container</strong>
        </p>
        <p>
In order to implement IChannel it’s necessary to match messages to their appropriate
consumers. One easy way to do this is by employing a DI Container. Here’s an example
that uses <a href="http://autofac.org">Autofac</a> to implement IChannel, but any
other container would do as well:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">AutofacChannel</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IChannel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IComponentContext</font></span> container;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> AutofacChannel(<span style="color: "><font color="#2b91af">IComponentContext</font></span> container)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (container
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"container"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.container
= container;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Send&lt;T&gt;(T
message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> consumer
= <span style="color: "><font color="#0000ff">this</font></span>.container.Resolve&lt;<span style="color: "><font color="#2b91af">IConsumer</font></span>&lt;T&gt;&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
consumer.Consume(message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This class is an <a href="http://en.wikipedia.org/wiki/Adapter_pattern">Adapter</a> from
Autofac’s IComponentContext interface to the IChannel interface. At this point I can
always see the “Q.E.D.” around the corner: “look! Service Locator isn’t an anti-pattern
after all! I’d like to see you implement IChannel without a Service Locator.”
</p>
        <p>
While I’ll do the latter in just a moment, I’d like to dwell on the DI Container-based
implementation for a moment.
</p>
        <ul>
          <li>
Is it simple? Yes. 
</li>
          <li>
Is it flexible? Yes, although it has shortcomings. 
</li>
          <li>
Would I use it like this? Perhaps. It depends :) 
</li>
          <li>
Is it the only way to implement IChannel? No – see the next section. 
</li>
          <li>
Does it use a Service Locator? No.</li>
        </ul>
        <p>
While AutofacChannel uses Autofac (a DI Container) to implement the functionality,
it’s not (necessarily) a Service Locator in action. This was the point I already tried
to get across in my <a href="http://blog.ploeh.dk/2011/08/25/ServiceLocatorRolesVsMechanics.aspx">previous
post about the subject</a>: just because its mechanics look like Service Locator it
doesn’t mean that it <em>is</em> one. In my implementation, the AutofacChannel class
is a piece of pure infrastructure code. I even made it a private nested class in my <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">Composition
Root</a> to underscore the point. The container is still not available to the application
code, so is never used in the Service Locator <em>role</em>.
</p>
        <p>
One of the shortcomings about the above implementations is that it provides no fallback
mechanism. What happens if the container can’t resolve the matching consumer? Perhaps
there isn’t a consumer for the message. That’s entirely possible because there are
no safeguards in place to ensure that there’s a consumer for every possibly message.
</p>
        <p>
The shape of the Send method enables the client to send any conceivable message type,
and the code still compiles even if no consumer exists. That may look like a problem,
but is actually an important insight into implementing an alternative IChannel class.
</p>
        <p>
          <strong>Message Dispatching using weakly typed matching</strong>
        </p>
        <p>
Consider the IChannel.Send method once again:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">void</font>
              </font>
            </span>
            <font style="font-size: 10pt"> Send&lt;T&gt;(T
message);</font>
          </pre>
        </div>
        <p>
Despite its generic signature it’s important to realize that this is, in fact, a weakly
typed method (at least when used with type inferencing, as in the above example).
Equivalently to a bona fide Service Locator, it’s possible for a developer to define
a new class (Foo) and send it – and the code still compiles:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">this</font>
              </font>
            </span>
            <font style="font-size: 10pt">.channel.Send(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Foo</font></span>());</font>
          </pre>
        </div>
        <p>
However, at run-time, this will fail because there’s no matching consumer. Despite
the generic signature of the Send method, it contains no type safety. This insight
can be used to implement IChannel without a DI Container.
</p>
        <blockquote>
          <p>
Before I go on I should point out that I don’t consider the following solution intrinsically
superior to using a DI Container. However, readers of <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my
book</a> will know that I consider it a very illuminating exercise to try to implement
everything with Poor Man’s DI once in a while.
</p>
          <p>
Using Poor Man’s DI often helps unearth some important design elements of DI because
it helps to think about solutions in terms of patterns and principles instead of in
terms of technology.
</p>
          <p>
However, once I have arrived at an appropriate conclusion while considering Poor Man’s
DI, I still tend to prefer mapping it back to an implementation that involves a DI
Container.
</p>
          <p>
Thus, the purpose of this section is first and foremost to outline how message dispatching
can be implemented without relying on a Service Locator.
</p>
        </blockquote>
        <p>
While this alternative implementation isn’t allowed to change any of the existing
API, it’s a pure implementation detail to encapsulate the insight about the weakly
typed nature of IChannel into a similarly weakly typed consumer interface:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IConsumer</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Consume(<span style="color: "><font color="#0000ff">object</font></span> message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Notice that this is a private nested interface of my Poor Man’s DI Composition Root
– it’s a pure implementation detail. However, given this private interface, it’s now
possible to implement IChannel like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">PoorMansChannel</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IChannel</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#2b91af">IConsumer</font></span>&gt;
consumers;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> PoorMansChannel(<span style="color: "><font color="#0000ff">params</font></span><span style="color: "><font color="#2b91af">IConsumer</font></span>[]
consumers)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.consumers
= consumers;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Send&lt;T&gt;(T
message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">foreach</font></span> (<span style="color: "><font color="#0000ff">var</font></span> c <span style="color: "><font color="#0000ff">in</font></span><span style="color: "><font color="#0000ff">this</font></span>.consumers)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
c.Consume(message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Notice that this is another private nested type that belongs to the Composition Root.
It loops though all injected consumers, so it’s up to each consumer to decide whether
or not to do anything about the message.
</p>
        <p>
A final private nested class bridges the generically typed world with the weakly typed
world:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Consumer</font>
              </span>&lt;T&gt;
: </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IConsumer</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IConsumer</font></span>&lt;T&gt;
consumer;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> Consumer(<span style="color: "><font color="#2b91af">IConsumer</font></span>&lt;T&gt;
consumer)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.consumer
= consumer;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Consume(<span style="color: "><font color="#0000ff">object</font></span> message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (message <span style="color: "><font color="#0000ff">is</font></span> T)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.consumer.Consume((T)message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This generic class is another Adapter – this time adapting the generic IConsumer&lt;T&gt;
interface to the weakly typed (private) IConsumer interface. Notice that it only delegates
the message to the adapted consumer if the type of the message matches the consumer.
</p>
        <p>
Each implementer of IConsumer&lt;T&gt; can be wrapped in the (private) Consumer&lt;T&gt;
class and injected into the PoorMansChannel class:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> channel
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">PoorMansChannel</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Consumer</font></span>&lt;<span style="color: "><font color="#2b91af">ChangeUserNameCommand</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ChangeUserNameConsumer</font></span>(store)),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Consumer</font></span>&lt;<span style="color: "><font color="#2b91af">RegisterUserCommand</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">RegisterUserConsumer</font></span>(store)),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Consumer</font></span>&lt;<span style="color: "><font color="#2b91af">ResetPasswordCommand</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ResetPasswordConsumer</font></span>(store)));</font>
          </pre>
        </div>
        <p>
So there you have it: type-based message dispatching without a DI Container in sight.
However, it would be easy to use convention-based configuration to scan an assembly
and register all IConsumer&lt;T&gt; implementations and wrap them in Consumer&lt;T&gt;
instances and use this list to compose a PoorMansChannel instance. However, I will
leave this as an exercise to the reader (or a later blog post).
</p>
        <p>
          <strong>My claim still stands</strong>
        </p>
        <p>
In conclusion, I find that I can still defend my original claim: <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service
Locator is an anti-pattern</a>.
</p>
        <p>
That claim, by the way, is <a href="http://en.wikipedia.org/wiki/Falsifiability">falsifiable</a>,
so I do appreciate that people take it seriously enough by attempting to disprove
it. However, until now, I’ve yet to be presented with a scenario where I couldn’t
come up with a better solution that didn’t involve a Service Locator.
</p>
        <p>
Keep in mind that a Service Locator is defined by the role it plays – not the shape
of the API.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=aa13e712-8f85-46d8-8a7f-b0e2da71f439" />
      </div>
    </content>
  </entry>
  <entry>
    <title>AutoFixture goes Continuous Delivery with Semantic Versioning</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/09/06/AutoFixtureGoesContinuousDeliveryWithSemanticVersioning.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,5342fbcc-2443-4af2-b94f-1bc269d1c19e.aspx</id>
    <published>2011-09-06T22:34:42.4414275+02:00</published>
    <updated>2011-09-06T22:34:42.4414275+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
For the last couple of months I’ve been working on setting up <a href="http://autofixture.codeplex.com/">AutoFixture</a> for
Continuous Delivery (thanks to the nice people at <a title="http://teamcity.codebetter.com/" href="http://teamcity.codebetter.com/">http://teamcity.codebetter.com/</a> for
supplying the CI service) and I think I’ve finally succeeded. I’ve just pushed some
code from my local Mercurial repository, and 5 minutes later the release is <a href="http://autofixture.codeplex.com/releases/view/72947">live
on both the CodePlex site</a> as well as <a href="http://nuget.org/List/Search?searchTerm=autofixture">on
the NuGet Gallery</a>.
</p>
        <p>
The plan for AutoFixture going forward is to maintain Continuous Delivery and switch
the versioning scheme from ad hoc to <a href="http://semver.org/">Semantic Versioning</a>.
This means that obviously you’ll see releases much more often, and versions are going
to be incremented much more often. Since the previous release the current release
incidentally ended at version 2.2.44, but since the versioning scheme has now changed,
you can expect to see 2.3, 2.4 etc. in rapid succession.
</p>
        <p>
While I’ve been mostly focused on setting up Continuous Delivery, <a href="http://www.nikosbaxevanis.com/bonus-bits/">Nikos
Baxevanis</a> and <a href="http://megakemp.wordpress.com/">Enrico Campidoglio</a> have
been busy writing new features:
</p>
        <ul>
          <li>
            <a href="http://megakemp.wordpress.com/2011/08/01/anonymous-delegates-in-autofixture/">Support
for anonymous delegates</a>
          </li>
          <li>
            <a href="http://www.nikosbaxevanis.com/bonus-bits/2011/08/heuristics-for-static-factory-methods-in-autofixture.html">Heuristics
for static factory methods</a>
          </li>
          <li>
            <a href="http://www.nikosbaxevanis.com/bonus-bits/2011/08/combining-xunit-data-theories.html">Inline
AutoData Theories</a>
          </li>
          <li>
            <a href="http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/">More
anonymous numbers</a>
          </li>
        </ul>
        <p>
Apart from these excellent contributions, other new features are
</p>
        <ul>
          <li>
            <a href="http://blog.ploeh.dk/2011/04/18/EnumerablesAreDynamicalsoInAutoFixture.aspx">Added
StableFiniteSequenceCustomization</a>
          </li>
          <li>
Added [FavorArrays], [FavorEnumerables] and [FavorLists] attributes to xUnit.net extension 
</li>
          <li>
Added a Generator&lt;T&gt; class 
</li>
          <li>
Added a completely new project/package called <em>Idioms</em>, which contains convention-based
tests (more about this later) 
</li>
          <li>
Probably some other things I’ve forgotten about…</li>
        </ul>
        <p>
While you can expect to see version numbers to increase more rapidly and releases
to occur more frequently, I’m also beginning to think about AutoFixture 3.0. This
release will streamline some of the API in the root namespace, which, I’ll admit,
was always a bit haphazard. For those people who care, I have no plans to touch the
API in the Ploeh.AutoFixture.Kernel namespace. AutoFixture 3.0 will mainly target
the API contained in the Ploeh.AutoFixture namespace itself.
</p>
        <p>
Some of the changes I have in mind will hopefully make the default experience with
AutoFixture more pleasant – I’m unofficially thinking about AutoFixture 3.0 as the
‘pit of success’ release. It will also enable some of the various <a href="http://autofixture.codeplex.com/workitem/list/basic">outstanding
feature requests</a>.
</p>
        <p>
Feedback is, as usual, appreciated.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=5342fbcc-2443-4af2-b94f-1bc269d1c19e" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Service Locator: roles vs. mechanics</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/08/25/ServiceLocatorRolesVsMechanics.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,40663e09-df4d-464d-8b34-b1690056db48.aspx</id>
    <published>2011-08-25T20:55:12.514761+02:00</published>
    <updated>2011-08-25T21:19:47.8786184+02:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
It’s time to take a step back from the whole debate about whether or not <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service
Locator</a> is, or isn’t, an anti-pattern. It remains my strong belief that it’s an
anti-pattern, while others disagree. Although everyone is welcome to think differently
than me, I’ve noticed that <a href="http://smart421.wordpress.com/2011/08/12/to-iservicelocator-or-not/">some
of the arguments being put forth in defense of Service Locator seem very convincing</a>.
However, I believe that in those cases we no longer talk about Service Locator, but
something that looks an awful lot like it.
</p>
        <p>
Some APIs are easy to confuse with a ‘real’ Service Locator. It probably doesn’t help
that last year I published an article on <a href="http://blog.ploeh.dk/2010/11/01/PatternRecognitionAbstractFactoryOrServiceLocator.aspx">how
to tell the difference between a Service Locator and an Abstract Factory</a>. In this
article I may have focused too much on the <em>mechanics</em> of Service Locator,
but as <a href="http://lostechies.com/derickbailey/">Derick Bailey</a> was so kind
to point out, this hides the <em>role</em> the API might play.
</p>
        <p>
To repeat that earlier post, a Service Locator looks like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IServiceLocator</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
T Create&lt;T&gt;(<span style="color: "><font color="#0000ff">object</font></span> context);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
All Service Locators I’ve seen so far look like that, or some variation thereof, but
that doesn’t mean that the relationship is transitive. Just because an API <em>looks</em> like
that it doesn’t <em>automatically</em> means that it’s a Service Locator.
</p>
        <p>
If it was, all DI containers would be Service Locators. As an example, here’s Castle
Windsor’s Resolve method:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt"> T
Resolve&lt;T&gt;()</font>
          </pre>
        </div>
        <p>
Even <a href="http://autofixture.codeplex.com/">AutoFixture</a> has an API like that:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">MyClass</font>
              </font>
            </span>
            <font style="font-size: 10pt"> sut
= fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">MyClass</font></span>&gt;();</font>
          </pre>
        </div>
        <p>
It has never been my intention to denounce every single DI container available, as
well as my own open source framework. Service Locator is ultimately not identified
by the <em>mechanics</em> of its API, but by the <em>role</em> it plays.
</p>
        <p>
A DI container encapsulated in a <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">Composition
Root</a> is not a Service Locator – it’s an <em>infrastructure</em> component.
</p>
        <p>
It <em>becomes</em> a Service Locator if used incorrectly: when <em>application</em> code
(as opposed to infrastructure code) actively <em>queries</em> a service in order to
be provided with required dependencies, then it has become a Service Locator.
</p>
        <p>
Service Locators are spread thinly and pervasively throughout a code base – <em>that</em> is
just as much a defining characteristic.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=40663e09-df4d-464d-8b34-b1690056db48" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Joining AppHarbor</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/08/01/JoiningAppHarbor.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,4de7115c-79c2-4c9e-91b9-9b33bc69cc6c.aspx</id>
    <published>2011-08-01T16:03:10.4282209+02:00</published>
    <updated>2011-08-01T16:03:10.4282209+02:00</updated>
    <category term="Miscellaneous" label="Miscellaneous" scheme="http://blog.ploeh.dk/CategoryView,category,Miscellaneous.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
I’m pleased to announce that I’ll be joining <a href="http://appharbor.com">AppHarbor</a> as
a developer. With my long-standing interest in TDD and OOD as well as my more recent
interests in open-source .NET software, distributed source control systems, Continuous
Delivery etc. AppHarbor seems like a perfect match for me.
</p>
        <p>
Although AppHarbor is very attractive to me, this has been a difficult decision as <a href="http://www.commentor.dk/">Commentor</a> has
been a great employer. However, despite great customers I just don’t feel like consulting
at the moment. Since Safewhere went out of business I’ve been writing much less code
than I’d liked, so when presented with an opportunity to join such a congenial outfit
as AppHarbor I had few doubts.
</p>
        <p>
I’ll still be working out of Copenhagen, Denmark, and I also expect to keep up my
usual community engagement at home as well as abroad.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=4de7115c-79c2-4c9e-91b9-9b33bc69cc6c" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Composition Root</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,eeb3103a-da41-40b1-b91d-dab5d7c91b1e.aspx</id>
    <published>2011-07-28T17:22:04.3617653+02:00</published>
    <updated>2011-07-28T17:22:04.3617653+02:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p align="left">
In <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my book</a> I
describe the Composition Root pattern in chapter 3. This post serves as a summary
description of the pattern.
</p>
        <p align="left">
The Constructor Injection pattern is easy to understand until a follow-up question
comes up:
</p>
        <blockquote>
          <p align="left">
Where should we compose object graphs?
</p>
        </blockquote>
        <p align="left">
It’s easy to understand that each class should require its dependencies through its
constructor, but this pushes the responsibility of composing the classes with their
dependencies <a href="http://www.natpryce.com/articles/000783.html">to a third party</a>.
Where should that be?
</p>
        <p align="left">
It seems to me that most people are eager to compose as early as possible, but the
correct answer is:
</p>
        <blockquote>
          <p align="left">
As close as possible to the application’s entry point.
</p>
        </blockquote>
        <p align="left">
This place is called the <em>Composition Root</em> of the application and defined
like this:
</p>
        <blockquote>
          <p align="left">
A Composition Root is a (preferably) unique location in an application where modules
are composed together.
</p>
        </blockquote>
        <p align="left">
This means that all the application code relies solely on Constructor Injection (or
other injection patterns), but is <em>never composed</em>. Only at the entry point
of the application is the <a href="http://blog.ploeh.dk/2011/03/04/ComposeObjectGraphsWithConfidence.aspx">entire
object graph</a> finally composed.
</p>
        <p align="left">
The appropriate entry point depends on the framework:
</p>
        <ul>
          <li>
            <div align="left">In console applications it’s the Main method
</div>
          </li>
          <li>
            <div align="left">In ASP.NET MVC applications it’s global.asax and a custom IControllerFactory
</div>
          </li>
          <li>
            <div align="left">In WPF applications it’s the Application.OnStartup method
</div>
          </li>
          <li>
            <div align="left">In WCF it’s a custom ServiceHostFactory
</div>
          </li>
          <li>
            <div align="left">etc.
</div>
          </li>
        </ul>
        <p align="left">
(you can read more about framework-specific Composition Roots in chapter 7 of my book.)
</p>
        <p align="left">
The Composition Root is an <em>application infrastructure component</em>.
</p>
        <blockquote>
          <p align="left">
Only applications should have Composition Roots. Libraries and frameworks shouldn’t.
</p>
        </blockquote>
        <p align="left">
The Composition Root can be implemented with Poor Man’s DI, but is also the (only)
appropriate place to use a DI Container.
</p>
        <blockquote>
          <p align="left">
A DI Container should only be referenced from the Composition Root. All other modules
should have no reference to the container.
</p>
        </blockquote>
        <p align="left">
Using a DI Container is often a good choice. In that case it should be applied using
the <a href="http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx">Register
Resolve Release</a> pattern entirely from within the Composition Root.
</p>
        <p align="left">
Read more in <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">Dependency
Injection in .NET</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=eeb3103a-da41-40b1-b91d-dab5d7c91b1e" />
      </div>
    </content>
  </entry>
  <entry>
    <title>SOLID Code isn’t</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/06/07/SOLIDCodeIsnt.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,d770cccd-8543-4de5-aef7-df63137ecca5.aspx</id>
    <published>2011-06-07T15:46:07.1059056+02:00</published>
    <updated>2011-06-07T15:46:07.1059056+02:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Recently I had an interesting conversation with a developer at my current client,
about how the <a href="http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29">SOLID</a> principles
would impact their code base. The client wants to write SOLID code – who doesn’t?
It’s a beautiful acronym that fully demonstrates the power of catchy terminology.
</p>
        <p align="left">
However, when you start to outline what it actually <em>means</em> people become uneasy.
At the point where the discussion became interesting, I had already sketched <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">my
view on encapsulation</a>. However, the client’s current code base is designed around
validation at the perimeter. Most of the classes in the Domain Model are actually <a href="http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx">internal</a> and
implicitly trust input.
</p>
        <p align="left">
We were actually discussing Test-Driven Development, and I had already told them that
they should only test against the public API of their code base. The discussion went
something like this (I’m hoping I’m not making my ‘opponent’ sound dumb, because the
real developer I talked to was anything but):
</p>
        <p align="left">
          <strong>Client:</strong> “That would mean that each and every class we expose must
validate input!”
</p>
        <p>
          <strong>Me:</strong> “Yes…?”
</p>
        <p>
          <strong>Client:</strong> “That would be a lot of extra work.”
</p>
        <p>
          <strong>Me:</strong> “Would it? Why is that?”
</p>
        <p>
          <strong>Client:</strong> “The input that we deal with consist of complex data structures,
and we must validate that all values are present and correct.”
</p>
        <p>
          <strong>Me:</strong> “Assume that input is SOLID as well. This would mean that each
input instance can be assumed to be in a valid state because that would be its own
responsibility. Given that, what would validation really mean?”
</p>
        <p>
          <strong>Client:</strong> “I’m not sure I understand what you mean…”
</p>
        <p>
          <strong>Me:</strong> “Assuming that the input instance is a self-validating reference
type, what could possibly go wrong?”
</p>
        <p>
          <strong>Client:</strong> “The instance might be null…”
</p>
        <p>
          <strong>Me:</strong> “Yes. Anything else?”
</p>
        <p>
          <strong>Client:</strong> “Not that I can think of…”
</p>
        <p>
          <strong>Me:</strong> “Me neither. This means that while you must add more code to
implement proper encapsulation, it’s really trivial code. It’s just some Guard Clauses.”
</p>
        <p>
          <strong>Client:</strong> “But isn’t it still gold plating?”
</p>
        <p>
          <strong>Me:</strong> “Not really, because we are designing for <em>change</em> in
the general sense. We know that we can’t predict <em>specific</em> change, but I can
guarantee you that change requests <em>will</em> occur. Instead of trying to predict
specific changes and design variability in those specific places, we simply put interfaces
around everything because the cost of doing so is really low. This means that when
change does happen, we already have Seams in the right places.”
</p>
        <p>
          <strong>Client:</strong> “How does SOLID help with that?”
</p>
        <p>
          <strong>Me:</strong> “A result of the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> is that each self-encapsulated class becomes really small,
and there will be a lot of them.”
</p>
        <p>
          <strong>Client:</strong> “Lots of classes… I’m not sure I’m comfortable with that.
Doesn’t it make it much harder to find what you need?”
</p>
        <p>
          <strong>Me:</strong> “I don’t think so. Each class is very small, so although you
have many of them, understanding what each one does is easy. In my experience this
is a lot easier than trying to figure out what a big class with thousands of lines
of code does. When you have few big classes, your object model might look something
like this:”
</p>
        <p>
          <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Large Grained Objects" border="0" alt="Large Grained Objects" src="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/SOLID-Code-isnt_B434/largegrainedobjects_3.png" width="400" height="257" />
        </p>
        <p>
“There’s a few objects and they kind of fit together to form the overall picture.
However, if you need to change something, you’ll need to substantially change the
shape of each of those objects. That’s a lot of work, and this is why such an object
design isn’t particularly adaptable to change.
</p>
        <p>
“With SOLID, on the other hand, you have lots of small-grained objects which you can
easily re-arrange to match new requirements:”
</p>
        <p>
          <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Fine Grained Objects" border="0" alt="Fine Grained Objects" src="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/SOLID-Code-isnt_B434/finegrainedobjects_3.png" width="246" height="233" />
        </p>
        <p align="left">
And that’s when it hit me: SOLID code isn’t really solid at all. I’m not a material
scientist, but to me a <a href="http://en.wikipedia.org/wiki/Solid">solid</a> indicates
a rigid structure. In essence a structure where the particles are tightly locked to
each other and can’t easily move about.
</p>
        <p align="left">
However, when thinking about SOLID code, it actually helps to think about it more
like a <a href="http://en.wikipedia.org/wiki/Liquid">liquid</a> (although perhaps
a rather viscous one). Each class has much more room to maneuver because it is small
and fits together with other classes in many different ways. It’s clear that when
you <a href="http://xkcd.com/895/">push an analogy too far, it breaks apart</a>.
</p>
        <p align="left">
Still, a closing anecdote is appropriate…
</p>
        <p align="left">
My (then) three-year old son one day handed me a handful of <a href="http://en.wikipedia.org/wiki/Lego_Duplo">Duplo</a> bricks
and asked me to build him a dragon. If you’ve ever tried to build anything out of
Duplo you’ll know that the ‘resolution’ of the bricks is rather coarse-grained. Given
that ‘a handful’ for a three-year old isn’t a lot of bricks, this was quite a challenge.
Fortunately, I had an appreciative audience with quite a bit of imagination, so I
was able to put the few bricks together in a way that satisfied my son.
</p>
        <p align="left">
Still, building a dragon of comparable size out of <a href="http://en.wikipedia.org/wiki/Lego">Lego</a> bricks
is much easier because the bricks have a much finer ‘resolution’. SOLID code is more
comparable to Lego than Duplo.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d770cccd-8543-4de5-aef7-df63137ecca5" />
      </div>
    </content>
  </entry>
  <entry>
    <title>At the Boundaries, Applications are Not Object-Oriented</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/31/AtTheBoundariesApplicationsAreNotObjectOriented.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,2a251d22-ad3e-443a-bc98-6dd165d639e2.aspx</id>
    <published>2011-05-31T15:27:11.3100575+02:00</published>
    <updated>2011-05-31T15:27:11.3100575+02:00</updated>
    <category term="Services" label="Services" scheme="http://blog.ploeh.dk/CategoryView,category,Services.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
My recent series of blog posts about <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">Poka-yoke
Design</a> generated a few responses (I would have been disappointed had this not
been the case). Quite a few of these reactions relate to various serialization or
translation technologies usually employed at application boundaries: Serialization,
XML (de)hydration, UI validation, etc. Note that such translation happens not only
at the perimeter of the application, but also at the persistence layer. ORMs are also
a translation mechanism.
</p>
        <p>
Common to most of the comments is that lots of serialization technologies require
the presence of a default constructor. As an example, the <a href="http://msdn.microsoft.com/en-us/library/182eeyhh.aspx">XmlSerializer</a> requires
a default constructor and public writable properties. Most ORMs I’ve investigated
seem to have the same kind of requirements. Windows Forms and WPF Controls (UI is
also an application boundary) also must have default constructors. Doesn’t that break
encapsulation? Yes and no.
</p>
        <p>
          <strong>Objects at the Boundary</strong>
        </p>
        <p>
It certainly <em>would</em> break encapsulation if you were to expose your (domain) <em>objects</em> directly
at the boundary. Consider a simple XML document like this one:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">&lt;</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">name</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">&gt;</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt"> 
&lt;</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">firstName</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">&gt;</font>
              </span>Mark<span style="color: "><font color="#0000ff">&lt;/</font></span><span style="color: "><font color="#a31515">firstName</font></span></font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">&gt;</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt"> 
&lt;</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">lastName</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">&gt;</font>
              </span>Seemann<span style="color: "><font color="#0000ff">&lt;/</font></span><span style="color: "><font color="#a31515">lastName</font></span></font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">&gt;</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">&lt;/</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">name</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">&gt;</font>
            </span>
          </pre>
        </div>
        <p>
Whether or not we have formal contract (XSD) or not, we might stipulate that both
the firstName and lastName elements are <em>required</em>. However, despite such a
contract, I can easily create a document that breaks it:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">&lt;</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">name</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">&gt;</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt"> 
&lt;</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">firstName</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">&gt;</font>
              </span>Mark<span style="color: "><font color="#0000ff">&lt;/</font></span><span style="color: "><font color="#a31515">firstName</font></span></font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">&gt;</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">&lt;/</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">name</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">&gt;</font>
            </span>
          </pre>
        </div>
        <p>
We can’t <em>enforce</em> the contract as there’s no compilation step involved. We
can <em>validate</em> input (and output), but that’s a different matter. Exactly because
there’s no enforcement it’s very easy to create malformed input. The same argument
can be made for UI input forms and any sort of serialized byte sequence. This is why
we must treat all input as suspect.
</p>
        <p>
This isn’t a new observation at all. In <a href="http://www.martinfowler.com/books.html#eaa">Patterns
of Enterprise Application Architecture</a>, <a href="http://www.martinfowler.com">Martin
Fowler</a> described this as a <a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html">Data
Transfer Object</a> (DTO). However, despite the name we should realize that DTOs are
not really objects at all. This is nothing new either. Back in 2004 Don Box formulated
the <a href="http://msdn.microsoft.com/en-us/magazine/cc164026.aspx">Four Tenets of
Service Orientation</a>. (Yes, I know that they are not in vogue any more and that
people <a href="http://www.pluralsight-training.net/community/blogs/dbox/archive/2007/08/15/48232.aspx">wanted
to retire them</a>, but some of them still make tons of sense.) Particularly the third
tenet is germane to this particular discussion:
</p>
        <blockquote>
          <p>
Services share schema and contract, not class.
</p>
        </blockquote>
        <p>
Yes, and that means they are <em>not objects</em>. A DTO is a <em>representation</em> of
such a piece of data <em>mapped into</em> an object-oriented language. That still
doesn’t make them objects in the sense of encapsulation. It would be impossible. Since
all input is suspect, we can hardly enforce any invariants at all.
</p>
        <p>
Often, as <a href="http://blogs.teamb.com/craigstuntz/">Craig Stuntz</a> points out
in <a href="http://blog.ploeh.dk/2011/05/27/DesignSmellRedundantRequiredAttribute.aspx">a
comment to one of my previous posts</a>, even if the input is invalid, we want to
capture what we <em>did</em> receive in order to present a proper error message (this
argument also applies on machine-to-machine boundaries). This means that any DTO must
have <em>very</em> weak invariants (if any at all).
</p>
        <blockquote>
          <p>
DTOs don’t break encapsulation because they aren’t objects at all.
</p>
        </blockquote>
        <p>
Don’t be fooled by your tooling. The .NET framework very, very much wants you to treat
DTOs as objects. Code generation ensues.
</p>
        <p>
However, the strong typing provided by such auto-generated classes gives a false sense
of security. You may think that you get <a href="http://blog.ploeh.dk/2011/04/29/FeedbackMechanismsAndTradeoffs.aspx">rapid
feedback from the compiler</a>, but there are many possible ways you can get run-time
errors (most notably when you forget to update the auto-generated code based on new
schema versions).
</p>
        <p>
An even more problematic result of representing input and output as objects is that
it tricks lots of developers into dealing with them as though they represent the real
object model. The result is invariably an <a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html">anemic
domain model</a>.
</p>
        <p>
More and more, this line of reasoning is leading me towards the conclusion that the
DTO mental model that we have gotten used to over the last ten years is a dead end.
</p>
        <p>
          <strong>What Should Happen at the Boundary</strong>
        </p>
        <p>
Given that we write write object-oriented code and that data at the boundary is anything
but object-oriented, how do we deal with it?
</p>
        <p>
One option is to stick with what we already have. To bridge the gap we must then develop <em>translation
layers</em> that can translate the DTOs to properly encapsulated domain objects. This
is the route I take with the samples in <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my
book</a>. However, this is a solution that more and more I’m beginning to think may
not be the best. It has issues with maintainability. (Incidentally, that’s the problem
with writing a book: at the time you’re done, you know so much more than you did when
you started out… Not that I’m denouncing the book – it’s just not perfect…)
</p>
        <p>
Another option is to stop treating data as objects and start treating it as the <em>structured
data</em> that it really is. It would be really nice if our programming language had
a separate concept of <em>structured data</em>… Interestingly, while C# has nothing
of the kind, F# has tons of ways to model data structures without behavior. Perhaps
that’s a more honest approach to dealing with data… I will need to experiment more
with this…
</p>
        <p>
A third option is to look towards dynamic types. In his article <a href="http://msdn.microsoft.com/en-us/magazine/ff796227.aspx">Cutting
Edge: Expando Objects in C# 4.0</a>, Dino Esposito outlines a dynamic approach towards
consuming structured data that shortcuts auto-generated code and provides a lightweight
API to structured data. This also looks like a promising approach… It doesn’t provide
compile-time feedback, but that’s only a false sense of security anyway. We must resort
to <a href="http://blog.ploeh.dk/2011/04/29/FeedbackMechanismsAndTradeoffs.aspx">unit
tests to get rapid feedback</a>, but we’re all using TDD already, right?
</p>
        <p>
In summary, my entire series about encapsulation relates to <em>object-oriented programming</em>.
Although there are lots of technologies available to represent boundary data as ‘objects’,
they are false objects. Even if we use an object-oriented language at the boundary,
the code has nothing to do with object orientation. Thus, the Poka-yoke Design rules
don’t apply there.
</p>
        <p>
Now go back and reread this post, but replace ‘DTO’ with ‘Entity’ (or whatever your
ORM calls its representation of a relational table row) and you should begin to see
the contours of why ORMs are problematic.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2a251d22-ad3e-443a-bc98-6dd165d639e2" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Design Smell: Default Constructor</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/30/DesignSmellDefaultConstructor.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,13f91979-d50a-49da-b27c-fdebeb7dde1b.aspx</id>
    <published>2011-05-30T15:02:02.4785244+02:00</published>
    <updated>2011-05-30T15:02:02.4785244+02:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This post is the fifth in a series about <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">Poka-yoke
Design</a> – also known as <em>encapsulation</em>.
</p>
        <p>
Default constructors are code smells. There you have it. That probably sounds outrageous,
but consider this: object-orientation is about <em>encapsulating</em> behavior <em>and
data</em> into cohesive pieces of code (classes). Encapsulation means that the class
should protect the integrity of the data it encapsulates. When data is required, it
must often be supplied through a constructor. Conversely, a default constructor implies
that no external data is <em>required</em>. That’s a rather weak statement about the
invariants of the class.
</p>
        <blockquote>
          <p>
Please be aware that this post represents a <em>smell</em>. This indicates that whenever
a certain idiom or pattern (in this case a default constructor) is encountered in
code it should trigger further investigation.
</p>
          <p>
As I will outline below, there are several scenarios where default constructors are
perfectly fine, so the purpose of this blog post is not to thunder against default
constructors. It’s to provide food for thought.
</p>
        </blockquote>
        <p>
If you have read <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my
book</a> you will know that Constructor Injection is the dominating DI pattern exactly
because it statically advertises dependencies and protects the integrity of those
dependencies by guaranteeing that an initialized consumer is always in a consistent
state. This is fail-safe design because <a href="http://blog.ploeh.dk/2011/04/29/FeedbackMechanismsAndTradeoffs.aspx">the
compiler can enforce the relationship, thus providing rapid feedback</a>.
</p>
        <p>
This principle extends far beyond DI. In a <a href="http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx">previous
post</a> I described how a constructor with arguments statically advertises that the
argument is required:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Fragrance</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IFragrance</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#0000ff">string</font></span> name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> Fragrance(<span style="color: "><font color="#0000ff">string</font></span> name)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (name
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"name"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.name
= name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> Spread()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The Fragrance class protects the integrity of the name by requiring it through the
constructor. Since this class requires the name to implement its behavior, requesting
it through the constructor is the correct thing to do. A default constructor would
not have been fail-safe, since it would introduce a <a href="http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx">temporal
coupling</a>.
</p>
        <p>
Consider that objects are supposed to be containers of behavior and data. Whenever
an object contains data, the data must be encapsulated. In the (very common) case
where no meaningful default value can be defined, the data must be provided via the
constructor. Thus, default constructors might indicate that encapsulation is broken.
</p>
        <p>
          <strong>When are Default Constructors OK?</strong>
        </p>
        <p>
There are still scenarios where default constructors are in order (I’m sure there
are more than those listed here).
</p>
        <ul>
          <li>
If a default constructor can assign meaningful default values to all contained fields
a default constructor still protects the invariants of the class. As an example, the
default constructor of <a href="http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx">UriBuilder</a> initializes
its internal values to a consistent set that will build the Uri http://localhost unless
one or more of its properties are subsequently manipulated. You may agree or disagree
with this default behavior, but it’s consistent and so encapsulation is preserved. 
</li>
          <li>
If a class contains no data obviously there is no data to protect. This may be a symptom
of the <a href="http://c2.com/cgi/wiki?FeatureEnvySmell">Feature Envy</a> code smell,
which is often evidenced by the class in question being a concrete class. 
<ul><li>
If such a class can be turned into a static class it’s a certain sign of Feature Envy. 
</li><li>
If, on the other hand, the class implements an interface, it might be a sign that
it actually represents pure behavior.</li></ul></li>
        </ul>
        <p>
A class that represents pure behavior by implementing an interface is not necessarily
a bad thing. This can be a very powerful construct.
</p>
        <p>
In summary, a default constructor should be a signal to stop and think about the invariants
of the class in question. Does the default constructor sufficiently guarantee the
integrity of the encapsulated data? If so, the default constructor is appropriate,
but otherwise it’s not. In my experience, default constructors tend to be the exception
rather than the rule.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=13f91979-d50a-49da-b27c-fdebeb7dde1b" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Design Smell: Redundant Required Attribute</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/27/DesignSmellRedundantRequiredAttribute.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,04140ccb-6793-4428-972b-cbf26ce5dae6.aspx</id>
    <published>2011-05-27T15:21:06.9318869+02:00</published>
    <updated>2011-05-27T15:21:06.9318869+02:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This post is the fourth in a series about <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">Poka-yoke
Design</a> – also known as <em>encapsulation</em>.
</p>
        <p>
Recently I saw this apparently enthusiastic tweet reporting from some Microsoft technology
event:
</p>
        <blockquote>
          <p>
            <a href="https://twitter.com/#!/jennifermarsman/status/57850114424848385">[Required]
attribute in code automatically creates a non-nullable entry in DB and validation
in the webpage – nice […]</a>
          </p>
        </blockquote>
        <p>
I imagine that it must look something like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">Smell</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">Required</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">int</font></span> Id
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Every time I see something like this I die a little inside. If you already read my
previous posts it should by now be painfully clear why this breaks encapsulation.
Despite the [Required] attribute there’s <a href="http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx">no
guarantee that the Id property will ever be assigned a value</a>. The attribute is
just a piece of garbage making a claim it can’t back up.
</p>
        <p>
Code like that is not fail-safe.
</p>
        <p>
I understand that the attribute mentioned in the above tweet is intended to signal
to some tool (probably EF) that the property must be mapped to a database schema as
non-nullable, but it’s still redundant. Attributes are not the correct way to make
a statement about invariants.
</p>
        <p>
          <strong>Improved Design</strong>
        </p>
        <p>
The [Required] attribute is redundant because there’s a much better way to state that
a piece of data is required. This has been possible since .NET 1.0. Here’s the Poka-yoke
version of that same statement:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">Fragrance</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#0000ff">int</font></span> id;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> Fragrance(<span style="color: "><font color="#0000ff">int</font></span> id)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.id
= id;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">int</font></span> Id</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.id;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This simple structural design ensures that the ID truly is required (and if the ID
can only be positive a Guard Clause can be added). An instance of Fragrance can only
be created with an ID. Since this is a structural construction, the <a href="http://blog.ploeh.dk/2011/04/29/FeedbackMechanismsAndTradeoffs.aspx">compiler
can enforce the requirement, giving us rapid feedback</a>.
</p>
        <p>
I do realize that the [Required] attribute mentioned above is intended to address
the challenge of mapping objects to relational data and rendering, but instead of
closing the impedance mismatch gap, it widens it. Instead of introducing yet another
redundant attribute the team should have made their tool understand simple idioms
for encapsulation like the one above.
</p>
        <p>
This isn’t at all hard to do. As an example, DI Containers thrive on structural information
encoded into constructors (this is called <em>Auto-wiring</em>). The team behind the
[Required] attribute could have done that as well. The [Required] attribute is a primitive
and toxic hack.
</p>
        <p>
This is the major reason I never expect to use EF. It forces developers to break encapsulation,
which is a principle upon which I refuse to compromise.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=04140ccb-6793-4428-972b-cbf26ce5dae6" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Code Smell: Automatic Property</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/26/CodeSmellAutomaticProperty.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,70e00361-46ae-4406-a148-da382b1c8d76.aspx</id>
    <published>2011-05-26T15:33:13.6607716+02:00</published>
    <updated>2011-05-26T20:31:13.4364026+02:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This post is the third in a series about <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">Poka-yoke
Design</a> – also known as <em>encapsulation</em>.
</p>
        <p>
          <a href="http://msdn.microsoft.com/en-us/library/bb384054.aspx">Automatic properties</a> are
one of the most redundant features of C#. I know that some people really love them,
but they address a problem you shouldn’t have in the first place.
</p>
        <p>
I totally agree that code like this looks redundant:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> name;</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> Name</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.name;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">set</font></span> { <span style="color: "><font color="#0000ff">this</font></span>.name
= <span style="color: "><font color="#0000ff">value</font></span>; }</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
However, the solution is not to write this instead:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> Name
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
        </div>
        <p>
The problem with the first code snippet isn’t that it contains too much ceremony.
The problem is that it breaks encapsulation. In fact
</p>
        <blockquote>
          <p>
“[…] getters and setters do not achieve encapsulation or information hiding: they
are a language-legitimized way to violate them.”
</p>
          <p>
James O. Coplien &amp; Gertrud Bjørnvig. <em>Lean Architecture</em>. Wiley. 2010.
p. 134.
</p>
        </blockquote>
        <p>
While I personally think that properties do have their uses, I very rarely find use
for <em>automatic</em> properties. They are never appropriate for reference types,
and only rarely for value types.
</p>
        <p>
          <strong>Code Smell: Automatic Reference Type Property</strong>
        </p>
        <p>
First of all, let’s consider the very large set of properties that expose a reference
type.
</p>
        <p>
In the case of reference types, null is a possible value. However, when we think about
Poka-yoke design, null is never an appropriate value because it leads to NullReferenceExceptions.
The <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null Object</a> pattern
provides a better alternative to deal with situations where a value might be undefined.
</p>
        <p>
In other words, an automatic property like the Name property above is never appropriate.
The setter must have some kind of Guard Clause to protect it against null (and possibly
other invalid values). Here’s the most fundamental example:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> name;</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> Name</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.name;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">set</font></span></font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (<span style="color: "><font color="#0000ff">value</font></span> == <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"value"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.name
= <span style="color: "><font color="#0000ff">value</font></span>; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
As an alternative, a Guard Clause could also check for null and provide a default
Null Object in the cases where the assigned value is null:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> name;</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> Name</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.name;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">set</font></span></font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (<span style="color: "><font color="#0000ff">value</font></span> == <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">this</font></span>.name
= <span style="color: "><font color="#a31515">""</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">return</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.name
= <span style="color: "><font color="#0000ff">value</font></span>; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p align="left">
However, this implementation contains a <a href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment">POLA</a> violation
because the getter sometimes returns a different value than what was assigned. It’s
possible to fix this problem by adding an associated boolean field indicating whether
the name was assigned null so that null can be returned from the setter in this special
case, but that leads to another code smell.
</p>
        <p align="left">
          <strong>Code Smell: Automatic Value Type Property</strong>
        </p>
        <p align="left">
If the type of the property is a value type, the case is less clear-cut because value
types can’t be null. This means that a Null Guard is never appropriate. However, directly
consuming a value type may still be inappropriate. In fact, <a href="http://blog.ploeh.dk/2011/05/25/DesignSmellPrimitiveObsession.aspx">it’s
only appropriate if the class can meaningfully accept and handle any value of that
type</a>.
</p>
        <p align="left">
If, for example, the class can really only handle a certain subset of all possible
values, a Guard Clause must be introduced. Consider this example:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">int</font>
              </span> RetryCount
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
        </div>
        <p align="left">
This property might be used to set the appropriate number or retries for a given operation.
The problem with using an automatic property is that it’s possible to assign a negative
value to it, and that wouldn’t make any sense. One possible remedy is to add a Guard
Clause:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">int</font>
              </span> retryCount;</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">int</font>
              </span> RetryCount</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.retryCount;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">set</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (<span style="color: "><font color="#0000ff">value</font></span> &lt;
0)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentOutOfRangeException</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.retryCount
= <span style="color: "><font color="#0000ff">value</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
However, in many cases, exposing a primitive property is more likely to be a case
of Primitive Obsession.
</p>
        <p>
          <strong>Improved Design: Guard Clause</strong>
        </p>
        <p>
As I described above, the most immediate fix for automatic properties is to properly
implement the property with a Guard Clause. This ensures that the class’ invariants
are properly encapsulated.
</p>
        <p>
          <strong>Improved Design: Value Object Property</strong>
        </p>
        <p>
When the automatic property is a value type, a Guard Clause may still be in order.
However, when the property is really a symptom of Primitive Obsession, a better alternative
is to introduce a proper Value Object.
</p>
        <p>
Consider, as an example, this property:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">int</font>
              </span> Temperature
{ <span style="color: "><font color="#0000ff">get</font></span>; <span style="color: "><font color="#0000ff">set</font></span>;
}</font>
          </pre>
        </div>
        <p>
This is bad design for a number of reasons. It doesn’t communicate the unit of measure
and allows unbounded values to be assigned. What happens if –100 is assigned? If the
unit of measure is Celcius it should succeed, although in the case when it’s Kelvin,
it should fail. No matter the unit of measure, attempting to assign int.MinValue should
fail.
</p>
        <p>
A more robust design can be had if we introduce a new Temperature type and change
the property to have that type. Apart from protection of invariants it would also
encapsulate conversion between different temperature scales.
</p>
        <p>
However, if that Value Object is implemented as a reference type the situation is
equivalent to the situation described above, and a Null Guard is necessary. Only in
the case where the Value Object is implemented as a value type is an anonymous property
appropriate.
</p>
        <p>
The bottom line is that automatic properties are rarely appropriate. In fact, they
are only appropriate when the type of the property is a value type and all conceivable
values are allowed. Since there <em>are</em> a few cases where automatic properties
are appropriate their use can’t be entirely dismissed, but it should be treated as
warranting further investigation. It’s a code smell, not an anti-pattern.
</p>
        <p>
On a different note properties also violate the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Law
of Demeter</a>, but that’s the topic of a future blog post…
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=70e00361-46ae-4406-a148-da382b1c8d76" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Design Smell: Primitive Obsession</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/25/DesignSmellPrimitiveObsession.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,0207ab74-33c5-4fef-8b30-948a7e741262.aspx</id>
    <published>2011-05-25T17:03:31.6278491+02:00</published>
    <updated>2011-05-25T17:03:31.6278491+02:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This post is the second in a series about <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">Poka-yoke
Design</a> – also known as <em>encapsulation</em>.
</p>
        <p>
Many classes have a tendency to consume or expose primitive values like integers and
strings. While such primitive types exist on any platform, they tend to lead to procedural
code. Furthermore they often break encapsulation by allowing invalid values to be
assigned.
</p>
        <p>
This problem has been addressed many times before. Years ago <a href="http://lostechies.com/jimmybogard/">Jimmy
Bogard</a> provided an <a href="http://grabbagoft.blogspot.com/2007/12/dealing-with-primitive-obsession.html">excellent
treatment of the issue, as well as guidance on how to resolve it</a>. In relation
to <a href="http://autofixture.codeplex.com/">AutoFixture</a> I also <a href="http://blog.ploeh.dk/2009/05/01/DealingWithConstrainedInput.aspx">touched
upon the subject some time ago</a>. As such, the current post is mostly a placeholder.
</p>
        <p>
However, it’s worth noting that both Jimmy’s and my own post address the concern that
strings and integers do not sufficiently encapsulate the concepts of Zip codes and
phone numbers.
</p>
        <ul>
          <li>
When a Zip code is represented as a string it’s possible to assign values such as
null, string.Emtpy, “foo”, very long strings, etc. Jimmy’s ZipCode class encapsulates
the concept by guaranteeing that an instance can only be successfully created with
a correct value. 
</li>
          <li>
When a Danish phone number is represented as an integer it’s possible to assign values
such as –98, 0, int.MaxValue, etc. Once again the DanishPhoneNumber class from the
above example encapsulates the concept by guaranteeing that an instance can only be
successfully created with a correct value.</li>
        </ul>
        <p>
Encapsulation is broken unless the concept represented by a primitive value can truly
take <em>any</em> of the possible values of the primitive type. This is rarely the
case.
</p>
        <p>
          <strong>Design Smell:</strong>
        </p>
        <p>
A class consumes a primitive type. However, further analysis shows that not all possible
values of the type are legal values.
</p>
        <p>
          <strong>Improved Design:</strong>
        </p>
        <p>
Encapsulate the primitive value in a Value Object that contains appropriate Guard
Clauses etc. to guarantee that only valid instances are possible.
</p>
        <p>
Primitives tend to not be fail-safe, but encapsulated Value Objects are.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0207ab74-33c5-4fef-8b30-948a7e741262" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Design Smell: Temporal Coupling</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,1cd9a774-cf57-469b-80b5-ddaa24e704c8.aspx</id>
    <published>2011-05-24T16:00:42.1074293+02:00</published>
    <updated>2011-05-24T16:00:42.1074293+02:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This post is the first in a series about <a href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx">Poka-yoke
Design</a> – also known as <em>encapsulation</em>.
</p>
        <p>
A common problem in API design is <em>temporal coupling</em>, which occurs when there’s
an implicit relationship between two, or more, members of a class requiring clients
to invoke one member before the other. This tightly couples the members in the temporal
dimension.
</p>
        <p>
The archetypical example is the use of an Initialize method, although copious other
examples can be found – even in the BCL. As an example, this usage of <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.endpointaddressbuilder.aspx">EndpointAddressBuilder</a> compiles,
but fails at run-time:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> b
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">EndpointAddressBuilder</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> e
= b.ToEndpointAddress();</font>
          </pre>
        </div>
        <p>
It turns out that at least an URI is required before an EndpointAddress can be created.
The following code compiles <em>and</em> succeeds at run-time:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> b
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">EndpointAddressBuilder</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">b.Uri
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">UriBuilder</font></span>().Uri;</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> e
= b.ToEndpointAddress();</font>
          </pre>
        </div>
        <p>
The API provides no hint that this is necessary, but there’s a temporal coupling between
the Uri property and the ToEndpointAddress method.
</p>
        <p>
In the rest of the post I will provide a more complete example, as well as a guideline
to improve the API towards Poka-yoke Design.
</p>
        <p>
          <strong>Smell Example</strong>
        </p>
        <p>
This example describes a more abstract code smell, exhibited by the Smell class. The
public API looks like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">Smell</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Initialize(<span style="color: "><font color="#0000ff">string</font></span> name)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> Spread()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Semantically the name of the Initialize method is obviously a clue, but on a structural
level this API gives us no indication of temporal coupling. Thus, code like this compiles,
but throws an exception at run-time:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> s
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Smell</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> n
= s.Spread();</font>
          </pre>
        </div>
        <p>
It turns out that the Spread method throws an InvalidOperationException because the
Smell has not been initialized with a name. The problem with the Smell class is that
it doesn’t properly protect its invariants. In other words, encapsulation is broken.
</p>
        <p>
To fix the issue the Initialize method must be invoked before the Spread method:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> sut
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Smell</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">sut.Initialize(<span style="color: "><font color="#a31515">"Sulphur"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> n
= sut.Spread();</font>
          </pre>
        </div>
        <p>
While it’s possible to write unit tests that explore the behavior of the Smell class,
it would be better if the design was improved to enable the <a href="http://blog.ploeh.dk/2011/04/29/FeedbackMechanismsAndTradeoffs.aspx">compiler
to provide feedback</a>.
</p>
        <p>
          <strong>Improvement: Constructor Injection</strong>
        </p>
        <p>
Encapsulation (Poka-yoke style) requires that the class can never be in an inconsistent
state. Since the name of the smell is required, a guarantee that it is always available
must be built into the class. If no good default value is available, the name must
be requested via the constructor:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Fragrance</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IFragrance</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#0000ff">string</font></span> name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> Fragrance(<span style="color: "><font color="#0000ff">string</font></span> name)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (name
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"name"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.name
= name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">string</font></span> Spread()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.name;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This effectively guarantees that the name is always available in all instances of
the class. There  are also positive side effects:
</p>
        <ul>
          <li>
The cyclomatic complexity of the class has been reduced 
</li>
          <li>
The class is now immutable, and thereby thread-safe</li>
        </ul>
        <p>
However, there are times when the original version of the class implements an interface
that causes the temporal coupling. It might have looked like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">ISmell</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Initialize(<span style="color: "><font color="#0000ff">string</font></span> name);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">string</font></span> Spread();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
In many cases the injected value (name) is unknown until run-time, in which case straight
use of the constructor seems prohibitive – after all, <a href="http://blog.ploeh.dk/2011/02/28/InterfacesAreAccessModifiers.aspx">the
constructor is an implementation detail and not part of the loosely coupled API</a>.
When programming against an interface it’s not possible to invoke the constructor.
</p>
        <p>
There’s a solution for that as well.
</p>
        <p>
          <strong>Improvement: Abstract Factory</strong>
        </p>
        <p>
To decouple the methods in the ISmell (ha ha) interface the Initialize method can
be moved to a new interface. Instead of mutating the (inconsistent) state of a class,
the Create method (formerly known as Initialize) returns a new instance of the IFragrance
interface:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IFragranceFactory</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IFragrance</font></span> Create(<span style="color: "><font color="#0000ff">string</font></span> name);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The implementation is straightforward:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">FragranceFactory</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IFragranceFactory</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#2b91af">IFragrance</font></span> Create(<span style="color: "><font color="#0000ff">string</font></span> name)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (name
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"name"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fragrance</font></span>(name);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This enables encapsulation because both the FragranceFactory and Fragrance classes
protect their invariants. They can never be in an inconsistent state. A client previously
interacting with the ISmell interface can use the IFragranceFactory/IFragrance combination
to achieve the same funcionality:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> f
= factory.Create(name);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> n
= f.Spread();</font>
          </pre>
        </div>
        <p>
This is better because improper use of the API can now be detected by the compiler
instead of at run-time. An interesting side-effect by moving towards a more statically
declared interaction structure is that classes tend towards immutability. Immutable
classes are automatically thread-safe, which is an increasingly important trait in
the (relatively) new multi-core era.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1cd9a774-cf57-469b-80b5-ddaa24e704c8" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Poka-yoke Design: From Smell to Fragrance</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,fc0d0cde-e12f-4589-b34e-469c05f7c946.aspx</id>
    <published>2011-05-24T15:57:39.0390823+02:00</published>
    <updated>2011-05-31T15:29:49.7456887+02:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Encapsulation is one of the most misunderstood aspects of object-oriented programming.
Most people seem to think that the related concept of <em>information hiding</em> simply
means that private fields should be exposed by public properties (or getter/setter
methods in languages that don’t have native properties).
</p>
        <p>
Have you ever wondered what’s the <em>real</em> benefit to be derived from code like
the following?
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> name;</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">string</font>
              </span> Name</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.name;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">set</font></span> { <span style="color: "><font color="#0000ff">this</font></span>.name
= <span style="color: "><font color="#0000ff">value</font></span>; }</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This feels awfully much like redundant code to me (and <a href="http://msdn.microsoft.com/en-us/library/bb384054.aspx">automatic
properties</a> are not the answer – it’s just a compiler trick that still creates
private backing fields). No information is actually hidden. <a href="http://lostechies.com/derickbailey/">Derick
Bailey</a> has a <a href="http://lostechies.com/derickbailey/2011/03/28/encapsulation-youre-doing-it-wrong/">good
piece on why this view of encapsulation is too narrow</a>, so I’m not going to reiterate
all his points here.
</p>
        <p>
So then what <em>is</em> encapsulation?
</p>
        <p>
The whole point of object-orientation is to produce cohesive pieces of code (classes)
that solve given problems once and for all, so that programmers can use those classes
without having to learn about the intricate details of the implementations.
</p>
        <blockquote>
          <p>
This is what encapsulation is all about: exposing a solution to a problem without
requiring the consumer to fully understand the problem domain.
</p>
        </blockquote>
        <p>
This is what all well-designed classes do.
</p>
        <ul>
          <li>
You don’t have to know the intricate details of <a href="http://en.wikipedia.org/wiki/Tabular_Data_Stream">TDS</a> to
use ADO.NET against SQL Server. 
</li>
          <li>
You don’t have to know the intricate details of painting on the screen to use WPF
or Windows Forms. 
</li>
          <li>
You don’t have to know the intricate details of Reflection to use a DI Container. 
</li>
          <li>
You don’t have to know how to efficiently sort a list in order to efficiently sort
a list in .NET. 
</li>
          <li>
Etc.</li>
        </ul>
        <p>
What makes encapsulation so important is exactly this trait. The class must hide the
information it encapsulates in order to protect it against ‘naïve’ users. <a href="http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29">Wikipedia
has this to say</a>:
</p>
        <blockquote>
          <p>
Hiding the internals of the object protects its integrity by preventing users from
setting the internal data of the component into an invalid or inconsistent state.
</p>
        </blockquote>
        <p>
Keep in mind that users are <em>expected</em> to not fully understand the internal
implementation of a class. This makes it obvious what encapsulation is really about:
</p>
        <blockquote>
          <p>
Encapsulation is a fail-safe mechanism.
</p>
        </blockquote>
        <p>
By corollary, encapsulation does <em>not</em> mean hiding complexity. Whenever complexity
is hidden (<a href="http://blog.ploeh.dk/2011/04/27/ProviderIsNotAPattern.aspx">as
is the case for Providers</a>) feedback time increases. Rapid feedback is much preferred,
so delaying feedback is not desirable if it can be avoided.
</p>
        <blockquote>
          <p>
Encapsulation is not about hiding complexity, but conversely exposing complexity in
a fail-safe manner.
</p>
        </blockquote>
        <p>
In Lean this is known as <a href="http://en.wikipedia.org/wiki/Poka-yoke">Poka-yoke</a>,
so I find it only fitting to think about encapsulation as <em>Poka-yoke Design</em>:
APIs that make it as hard as possible to do the wrong thing. Considering that <a href="http://blog.ploeh.dk/2011/04/29/FeedbackMechanismsAndTradeoffs.aspx">compilation
is the cheapest feedback mechanism</a>, it’s preferable to design APIs so that the
code can only compile when classes are used correctly.
</p>
        <p>
In a series of blog posts I will look at various design smells that break encapsulation,
as well as provide guidance on how to improve the design to make it safer, thus going
from smell to fragrance.
</p>
        <ol>
          <li>
            <a href="http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx">Design
Smell: Temporal Coupling</a>
          </li>
          <li>
            <a href="http://blog.ploeh.dk/2011/05/25/DesignSmellPrimitiveObsession.aspx">Design
Smell: Primitive Obsession</a>
          </li>
          <li>
            <a href="http://blog.ploeh.dk/2011/05/26/CodeSmellAutomaticProperty.aspx">Code Smell:
Automatic Property</a>
          </li>
          <li>
            <a href="http://blog.ploeh.dk/2011/05/27/DesignSmellRedundantRequiredAttribute.aspx">Design
Smell: Redundant Required Attribute</a>
          </li>
          <li>
            <a href="http://blog.ploeh.dk/2011/05/30/DesignSmellDefaultConstructor.aspx">Design
Smell: Default Constructor</a>
          </li>
        </ol>
        <p>
Postscript: <a href="http://blog.ploeh.dk/2011/05/31/AtTheBoundariesApplicationsAreNotObjectOriented.aspx">At
the Boundaries, Applications are Not Object-Oriented</a></p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=fc0d0cde-e12f-4589-b34e-469c05f7c946" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Tennis Kata with immutable types and a cyclomatic complexity of 1</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/16/TennisKataWithImmutableTypesAndACyclomaticComplexityOf1.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,300de4ea-0211-4921-8aed-9295b77e90e6.aspx</id>
    <published>2011-05-16T13:01:00+02:00</published>
    <updated>2011-05-16T17:40:21.7550291+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p align="left">
Recently I had the inclination to do the <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataTennis">Tennis
Kata</a> a couple of times. The first time I saw it I thought it wasn’t terribly interesting
as an exercise in C# development. It would basically just be an application of the <a href="http://en.wikipedia.org/wiki/State_pattern">State</a> pattern,
so I decided to make it a bit more interesting. More or less by intuition I decided
to give myself the following constraints:
</p>
        <ul>
          <li>
            <div align="left">All types must be immutable
</div>
          </li>
          <li>
            <div align="left">All members must have a <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic
complexity</a> of 1
</div>
          </li>
        </ul>
        <p align="left">
Now that’s more interesting :)
</p>
        <p align="left">
Given these constraints, what would be the correct approach? Given that this is a
finite state machine with a fixed number of states, the <a href="http://en.wikipedia.org/wiki/Visitor_pattern">Visitor</a> pattern
will be a good match.
</p>
        <p align="left">
Each player’s score can be modeled as a Value Object that can be one of these types:
</p>
        <ul>
          <li>
            <div align="left">ZeroPoints
</div>
          </li>
          <li>
            <div align="left">FifteenPoints
</div>
          </li>
          <li>
            <div align="left">ThirtyPoints
</div>
          </li>
          <li>
            <div align="left">FortyPoints
</div>
          </li>
          <li>
            <div align="left">AdvantagePoint
</div>
          </li>
          <li>
            <div align="left">GamePoint
</div>
          </li>
        </ul>
        <p align="left">
All of these classes implement the IPoints interface:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">IPoints</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IPoints</font></span> Accept(<span style="color: "><font color="#2b91af">IPoints</font></span> visitor);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IPoints</font></span> LoseBall();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IPoints</font></span> WinBall(<span style="color: "><font color="#2b91af">IPoints</font></span> opponentPoints);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IPoints</font></span> WinBall(<span style="color: "><font color="#2b91af">AdvantagePoint</font></span> opponentPoints);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IPoints</font></span> WinBall(<span style="color: "><font color="#2b91af">FortyPoints</font></span> opponentPoints);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p align="left">
The interesting insight here is that until the opponent's score reaches FortyPoints
nothing special happens. Those states can be effectively collapsed into the WinBall(IPoints)
method. However, when the opponent either has FortyPoints or AdvantagePoint, special
things happen, so IPoints has specialized methods for those cases. All implementations
should use <a href="http://en.wikipedia.org/wiki/Double_dispatch">double dispatch</a> to
invoke the correct overload of WinBall, so the Accept method must be implemented like
this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IPoints</font>
              </span> Accept(<span style="color: "><font color="#2b91af">IPoints</font></span> visitor)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span> visitor.WinBall(<span style="color: "><font color="#0000ff">this</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p align="left">
That’s the core of the Visitor pattern in action. When the implementer of the Accept
method is either FortyPoints or AdvantagePoint, the specialized overload will be invoked.
</p>
        <p align="left">
It’s now possible to create a context around a pair of IPoints (called a Game) to
implement a method to register that Player 1 won a ball:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">Game</font>
              </span> PlayerOneWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> newPlayerOnePoints
= <span style="color: "><font color="#0000ff">this</font></span>.PlayerTwoScore</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.Accept(<span style="color: "><font color="#0000ff">this</font></span>.PlayerOneScore);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> newPlayerTwoPoints
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.PlayerTwoScore.LoseBall();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Game</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
newPlayerOnePoints, newPlayerTwoPoints);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p align="left">
A similar method for player two simply reverses the roles. (I’m currently reading <a href="http://www.amazon.com/Lean-Architecture-Agile-Software-Development/dp/0470684208">Lean
Architecture</a>, but have yet to reach the chapter on <a href="http://en.wikipedia.org/wiki/Data,_Context_and_Interaction">DCI</a>.
However, considering what I’ve already read about DCI, this seems to fit the bill
pretty well… although I might be wrong on that account.)
</p>
        <p align="left">
The context calculates new scores for both players and returns the result as a new
instance of the Game class. This keeps the Game and IPoints implementations immutable.
</p>
        <p>
The new score for the winner depends on the opponent’s score, so the appropriate overload
of WinBall should be invoked. The Visitor implementation makes it possible to pick
the right overload without resorting to casts and <em>if</em> statements. As an example,
the FortyPoints class implements the three WinBall overloads like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IPoints</font>
              </span> WinBall(<span style="color: "><font color="#2b91af">IPoints</font></span> opponentPoints)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">GamePoint</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IPoints</font>
              </span> WinBall(<span style="color: "><font color="#2b91af">FortyPoints</font></span> opponentPoints)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">AdvantagePoint</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IPoints</font>
              </span> WinBall(<span style="color: "><font color="#2b91af">AdvantagePoint</font></span> opponentPoints)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
It’s also important to correctly implement the LoseBall method. In most cases, losing
a ball doesn’t change the current state of the loser, in which case the implementation
looks like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IPoints</font>
              </span> LoseBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
However, when the player has advantage and loses the ball, he or she loses the advantage,
so for the AdvantagePoint class the implementation looks like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">IPoints</font>
              </span> LoseBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">FortyPoints</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
To keep things simple I decided to implicitly model <em>deuce</em> as both players
having FortyPoints, so there’s not explicit Deuce class. Thus, AdvantagePoint returns
FortyPoints when losing the ball.
</p>
        <p>
Using the Visitor pattern it’s possible to keep the cyclomatic complexity at 1. The
code has no branches or loops. It’s immutable to boot, so a game might look like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">Fact</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> PlayerOneWinsAfterHardFight()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> game
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Game</font></span>()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerOneWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerOneWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerOneWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerTwoWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerTwoWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerTwoWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerTwoWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerOneWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerOneWinsBall()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
.PlayerOneWinsBall();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Assert</font></span>.Equal(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">GamePoint</font></span>(),
game.PlayerOneScore);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Assert</font></span>.Equal(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">FortyPoints</font></span>(),
game.PlayerTwoScore);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
In case you’d like to take a closer look at the code I’m attaching it to this post.
It was driven completely by using the <a href="http://blog.ploeh.dk/2010/10/08/AutoDataTheoriesWithAutoFixture.aspx">AutoFixture.Xunit
extension</a>, so if you are interested in idiomatic <a href="http://autofixture.codeplex.com/">AutoFixture</a> code
it’s also a good example of that.
</p>
        <a href="http://blog.ploeh.dk/content/binary/TennisKata.zip">TennisKata.zip (3.09
MB)</a>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=300de4ea-0211-4921-8aed-9295b77e90e6" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Generic unit testing with xUnit.net</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/09/GenericUnitTestingWithXUnitnet.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,991d4f09-1bc8-4550-81cc-a11309d07555.aspx</id>
    <published>2011-05-09T14:37:17.3163696+02:00</published>
    <updated>2011-05-09T14:37:17.3163696+02:00</updated>
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <category term="xUnit.net" label="xUnit.net" scheme="http://blog.ploeh.dk/CategoryView,category,xUnitnet.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Generics in .NET are wonderful, but sometimes when doing Test-Driven Development against
a generic class I’ve felt frustrated because I’ve been feeling that dropping down
to the lowest common denominator and testing against, say, Foo&lt;object&gt; doesn’t
properly capture the variability inherent in generics. On the other hand, writing
the same test for five different types of T have seemed too wasteful (not to mention
boring) to bother with.
</p>
        <p>
That’s until it occurred to me that in xUnit.net (and possibly other unit testing
frameworks) I can define a generic test class. As an example, I wanted to test-drive
a class with this class definition:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Interval</font>
              </span>&lt;T&gt;</font>
          </pre>
        </div>
        <p>
Instead of writing a set of tests against Interval&lt;object&gt; I rather wanted to
write a set of tests against a representative set of T. This is so easy to do that
I don’t know why I haven’t thought of it before. I simply declared the test class
itself as a generic class:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">abstract</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">IntervalFacts</font>
              </span>&lt;T&gt;</font>
          </pre>
        </div>
        <p>
The reason I declared the class as abstract is because that effectively prevents the
test runner from trying to run the test methods directly on the class. That would
fail because T is still open. However, it enabled me to write tests like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">Theory</font></span>, <span style="color: "><font color="#2b91af">AutoCatalogData</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> MinimumIsCorrect(<span style="color: "><font color="#2b91af">IComparable</font></span>&lt;T&gt;
first, </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IComparable</font></span>&lt;T&gt;
second)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> sut
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Interval</font></span>&lt;T&gt;(first,
second);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IComparable</font></span>&lt;T&gt;
result = sut.Minimum;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Assert</font></span>.Equal(result,
first);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
In this test, I also use <a href="http://autofixture.codeplex.com/">AutoFixture</a>’s <a href="http://blog.ploeh.dk/2010/10/08/AutoDataTheoriesWithAutoFixture.aspx">xUnit.net
extension</a>, but that’s completely optional. You might as well just write an old-fashioned
unit test, but then you’ll need a <a href="http://blog.ploeh.dk/2009/02/13/SUTFactory.aspx">SUT
Factory</a> that can resolve generics. If you don’t use AutoFixture any other (auto-mocking)
container will do, and if you don’t use one of those, you can define a <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory
Method</a> that creates appropriate instances of T (and, in this particular case,
instances of IComparable&lt;T&gt;).
</p>
        <p>
In the above example I used a [Theory], but I might as well have been using a [Fact]
as long as I had a container or a Factory Method to create the appropriate instances.
</p>
        <p>
The above test doesn’t execute in itself because the owning class is abstract. I needed
to declare an appropriate set of constructed types for which I wanted the test to
run. To do that, I defined the following test classes:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">DecimalIntervalFacts</font>
              </span> : <span style="color: "><font color="#2b91af">IntervalFacts</font></span>&lt;<span style="color: "><font color="#0000ff">decimal</font></span>&gt;
{ }</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">StringIntervalFacts</font>
              </span> : <span style="color: "><font color="#2b91af">IntervalFacts</font></span>&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;
{ }</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">DateTimeIntervalFacts</font>
              </span> : <span style="color: "><font color="#2b91af">IntervalFacts</font></span>&lt;<span style="color: "><font color="#2b91af">DateTime</font></span>&gt;
{ }</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">TimSpanIntervalFacts</font>
              </span> : <span style="color: "><font color="#2b91af">IntervalFacts</font></span>&lt;<span style="color: "><font color="#2b91af">TimeSpan</font></span>&gt;
{ }</font>
          </pre>
        </div>
        <p>
The only thing these classes do is to each pick a particular type for T. However,
since they are concrete classes with test methods, the test runner will pick up the
test cases and execute them. This means that the single unit test I wrote above is
now being executed four times – one for each constructed type.
</p>
        <p>
It’s even possible to specialize the generic class and add more methods to a single
specialized class. As a sanity check I wanted to write a set of tests specifically
against Interval&lt;int&gt;, so I added this class as well:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">Int32IntervalFacts</font>
              </span> : <span style="color: "><font color="#2b91af">IntervalFacts</font></span>&lt;<span style="color: "><font color="#0000ff">int</font></span>&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">Theory</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">InlineData</font></span>(0, 0, 0, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1, 1, -1, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1, 1, 0, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1, 1, 1, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1, 1, -2, <span style="color: "><font color="#0000ff">false</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1, 1, 2, <span style="color: "><font color="#0000ff">false</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Int32ContainsReturnsCorrectResult(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">int</font></span> minimum, <span style="color: "><font color="#0000ff">int</font></span> maximum, <span style="color: "><font color="#0000ff">int</font></span> value,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">bool</font></span> expectedResult)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> sut
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Interval</font></span>&lt;<span style="color: "><font color="#0000ff">int</font></span>&gt;(minimum,
maximum);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> result
= sut.Contains(value);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">Assert</font></span>.Equal(expectedResult,
result);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
More tests...</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
When added as an extra class in addition to the four ‘empty’ concrete classes above,
it now causes each generic method to be executed five times, whereas the above unit
test is only executed for the Int32IntervalFacts class (on the other hand it’s a parameterized
test, so the method is actually executed six times).
</p>
        <p>
It’s also possible to write parameterized tests in the generic test class itself:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">Theory</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1,
-1, <span style="color: "><font color="#0000ff">false</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1,
0, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(-1,
1, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(0,
-1, <span style="color: "><font color="#0000ff">false</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(0,
0, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(0,
1, <span style="color: "><font color="#0000ff">true</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(1,
-1, <span style="color: "><font color="#0000ff">false</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(1,
0, <span style="color: "><font color="#0000ff">false</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">InlineData</font></span>(1,
1, <span style="color: "><font color="#0000ff">false</font></span>)]</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> ContainsReturnsCorrectResult(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">int</font></span> minumResult, <span style="color: "><font color="#0000ff">int</font></span> maximumResult,</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">bool</font></span> expectedResult)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#008000">//
Test method body</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Since this parameterized test in itself has 9 variations and is declared by IntervalFacts&lt;T&gt;
which now has 5 constructed implementers, this single test method will be executed
9 x 5 = 45 times!
</p>
        <p>
Not that the the number of executed tests in itself is any measure of the quality
of the test, but I do appreciate the ability to write generic unit tests against generic
types.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=991d4f09-1bc8-4550-81cc-a11309d07555" />
      </div>
    </content>
  </entry>
  <entry>
    <title>AutoFixture 2.1</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/02/AutoFixture21.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,420377cb-f645-4bde-a696-102faac51e86.aspx</id>
    <published>2011-05-02T20:34:52.8542369+02:00</published>
    <updated>2011-05-04T15:02:18.1777179+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Since I announced <a href="http://autofixture.codeplex.com/">AutoFixture</a> 2.1 beta
1 no issues have been reported, so I’ve now promoted the release to the official 2.1
release. This means that if you already downloaded AutoFixture 2.1 beta 1, you already
have the 2.1 binaries. If not, you can head over to the <a href="http://autofixture.codeplex.com/releases/view/64686">release
page</a> to get it.
</p>
        <p>
The NuGet packages will soon be available.
</p>
        <p>
          <strong>Update</strong> (2011.5.4): The NuGet packages are now available.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=420377cb-f645-4bde-a696-102faac51e86" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Azure migration smell: SQL Server over-utilization</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/05/02/WindowsAzureMigrationSmellSQLServerOverutilization.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,6ee7b4b9-cb98-4360-a252-cfc6ab99d7b4.aspx</id>
    <published>2011-05-02T14:23:49.1901867+02:00</published>
    <updated>2011-05-02T14:25:27.8458515+02:00</updated>
    <category term="Azure" label="Azure" scheme="http://blog.ploeh.dk/CategoryView,category,Azure.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Recently I partook in a Windows Azure migration workshop, helping developers from
existing development organizations port their applications to Windows Azure. Once
more an old design smell popped up: <em>SQL Server over-utilization</em>. This ought
to be old news to anyone with experience designing software on the Wintel stack, but
apparently it bears repetition:
</p>
        <blockquote>
          <p>
Don’t put logic in your database. SQL Server should be used only for persistent storage
of data.
</p>
        </blockquote>
        <p>
(Yes: this post <em>is</em> written in 2011…)
</p>
        <p>
Many years ago I heard that role described as a ‘bit bucket’ – you put in data and
pull it out again, and that’s all you do. No fancy stored procedures or functions
or triggers.
</p>
        <p>
Why wouldn’t we want to use the database if we have one? Scalability is the answer.
SQL Server doesn’t scale horizontally. You can’t add more servers to take the load
off a database server (well, some of my old colleagues will argue that this is possible
with Oracle, and that may be true, but with SQL Server it’s impossible).
</p>
        <p>
Yes, we can jump through hoops like partitioning and splitting the database up into
several smaller databases, but it still doesn’t give us horizontal scalability. SQL
Server is a bottleneck in any system in which it takes part.
</p>
        <p>
How is this relevant to Windows Azure? It’s relevant for two important reasons:
</p>
        <ul>
          <li>
There’s an upper size limit on SQL Azure. Currently that size limit is 50 GB, and
while it’s likely to grow in the future, there’s going to be a ceiling for a long
time. 
</li>
          <li>
You can’t fine tune the hardware for performance. The server runs on virtual hardware.</li>
        </ul>
        <p>
Development organizations that rely heavily on the database for execution of logic
often need expensive hardware and experienced DBAs to squeeze extra performance out
of the database servers. Such people know that write-intensive/append-only tables
work best with one type of RAID, while read-intensive tables are better hosted on
other file groups on different disks with different RAID configurations.
</p>
        <p>
With SQL Azure you can just forget about all that.
</p>
        <p>
The bottom line is that there are fundamental rules for software development that
you must follow if you want to be able to successfully migrate to Windows Azure. I
previously described an <a href="http://blog.ploeh.dk/2010/10/14/WindowsAzureMigrationSanityCheck.aspx">even
simpler sanity check you should perform</a>, but after that you should take a good
look at your database.
</p>
        <p>
The best solution is if you can completely replace SQL Server with Azure’s very scalable
storage services, but those <a href="http://blog.ploeh.dk/2011/01/24/ScalableDoesntMeanFast.aspx">come
with their own set of challenges</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=6ee7b4b9-cb98-4360-a252-cfc6ab99d7b4" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Feedback mechanisms and tradeoffs</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/04/29/FeedbackMechanismsAndTradeoffs.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,aec9ab37-ac49-4e6f-b875-a236a47a6ca1.aspx</id>
    <published>2011-04-29T15:02:14.4316943+02:00</published>
    <updated>2011-04-29T15:02:14.4316943+02:00</updated>
    <category term="Productivity" label="Productivity" scheme="http://blog.ploeh.dk/CategoryView,category,Productivity.aspx" />
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <em>Rapid feedback</em> is one of the cornerstones of agile development. The faster
we can get feedback, the less it costs to correct errors. Unit testing is one of the
ways to get feedback, but not the only one. Each way we can get feedback comes with
its own advantages and disadvantages.
</p>
        <p>
In my experience there’s a tradeoff between the cost of setting up a feedback mechanism
and the level of confidence we can get from it. This is quite intuitive to most people,
but I’ve rarely seen it explicitly described. The purpose of this post is to explicitly
describe and relate those different mechanisms.
</p>
        <p>
          <strong>Compilation</strong>
        </p>
        <p>
In compiled languages, compilation provides the first level of feedback. I think a
lot of people don’t think about this as feedback as (for compiled languages) it’s
a necessary step before the code can be executed.
</p>
        <p>
The level of confidence may not be very high – we tend to laugh at statements like
‘if it compiles, it works’. However, the compiler still catches a lot of mistakes.
Think about it: does your code always compile, or do you sometimes get compilation
errors? Do you sometimes try to compile your code just to see if it’s possible? I
certainly do, and that’s because the compiler is always available, and it’s the first
and fastest level of feedback we get.
</p>
        <p>
Code can be designed to take advantage of this verification step. Constructor Injection,
for example, ensures that we can’t create a new instance of a class without supplying
it with its <em>required</em> dependencies.
</p>
        <p>
It’s also interesting to note that anecdotal evidence seems to suggest that unit testing
is more prevalent for interpreted languages. That makes a lot of sense, because as
developers we need feedback as soon as possible, and if there’s no compiler we must
reach for the next level of feedback mechanism.
</p>
        <p>
          <strong>Static code analysis</strong>
        </p>
        <p>
The idea of static code analysis isn’t specific to .NET, but in certain versions of
Visual Studio we have Code Analysis (which is also available as FxCop). Static code
analysis is a step up from compilation – not only is code checked for syntactical
correctness, but it’s also checked against a set of known anti-patterns and idioms.
</p>
        <p>
Static code analysis is encapsulated expert knowledge, yet surprisingly few people
use it. I think part of the reason for this is because the ratio of time against confidence
isn’t as compelling as with other feedback mechanism. It takes some time to run the
analysis, but like compilation the level of confidence gained from getting a clean
result is not very high.
</p>
        <p>
Personally, I use static code analysis once in a while (e.g. before checking in code
to the default branch), but not as often as other feedback mechanisms. Still, I think
this type of feedback mechanism is under-utilized.
</p>
        <p>
          <strong>Unit testing</strong>
        </p>
        <p>
Running a unit test suite is one of the most efficient ways to gain rapid feedback.
The execution time is often comparable to running static code analysis while the level
of confidence is much higher.
</p>
        <p>
Obviously a successful unit test execution is no guarantee that the final application
works as intended, but it’s a much better indicator than the two previous mechanisms.
When presented with the choice of using either static code analysis or unit tests,
I prefer unit tests every time because the confidence level is much higher.
</p>
        <p>
If you have sufficiently high code coverage I’d say that a successful unit test suite
is enough confidence to check in code and let continuous integration take care of
the rest.
</p>
        <blockquote>
          <p>
Keep in mind that continuous integration and other types of automated builds are feedback
mechanisms. If you institute rules where people are ‘punished’ for checking in code
that breaks the build, you effectively disable the automated build as a source of
feedback.
</p>
        </blockquote>
        <p>
Thus, the rest of these feedback mechanisms should be used rarely (if at all) on developer
work stations.
</p>
        <p>
          <strong>Integration testing</strong>
        </p>
        <p>
Integration testing comes in several sub-categories. You can integrate multiple classes
from within the same library, or integrate multiple libraries while still using <a href="http://xunitpatterns.com/Test%20Double.html">Test
Doubles</a> instead of out-of-process resources. At this level, the cost/confidence
ratio is comparable to unit testing.
</p>
        <p>
          <strong>Subcutaneous testing</strong>
        </p>
        <p>
A more full level of integration testing comes when all resources are integrated,
but the tests are still driven by code instead of through the UI. While this gives
a degree of confidence that is close to what you can get from a full systems test,
the cost of setting up the entire testing environment is <em>much</em> higher. In
many cases I consider this the realm of a dedicated testing department, as it’s often
a full-time job to maintain the suite of automation tools that enable such tests –
particularly if we are talking about distributed systems.
</p>
        <p>
          <strong>System testing</strong>
        </p>
        <p>
This is a test of the full system, often driven through the UI and supplemented with
manual testing (such as exploratory testing). This provides the highest degree of
confidence, but comes with a very high cost. It’s often at this level we find formal
acceptance tests.
</p>
        <p>
The time before we can get feedback at this level is often considerable. It may take
days or even weeks or months.
</p>
        <p>
          <strong>Understand the cost/confidence ratio</strong>
        </p>
        <p>
The purpose of this post has been to talk about different ways we can get feedback
when developing software. If we could get <em>instantaneous</em> feedback with <em>guaranteed</em> confidence
it would be easy to choose, but as this is not the case we must understand the benefits
and drawbacks of each mechanism.
</p>
        <p>
It’s important to realize that there are many mechanisms, and that we can combine
them in a staggered approach where we start with fast feedback (like the compiler)
with a low degree of confidence and then move through successive stages that each
provide a higher level of confidence.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=aec9ab37-ac49-4e6f-b875-a236a47a6ca1" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Provider is not a pattern</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/04/27/ProviderIsNotAPattern.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,ada0595f-f5c5-488e-b0ae-e179a6774188.aspx</id>
    <published>2011-04-27T14:14:52.9670554+02:00</published>
    <updated>2011-04-27T14:14:52.9670554+02:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p align="left">
Developers exposed to ASP.NET are likely to be familiar with the so-called <a href="http://msdn.microsoft.com/en-us/library/ms972319.aspx">Provider
pattern</a>. You see it a lot in that part of the BCL: <a href="http://msdn.microsoft.com/en-us/library/6b241xwt.aspx">Role
Provider</a>, <a href="http://msdn.microsoft.com/en-us/library/sx3h274z.aspx">Membership
Provider</a>, <a href="http://msdn.microsoft.com/en-us/library/014bec1k.aspx">Profile
Provider</a>, etc. Lots of text has already been written about Providers, but the
reason I want to add yet another blog post on the topic is because once in a while
I get the question on how it relates to Dependency Injection (DI).
</p>
        <p align="left">
Is Provider a proper way to do DI?
</p>
        <p align="left">
No, it has nothing to do with DI, but as it tries to mimic loose coupling I can understand
the confusion.
</p>
        <p align="left">
First things first. Let’s start with the name. Is it a pattern at all? Regular readers
of this blog may get the impression that I’m fond of calling everything and the kitchen
sink an anti-pattern. That’s not true because I <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">only
make that claim when I’m certain I can hold that position</a>, so I’m not going to
denounce Provider as an anti-pattern. On the contrary I will make the claim that Provider
is not a pattern at all.
</p>
        <p align="left">
A design pattern is not <em>invented</em> – it’s <em>discovered</em> as a repeated
solution to a commonly recurring problem. Providers, on the other hand, were invented
by Microsoft, and I’ve rarely seen them used outside their original scope. Secondly
I’d also dispute that they solve anything.
</p>
        <p align="left">
That aside, however, I want to explain why Provider is bad design:
</p>
        <ul>
          <li>
            <div align="left">It uses the Constrained Construction anti-pattern
</div>
          </li>
          <li>
            <div align="left">It hides complexity
</div>
          </li>
          <li>
            <div align="left">It prevents proper lifetime management
</div>
          </li>
          <li>
            <div align="left">It’s not testable
</div>
          </li>
        </ul>
        <p align="left">
In the rest of this post I will explain each point in detail, but before I do that
we need an example to look at. The <a href="http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx">old
OrderProcessor example</a> suffices, but instead of injecting IOrderValidator, IOrderCollector,
and IOrderShipper this variation uses Providers to provide instances of the Services:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#2b91af">SuccessResult</font>
              </span> Process(<span style="color: "><font color="#2b91af">Order</font></span> order)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IOrderValidator</font></span> validator
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">ValidatorProvider</font></span>.Validator;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">bool</font></span> isValid
= validator.Validate(order);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">if</font></span> (isValid)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">CollectorProvider</font></span>.Collector.Collect(order);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">ShipperProvider</font></span>.Shipper.Ship(order);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.CreateStatus(isValid);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p align="left">
The ValidatorProvider uses the configuration system to create and return an instance
of IOrderValidator:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">static</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">IOrderValidator</font>
              </span> Validator</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">get</font></span></font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> section
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">OrderValidationConfigurationSection</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">               
.GetSection();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> typeName
= section.ValidatorTypeName;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> type
= <span style="color: "><font color="#2b91af">Type</font></span>.GetType(typeName, <span style="color: "><font color="#0000ff">true</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> obj
= <span style="color: "><font color="#2b91af">Activator</font></span>.CreateInstance(type);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">return</font></span> (<span style="color: "><font color="#2b91af">IOrderValidator</font></span>)obj;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p align="left">
There are lots of details I omitted here. I could have saved the reference for later
use instead of creating a new instance each time the property is accessed. In that
case I would also have had to make the code thread-safe, so I decided to skip that
complexity. The code could also be more defensive, but I’m sure you get the picture.
</p>
        <p align="left">
The type name is defined in the app.config file like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">&lt;</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#a31515">orderValidation</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">
              </font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">  </font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#ff0000">type</font>
              </span>
              <span style="color: ">
                <font color="#0000ff">=</font>
              </span>"</font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">Ploeh.Samples.OrderModel.UnitTest.TrueOrderValidator,</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">       
Ploeh.Samples.OrderModel.UnitTest</font>
              </font>
            </span>
            <font style="font-size: 10pt">"</font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff"> /&gt;</font>
            </span>
          </pre>
        </div>
        <p align="left">
Obviously, CollectorProvider and ShipperProvider follow the same… blueprint.
</p>
        <p align="left">
This should be well-known to most .NET developers, so what’s wrong with this model?
</p>
        <p align="left">
          <strong>Constrained Construction</strong>
        </p>
        <p>
In <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">my book</a>’s
chapter on DI anti-patterns I describe the <em>Constrained Construction</em> anti-pattern.
Basically it occurs every time there’s an implicit constraint on the constructor of
an implementer. In the case of Providers the constraint is that each implementer must
have a default constructor. In the example the culprit is this line of code:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> obj
= <span style="color: "><font color="#2b91af">Activator</font></span>.CreateInstance(type);</font>
          </pre>
        </div>
        <p>
This constrains any implementation of IOrderValidator to have a default constructor,
which obviously means that the most fundamental DI pattern Constructor Injection is
out of the question.
</p>
        <p>
Variations of the Provider idiom is to supply an Initialize method with a context,
but this creates a temporal coupling while still not enabling us to inject arbitrary
Services into our implementations. I’m not going to repeat six pages of detailed description
of Constrained Construction here, but the bottom line is that you can’t fix it – you
have to refactor towards true DI – preferably Constructor Injection.
</p>
        <p>
          <strong>Hidden complexity</strong>
        </p>
        <p>
Providers hide the complexity of their implementations. This is not the same as <em>encapsulation</em>.
Rather it’s a dishonest API and the problem is that it just postpones the moment when
you discover how complex the implementation really is.
</p>
        <p>
When you implement a client and use code like the following everything looks <em>deceptively</em> simple:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">IOrderValidator</font>
              </font>
            </span>
            <font style="font-size: 10pt"> validator
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">ValidatorProvider</font></span>.Validator;</font>
          </pre>
        </div>
        <p>
However, if this is the only line of code you write it will fail, but you will not
notice until run-time. Check back to the implementation of the Validator property
if you need to refresh the implementation: there’s a lot of things that can go wrong
here:
</p>
        <ul>
          <li>
The appropriate configuration section is not available in the app.config file. 
</li>
          <li>
The ValidatorTypeName is not provided, or is null, or is malformed. 
</li>
          <li>
The ValidatorTypeName is correctly formed, but the type in question cannot be located
by Fusion. 
</li>
          <li>
The Type doesn’t have a default constructor. This is one of the other problems of
Constrained Construction: it can’t be statically enforced because a constructor is
not part of an <a href="http://blog.ploeh.dk/2011/02/28/InterfacesAreAccessModifiers.aspx">abstraction’s
API</a>. 
</li>
          <li>
The created type doesn’t implement IOrderValidator.</li>
        </ul>
        <p>
I’m sure I even forgot a thing or two, but the above list is sufficient for me. None
of these problems are caught by the compiler, so you don’t discover these issues until
you run an integration test. So much for rapid feedback.
</p>
        <p>
I don’t like APIs that lie about their complexity.
</p>
        <blockquote>
          <p>
Hiding complexity does not make an API easier to use; it makes it harder.
</p>
        </blockquote>
        <p>
An API that hides necessary complexity makes it impossible to discover problems at
compile time. It simply creates more friction.
</p>
        <p>
          <strong>Lifetime management issues</strong>
        </p>
        <p>
A Provider exerts too much control over the instances it creates. This is a variation
of the <em>Control Freak</em> anti-pattern (also from my book). In the current implementation
the Validator property totally violates the <a href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment">Principle
of least surprise</a> since it returns a new instance every time you invoke the getter.
I did this to keep the implementation simple (this is, after all, example code), but
a more normal implementation would reuse the same instance every time.
</p>
        <p>
However, reusing the same instance every time may be problematic in a multi-threaded
context (such as a web application) because you’ll need to make sure that the implementation
is thread-safe. Often, we’d much prefer to scope the lifetime of the Service to each
HTTP request.
</p>
        <p>
HTTP request scoping <em>can</em> be built into the Provider, but then it would <em>only</em> work
in web applications. That’s not very flexible.
</p>
        <p>
What’s even more problematic is that once we move away from the Singleton lifestyle
(not to be confused with the Singleton design pattern) we may have a memory leak at
hand, since the implementation may implement IDisposable. This can be solved by adding
a Release method to each Provider, but now we are moving so far into DI Container
territory that I find it far more reasonable to just use proper DI instead of trying
to reinvent the wheel.
</p>
        <p>
Furthermore, the fact that each Provider owns the lifetime of the Service it controls
makes it impossible to share resources. What if the implementation we want to use
implements several <a href="http://martinfowler.com/bliki/RoleInterface.html">Role
Interfaces</a> each served up by a different Provider? We might want to use that common
implementation to share or coordinate state across different Services, but that’s
not possible because we can’t share an instance across multiple providers.
</p>
        <p>
Even if we configure all Providers with the same concrete class, each will instantiate
and serve its own separate instance.
</p>
        <p>
          <strong>Testability</strong>
        </p>
        <p>
The Control Freak also impacts testability. Since a Provider creates instances of
interfaces based on XML configuration and Activator.CreateInstance, there’s no way
to inject a dynamic mock.
</p>
        <p>
It <em>is</em> possible to use hard-coded <a href="http://xunitpatterns.com/Test%20Double.html">Test
Doubles</a> such as <a href="http://xunitpatterns.com/Test%20Stub.html">Stubs</a> or <a href="http://xunitpatterns.com/Fake%20Object.html">Fakes</a> because
we can configure the XML with their type names, but even a <a href="http://xunitpatterns.com/Test%20Spy.html">Spy</a> is
problematic because we’ll rarely have an object reference to the Test Double.
</p>
        <p>
In short, the Provider idiom is not a good approach to loose coupling. Although Microsoft
uses it in some of their products, it only leads to problems, so there’s no reason
to mimic it. Instead, use Constructor Injection to create loosely coupled components
and wire them in the application’s <em>Composition Root</em> using the <a href="http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx">Register
Resolve Release</a> pattern.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ada0595f-f5c5-488e-b0ae-e179a6774188" />
      </div>
    </content>
  </entry>
  <entry>
    <title>AutoFixture 2.1 beta 1</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/04/19/AutoFixture21Beta1.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,41a52013-c79e-45da-ac5f-29a1d3ba6ed5.aspx</id>
    <published>2011-04-19T16:05:11.2931023+02:00</published>
    <updated>2011-04-19T16:05:11.2931023+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
It gives me great pleasure to announce that <a href="http://autofixture.codeplex.com/">AutoFixture</a> 2.1
beta 1 is now <a href="http://autofixture.codeplex.com/releases/view/64686">available
for download</a>. Compared to version 2.0 this release mostly contains added features
as well as a few bug fixes. The release page contains a list of the new features.
</p>
        <p>
The general availability of beta 1 of AutoFixture 2.1 marks the beginning of a trial
period. If no new issues are reported within the next few weeks, a final version 2.1
will be released. If too many issues are reported, a new beta version may be necessary.
</p>
        <p>
Please <a href="http://autofixture.codeplex.com/workitem/list/basic">report any issues</a> you
find.
</p>
        <p>
NuGet packages will follow the RTW version.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=41a52013-c79e-45da-ac5f-29a1d3ba6ed5" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Constructor strategies for AutoFixture</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/04/19/ConstructorStrategiesForAutoFixture.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,7c036292-a005-4205-8d5c-cd6de6c2378e.aspx</id>
    <published>2011-04-19T08:59:19.2992613+02:00</published>
    <updated>2011-04-19T08:59:19.2992613+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
When <a href="http://autofixture.codeplex.com/">AutoFixture</a> creates complex objects
it invokes the constructors of the types in question. When a class exposes more than
one constructor, the <a href="http://blog.ploeh.dk/2009/03/24/HowAutoFixtureCreatesObjects.aspx">default
behavior is to pick the constructor with the fewest number  of arguments</a>.
This is the exact opposite of most DI Containers that select the greediest constructor.
</p>
        <p>
For a DI Container it makes more sense to select the greediest constructor because
that maximizes the chance that all dependencies are properly being auto-wired.
</p>
        <p>
The reason that AutoFixture’s default behavior is different is that it maximizes the
chance that an object graph can be created at all. If a convenience overload is available,
this gives AutoFixture a better chance to compose the object graph.
</p>
        <p align="left">
This works well until a class comes along and introduces the wrong kind of ambiguity.
Consider this case of <em>Bastard Injection</em> (<a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">Dependency
Injection in .NET</a>, section 5.2):
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">Bastard</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IFoo</font></span> foo;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> Bastard()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
: <span style="color: "><font color="#0000ff">this</font></span>(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">DefaultFoo</font></span>())</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> Bastard(<span style="color: "><font color="#2b91af">IFoo</font></span> foo)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (foo
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"foo"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.foo
= foo;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#2b91af">IFoo</font></span> Foo</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.foo;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p align="left">
By default AutoFixture will use the default constructor which means that the Foo will
always be the instance of DefaultFoo owned by the Bastard class itself. This is problematic
if we wish to <a href="http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx">inject
and freeze a Test Double</a> because even if we freeze an IFoo instance, it will never
be injected because the default constructor is being invoked.
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Register&lt;<span style="color: "><font color="#2b91af">IFoo</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">DummyFoo</font></span>&gt;);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> b
= fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">Bastard</font></span>&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">Assert</font>
              </font>
            </span>
            <font style="font-size: 10pt">.IsAssignableFrom&lt;<span style="color: "><font color="#2b91af">DefaultFoo</font></span>&gt;(b.Foo);</font>
          </pre>
        </div>
        <p align="left">
As the above unit test demonstrates, even though the Register method call defines
a mapping from IFoo to DummyFoo, the Foo property is an instance of DefaultFoo. The
DummyFoo instance is never injected into the Bastard instance since the default constructor
is used.
</p>
        <p align="left">
Your first reaction in such a case should be to get rid of all convenience constructors
to make the the class’ constructor unambiguous. However, it’s also possible to change
AutoFixture’s behavior.
</p>
        <blockquote>
          <p align="left">
The following is a description of a feature that will be a available in AutoFixture
2.1. It’s not available in AutoFixture 2.0, but is already available in the code repository.
Thus, if you can’t wait for AutoFixture 2.1 you can download the source and build
it.
</p>
        </blockquote>
        <p align="left">
As always, AutoFixture’s very extensible interface makes it possible to change this
behavior. Constructor selection is guided by an interface called IConstructorQuery,
and while ModestConstructorQuery is the default implementation, there’s also an implementation
called GreedyConstructorQuery.
</p>
        <p align="left">
To change the behavior specifically for the Bastard class the Fixture instance must
be customized. The following unit test demonstrates how to do that.
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Customize&lt;<span style="color: "><font color="#2b91af">Bastard</font></span>&gt;(c
=&gt; c.FromFactory(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ConstructorInvoker</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">GreedyConstructorQuery</font></span>())));</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Register&lt;<span style="color: "><font color="#2b91af">IFoo</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">DummyFoo</font></span>&gt;);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> b
= fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">Bastard</font></span>&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">Assert</font>
              </font>
            </span>
            <font style="font-size: 10pt">.IsAssignableFrom&lt;<span style="color: "><font color="#2b91af">DummyFoo</font></span>&gt;(b.Foo);</font>
          </pre>
        </div>
        <p align="left">
Notice that the only difference from before is an additional call to the Customize
method where Bastard is modified to use greedy constructor selection. This changes
the factory for the Bastard type, but not for any other types.
</p>
        <p align="left">
If you’d rather prefer to completely change the overall constructor selection behavior
for AutoFixture you can add the GreedyConstructorQuery wrapped in a ConstructorInvoker
to the Fixture’s Customizations:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Customizations.Add(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ConstructorInvoker</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">GreedyConstructorQuery</font></span>()));</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Register&lt;<span style="color: "><font color="#2b91af">IFoo</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">DummyFoo</font></span>&gt;);</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> b
= fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">Bastard</font></span>&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">Assert</font>
              </font>
            </span>
            <font style="font-size: 10pt">.IsAssignableFrom&lt;<span style="color: "><font color="#2b91af">DummyFoo</font></span>&gt;(b.Foo);</font>
          </pre>
        </div>
        <p align="left">
In this unit test, the only change from the previous is that instead of assigning
the GreedyConstructorQuery specifically to Bastard, it’s now assigned as the new default
strategy. All specimens created by AutoFixture will be created by invoking their most
greedy constructor.
</p>
        <p align="left">
As always I find the default behavior more attractive, but the option to change behavior
is there if you need it.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7c036292-a005-4205-8d5c-cd6de6c2378e" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Enumerables are dynamic–also in AutoFixture</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/04/18/EnumerablesAreDynamicalsoInAutoFixture.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,0ba5b516-1130-4851-8a9d-ff72f49ec95f.aspx</id>
    <published>2011-04-18T15:22:29.6305407+02:00</published>
    <updated>2011-08-10T15:38:10.8535513+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
I just got a question about <a href="http://autofixture.codeplex.com/">AutoFixture</a>’s
way of dealing with enumerables, and since I suspect this is something that might
surprise a few people I found it reasonable to answer in a blog post.
</p>
        <p>
In short, this unit test <em>succeeds:</em></p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> expected
= fixture.CreateMany&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">Assert</font>
              </font>
            </span>
            <font style="font-size: 10pt">.False(expected.SequenceEqual(expected));</font>
          </pre>
        </div>
        <p>
If this doesn’t surprise you, then read the assertion again. The sequence is expected
to <em>not</em> equal itself!
</p>
        <p>
          <em>This behavior is by design.</em>
        </p>
        <p>
(I’ve always wanted to write that.) The reason is that the return type of the CreateMany
method is IEnumerable&lt;T&gt;, and that interface makes no guarantee that it will
return the same sequence every time you iterate over it. The implementation may be
a <a href="http://en.wikipedia.org/wiki/Generator_%28computer_science%29">Generator</a>.
</p>
        <p>
According to its principle of <a href="http://blog.ploeh.dk/2009/03/05/ConstrainedNonDeterminism.aspx">Constrained
Non-determinism</a>, AutoFixture goes to great lengths to ensure that since IEnumerable&lt;T&gt; <em>might
be</em> non-deterministic, it will be. This can be very useful in flushing out incorrect
assumptions made by the <a href="http://xunitpatterns.com/SUT.html">SUT</a>.
</p>
        <p align="left">
This behavior is carried forward by the <a href="http://blog.ploeh.dk/2011/02/08/CreatingGeneralPopulatedListsWithAutoFixture.aspx">MultipleCustomization</a>.
This unit test also succeeds:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.Customize(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">MultipleCustomization</font></span>());</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> expected
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">Assert</font>
              </font>
            </span>
            <font style="font-size: 10pt">.False(expected.SequenceEqual(expected));</font>
          </pre>
        </div>
        <p>
The behavior is the same because with the MultipleCustomization IEnumerable&lt;T&gt;
acts as a <a href="http://nblumhardt.com/2010/01/the-relationship-zoo/">relationship
type</a>. The class responsible for this behavior is called FiniteSequenceRelay, but
AutoFixture 2.1 will also ship with an alternative StableFiniteSequenceRelay which
wraps the sequence in a List&lt;T&gt;.
</p>
        <p>
To change the default behavior you can add the StableFiniteSequenceRelay to a Fixture’s
customizations:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> stableRelay
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">StableFiniteSequenceRelay</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Customizations.Add(stableRelay);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> expected
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateMany&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">Assert</font>
              </font>
            </span>
            <font style="font-size: 10pt">.True(expected.SequenceEqual(expected));</font>
          </pre>
        </div>
        <p>
The above unit test succeeds. Notice that the assertion now verifies that the sequence
of strings is equal to itself.
</p>
        <blockquote>
          <p>
Just like MultipleCustomization the StableFiniteSequenceRelay class will be available
in AutoFixture 2.1, but is not availale in 2.0.
</p>
        </blockquote>
        <p>
As always, it’s best to <a href="http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations.aspx">encapsulate
this behavior change into a Customization</a>:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">StableFiniteSequenceCustomization</font>
              </span> :</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">ICustomization</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Customize(<span style="color: "><font color="#2b91af">IFixture</font></span> fixture)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">var</font></span> stableRelay
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">StableFiniteSequenceRelay</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
fixture.Customizations.Add(stableRelay);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This makes it easier to bundle it with the MultipleCustomization if we want all the
other benefits of conventions for multiples:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">StableMultipeCustomization</font>
              </span> : </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">CompositeCustomization</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> StableMultipeCustomization()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
: <span style="color: "><font color="#0000ff">base</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">StableFiniteSequenceCustomization</font></span>(),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">MultipleCustomization</font></span>())</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
With the StableMultipleCustomization the following unit test now passes:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.Customize(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">StableMultipeCustomization</font></span>());</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> expected
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateAnonymous&lt;<span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#0000ff">string</font></span>&gt;&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#2b91af">
                <font style="font-size: 10pt">Assert</font>
              </font>
            </span>
            <font style="font-size: 10pt">.True(expected.SequenceEqual(expected));</font>
          </pre>
        </div>
        <p>
I still prefer the default behavior for its potential to act as an early warning system,
but as I realize that this behavior may be problematic in some scenarios, the StableFiniteSequenceRelay
provides an easy way to change that behavior.
</p>
        <p>
          <strong>Update (2011.8.10):</strong> StableFiniteSequenceCustomization is now part
of AutoFixture and will be available in AutoFixture 2.2.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0ba5b516-1130-4851-8a9d-ff72f49ec95f" />
      </div>
    </content>
  </entry>
  <entry>
    <title>MSDN Magazine article about CQRS on Windows Azure</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/04/05/MSDNMagazineArticleAboutCQRSOnWindowsAzure.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,e05fda1e-56a3-4aa6-8259-b943978f2843.aspx</id>
    <published>2011-04-05T21:52:57.5911247+02:00</published>
    <updated>2011-04-05T21:52:57.5911247+02:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Azure" label="Azure" scheme="http://blog.ploeh.dk/CategoryView,category,Azure.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p align="left">
My latest MSDN Magazine article, this time about CQRS on Windows Azure, is now <a href="http://msdn.microsoft.com/en-us/magazine/gg983487.aspx">available
at the April MSDN Magazine web site</a>.
</p>
        <p align="left">
It’s mostly meant as an introduction to CQRS as well as containing some tips and tricks
that are specific to applying CQRS on Windows Azure.
</p>
        <p>
As an added bonus the code sample download contains lots of idiomatic unit tests written
with <a href="http://autofixture.codeplex.com/">AutoFixture</a>’s <a href="http://blog.ploeh.dk/2010/10/08/AutoDataTheoriesWithAutoFixture.aspx">xUnit.net
extensions</a>, so if you’d like to see the result of my TDD work with AutoFixture,
there’s a complete code base to look at there.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=e05fda1e-56a3-4aa6-8259-b943978f2843" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Commands are Composable</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/03/22/CommandsAreComposable.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,7cae4639-8453-4a39-9ad8-49269ff28896.aspx</id>
    <published>2011-03-22T14:09:25.9302818+01:00</published>
    <updated>2011-03-22T14:09:25.9302818+01:00</updated>
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
A few months back I wrote a (somewhat theoretical) <a href="http://blog.ploeh.dk/2010/12/03/TowardsBetterAbstractions.aspx">post
on composable interfaces</a>. A major point of that post was that <a href="http://martinfowler.com/bliki/RoleInterface.html">Role
Interfaces</a>  with a single <a href="http://en.wikipedia.org/wiki/Command_pattern">Command</a> method
(i.e. a method that returns no value) is a very versatile category of abstraction.
</p>
        <p>
Some of my readers asked for examples, so in this post I will provide a few. Consider
this interface that fits the above description:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">IMessageConsumer</font>
              </span>&lt;T&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Consume(T
message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This is a very common type of interface you will tend to encounter a lot in distributed,
message-based architectures such as <a href="http://abdullin.com/cqrs/">CQRS</a> or <a href="http://msdn.microsoft.com/en-us/architecture/aa699424">Udi
Dahan’s view of SOA</a>. Some people would call it a <em>message subscriber</em> instead…
</p>
        <p>
In the rest of this post I will examine how we can create compositions out of the
IMessageConsumer&lt;T&gt; interface using (in order of significance) <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>, <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null
Object</a>, <a href="http://en.wikipedia.org/wiki/Composite_pattern">Composite</a>,
and other well-known programming constructs.
</p>
        <p>
          <strong>Decorator</strong>
        </p>
        <p>
Can we create a meaningful Decorator around the IMessageConsumer&lt;T&gt; interface?
Yes, that’s easy – <a href="http://blog.ploeh.dk/2010/04/07/DependencyInjectionIsLooseCoupling.aspx">I’ve
earlier provided various detailed examples of Decorators</a>, so I’m not going to
repeat them here.
</p>
        <blockquote>
          <p>
I’ve yet to come up with an example of an interface that prevents us from applying
a Decorator, so it’s a valid <a href="http://en.wikipedia.org/wiki/Falsifiability">falsifiable</a> claim
that we can always Decorate an interface. However, I have yet to prove that this is
true, so until now we’ll have to call it a <a href="http://en.wikipedia.org/wiki/Conjecture">conjecture</a>.
</p>
        </blockquote>
        <p>
However, since it’s so easy to apply a Decorator to an interface, it’s not a particularly
valuable trait when evaluating the composability of an interface.
</p>
        <p>
          <strong>Null Object</strong>
        </p>
        <p>
It can be difficult to implement the Null Object pattern when the method(s) in question
return a value, but for Commands it’s easy:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">NullMessageConsumer</font>
              </span>&lt;T&gt;
: <span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Consume(T
message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The implementation simply ignores the input and does nothing.
</p>
        <blockquote>
          <p>
Once again my lack of formal CS education prevents me from putting forth a formal
proof, but I strongly suspect that it’s always possibly to apply the Null Object pattern
to a Command (keep in mind that <em>out</em> parameters count as output, so any interface
with one or more of these are not Commands).
</p>
        </blockquote>
        <p>
It’s often valuable to be able to use a Null Object, but the real benefit comes when
we can compose various implementations together.
</p>
        <p>
          <strong>Composite</strong>
        </p>
        <p>
To be truly composable, an interface should make it possible to create various concrete
implementations that each adhere to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> and then compose those together in a complex implementation.
A Composite is a general-purpose implementation of this concept, and it’s easy to
create a Composite out of a Command:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">CompositeMessageConsumer</font>
              </span>&lt;T&gt;
: </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#0000ff">readonly</font></span><span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;&gt; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
consumers;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> CompositeMessageConsumer(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">params</font></span><span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;[]
consumers)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (consumers
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"consumers"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.consumers
= consumers;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#2b91af">IEnumerable</font></span>&lt;<span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;&gt;
Consumers</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">get</font></span> { <span style="color: "><font color="#0000ff">return</font></span><span style="color: "><font color="#0000ff">this</font></span>.consumers;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">   
#region</font>
              </font>
            </span>
            <font style="font-size: 10pt"> IMessageConsumer&lt;T&gt;
Members</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Consume(T
message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">foreach</font></span> (<span style="color: "><font color="#0000ff">var</font></span> consumer <span style="color: "><font color="#0000ff">in</font></span><span style="color: "><font color="#0000ff">this</font></span>.Consumers)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
consumer.Consume(message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font style="font-size: 10pt" color="#0000ff">   
#endregion</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The implementation of the Consume method simply loops over each composed IMessageConsumer&lt;T&gt;
and invokes its Consume method.
</p>
        <p>
I can, for example, implement a sequence of actions that will take place by composing
the individual concrete implementations. First we have a guard that protects against
invalid messages, followed by a consumer that writes the message to a persistent store,
completed by a consumer that raises a Domain Event that the reservation request was
accepted.
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> c
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">CompositeMessageConsumer</font></span>&lt;<span style="color: "><font color="#2b91af">MakeReservationCommand</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
guard, </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
writer, </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
acceptRaiser);</font>
          </pre>
        </div>
        <p>
Consumers following the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov
Substitution Principle</a> will not notice the difference, as all they will see is
an implementation of IMessageConsumer&lt;MakeReservationCommand&gt;.
</p>
        <p>
          <strong>More advanced programming constructs</strong>
        </p>
        <p>
The Composite pattern only describes a single, general way to compose implementations,
but with a Command interface we can do more. As <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain-Driven
Design</a> explains, a successful interface is often characterized by making it possible
to apply well-known arithmetic or logical operators. As an example, in the case of
the IMessageConsumer&lt;T&gt; interface, we can easily mimic the well-known ?! ternary
operator from C#:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">ConditionalMessageConsumer</font>
              </span>&lt;T&gt;
: </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#2b91af">Func</font></span>&lt;T, <span style="color: "><font color="#0000ff">bool</font></span>&gt;
condition;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;
first;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">private</font></span><span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;
second;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> ConditionalMessageConsumer(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">Func</font></span>&lt;T, <span style="color: "><font color="#0000ff">bool</font></span>&gt;
condition, </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;
first, </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#2b91af">IMessageConsumer</font></span>&lt;T&gt;
second)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (condition
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"condition"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (first
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"first"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">if</font></span> (second
== <span style="color: "><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">throw</font></span><span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ArgumentNullException</font></span>(<span style="color: "><font color="#a31515">"second"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.condition
= condition;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.first
= first;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span style="color: "><font color="#0000ff">this</font></span>.second
= second;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span><span style="color: "><font color="#0000ff">void</font></span> Consume(T
message)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
(<span style="color: "><font color="#0000ff">this</font></span>.condition(message)
? <span style="color: "><font color="#0000ff">this</font></span>.first : <span style="color: "><font color="#0000ff">this</font></span>.second)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
.Consume(message);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This is more verbose than the ?! operator because C# doesn’t allow us to define operator
overloads for interfaces, but apart from that, it does exactly the same thing. Notice
particularly that the Consume method uses the ?! operator to select among the two
alternatives, and then subsequently invokes the Consume method on the selected consumer.
</p>
        <p>
We can use the ConditionalMessageConsumer to define branches in the consumption of
messages. As an example, we can encapsulate the previous CompositeMessageConsumer&lt;MakeReservationCommand&gt;
into a conditional branch like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> consumer
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">ConditionalMessageConsumer</font></span>&lt;<span style="color: "><font color="#2b91af">MakeReservationCommand</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
guard.HasCapacity, c, rejectRaiser);</font>
          </pre>
        </div>
        <p>
Notice that I use the method group syntax to supply the condition delegate. If the
HasCapacity method returns true, the previous composite (c) is being invoked, but
if the result is false we instead use a consumer that raises the Domain Event that
the reservation request was rejected.
</p>
        <p>
          <strong>Concluding thoughts</strong>
        </p>
        <p>
Apart from the direct purpose of providing examples of the immensely powerful composition
options a Command interface provides I want to point out a couple of things:
</p>
        <ul>
          <li>
Each of the design pattern implementations (Null Object, Composite – even Conditional)
are generic. This is a strong testament to the power of this particular abstraction. 
</li>
          <li>
The dynamic mocks I’m familiar with (<a href="http://code.google.com/p/moq/">Moq</a>, <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino
Mocks</a>) will by default try to create Null Object implementations for interfaces
without explicit setups. Since it’s trivial to implement a Null Command, they just
emit them by default. If you use an AutoMocking Container with your unit tests, you
can refactor to your heart’s content, adding and removing dependencies as long as
they are Command interfaces, and your testing infrastructure will just take care of
things for you. It’ll just work. 
</li>
          <li>
Did you notice that even with these few building blocks we have implemented a large
part of a sequential workflow engine? We can execute consumers in sequence as well
as branch between different sequences. Obviously, more building blocks are needed
to make a full-blown workflow engine, but not that many. I’ll leave the rest as an
exercise to the reader :)</li>
        </ul>
        <p>
As I <a href="http://blog.ploeh.dk/2010/12/03/TowardsBetterAbstractions.aspx">originally
sketched</a>, a Command interface is the ultimate in composability. To illustrate,
the application from where I took the above examples is a small application with 48
types (classes and interfaces) in the production code base (that is, excluding unit
tests). Of these, 9 are implementations of the IMessageConsumer&lt;T&gt; interface.
If we also count the interface itself, it accounts for more than 20 percent of the
code base. According to the <a href="http://parlezuml.com/blog/?postid=934">Reused
Abstractions Principle (RAP)</a> I consider this a very successful abstraction.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7cae4639-8453-4a39-9ad8-49269ff28896" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Encapsulating AutoFixture Customizations</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,12de0069-5d1f-4500-8aca-c12b8c2eedec.aspx</id>
    <published>2011-03-18T13:51:08.0967113+01:00</published>
    <updated>2011-03-18T13:51:08.0967113+01:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://autofixture.codeplex.com/">AutoFixture</a> is designed around the
80-20 principle. If your code is well-designed I’d expect a default instance of Fixture
to be able to create specimens of your classes without too much trouble. There are
cases where AutoFixture needs extra help:
</p>
        <ul>
          <li>
If a class consumes interfaces a default Fixture will not be able to create it. However,
this is easily fixed through one of the <a href="http://blog.ploeh.dk/2010/08/19/AutoFixtureAsAnAutomockingContainer.aspx">AutoMocking
Customizations</a>. 
</li>
          <li>
If an API has circular references, Fixture might enter an infinite recursion, but
you can easily customize it to cut off one the references. 
</li>
          <li>
Some constructors may only accept arguments that don’t fit with the default specimens
created by Fixture. <a href="http://blog.ploeh.dk/2009/05/01/DealingWithConstrainedInput.aspx">There
are ways to deal with that</a> as well.</li>
        </ul>
        <p>
I could keep on listing examples, but let’s keep it at that. The key assumption underlying
AutoFixture is that these special cases are a relatively small part of the overall
API you want to test – preferably much less than 20 percent.
</p>
        <p>
Still, to address those special cases you’ll need to customize a Fixture instance
in some way, but you also want to keep your test code DRY.
</p>
        <p>
As the popularity of AutoFixture grows, I’m getting more and more glimpses of how
people address this challenge: Some derive from Fixture, others create extension methods
or other static methods, while others again wrap creation of Fixture instances in
Factories or Builders.
</p>
        <p>
There really is no need to do that. AutoFixture has an idiomatic way to encapsulate
Customizations. It’s called… well… a <em>Customization</em>, which is just another
way to say that there’s an ICustomization interface that you can implement. This concept
corresponds closely to the modularization APIs for several well-known DI Containers.
Castle Windsor has <em>Installers</em>, StructureMap has <em>Registries</em> and Autofac
has<em> Modules</em>.
</p>
        <p>
The ICustomization interface is simple and has a very gentle learning curve:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">ICustomization</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">void</font></span> Customize(<span style="color: "><font color="#2b91af">IFixture</font></span> fixture);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Anything you can do with a Fixture instance you can also do with the IFixture instance
passed to the Customize method, so this is the perfect place to encapsulate common
Customizations to AutoFixture. Note that the AutoMocking extensions as well as several
other optional behaviors for AutoFixture are already defined as Customizations.
</p>
        <p>
Using a Customization is also easy:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.Customize(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">DomainCustomization</font></span>());</font>
          </pre>
        </div>
        <p>
You just need to invoke the Customize method on the Fixture. That’s no more difficult
than calling a custom Factory or extension method – particularly if you also use a
Visual Studio Code Snippet.
</p>
        <p>
When I start a new unit testing project, one of the first things I always do is to
create a new ‘default’ customization for that project. It usually doesn’t take long
before I need to tweak it a bit – if nothing else, then for adding the AutoMoqCustomization.
To apply separation of concerns I encapsulate each Customization in its own class
and compose them with a CompositeCustomization:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">DomainCustomization</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">CompositeCustomization</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> DomainCustomization()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
: <span style="color: "><font color="#0000ff">base</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">AutoMoqCustomization</font></span>(),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">FuncCustomization</font></span>())</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Whenever I need to make sweeping changes to my Fixtures I can simply modify DomainCustomization
or one of the Customizations it composes.
</p>
        <p>
In fact, these days I rarely explicitly create new Fixture instances, but rather encapsulate
them in a custom AutoDataAttribute like this:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">class</font>
              </span>
              <span style="color: ">
                <font color="#2b91af">AutoDomainDataAttribute</font>
              </span> : </font>
            <span style="color: ">
              <font style="font-size: 10pt" color="#2b91af">AutoDataAttribute</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">public</font></span> AutoDomainDataAttribute()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
: <span style="color: "><font color="#0000ff">base</font></span>(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">Fixture</font></span>()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">           
.Customize(<span style="color: "><font color="#0000ff">new</font></span><span style="color: "><font color="#2b91af">DomainCustomization</font></span>()))</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This means that I can reuse the DomainCustomization across normal, imperative unit
tests as well as the <a href="http://blog.ploeh.dk/2010/10/08/AutoDataTheoriesWithAutoFixture.aspx">declarative,
xUnit.net-powered data theories I normally prefer</a>:
</p>
        <div style="font-family: ; background: white; color: ">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">[<span style="color: "><font color="#2b91af">Theory</font></span>, <span style="color: "><font color="#2b91af">AutoDomainData</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <span style="color: ">
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span style="color: ">
                <font color="#0000ff">void</font>
              </span> CanReserveReturnsTrueWhenQuantityIsEqualToRemaining(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Capacity</font></span> sut, <span style="color: "><font color="#2b91af">Guid</font></span> id)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#0000ff">var</font></span> result
= sut.CanReserve(sut.Remaining, id);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span style="color: "><font color="#2b91af">Assert</font></span>.True(result);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Using Customizations to encapsulate your own specializations makes it easy to compose
and manage them in an object-oriented fashion.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=12de0069-5d1f-4500-8aca-c12b8c2eedec" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Resolving closed types with MEF</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/03/14/ResolvingClosedTypesWithMEF.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,3421c846-492c-4970-b6f4-1b43c625a4cc.aspx</id>
    <published>2011-03-14T21:49:11.3505537+01:00</published>
    <updated>2011-03-14T21:49:11.3505537+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
A while back I posed the challenge of <a href="http://blog.ploeh.dk/2010/12/24/ChallengeResolveClosedTypesWithMEF.aspx">resolving
closed types with MEF</a>. I received some responses, but I also wanted to provide
an alternative outline for a solution. In case you don’t remember the problem statement,
it revolved around using the <a href="http://mef.codeplex.com/">Managed Extensibility
Framework</a> (MEF) to compose classes in those cases where it’s impossible to annotate
those classes with the MEF attributes. In the given example I want to compose the
Mayonnaise class from EggYolk and OliveOil, but all three classes are sealed and cannot
be recompiled.
</p>
        <p>
As I describe <a href="http://affiliate.manning.com/idevaffiliate.php?id=1150_236">in
my book</a>, a general solution to this type of problem is to create a sort of adapter
the exports the closed type via a read-only attribute, like these EggYolkAdapter and
MayonnaiseAdapter classes (the OliveOilAdapter looks just like the EggYolkAdapter):
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span>
              <font style="font-size: 10pt" color="#2b91af">EggYolkAdapter</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">private</font></span><span><font color="#0000ff">readonly</font></span><span><font color="#2b91af">EggYolk</font></span> eggYolk;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span> EggYolkAdapter()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">this</font></span>.eggYolk
= <span><font color="#0000ff">new</font></span><span><font color="#2b91af">EggYolk</font></span>();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span><font color="#2b91af">Export</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span><span><font color="#0000ff">virtual</font></span><span><font color="#2b91af">EggYolk</font></span> EggYolk</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">get</font></span> { <span><font color="#0000ff">return</font></span><span><font color="#0000ff">this</font></span>.eggYolk;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
          <pre style="margin: 0px">
            <font size="2">
            </font> </pre>
        </div>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">class</font>
              </span>
            </font>
            <span>
              <font style="font-size: 10pt" color="#2b91af">MayonnaiseAdapter</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">private</font></span><span><font color="#0000ff">readonly</font></span><span><font color="#2b91af">Mayonnaise</font></span> mayo;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span><font color="#2b91af">ImportingConstructor</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span> MayonnaiseAdapter(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#2b91af">EggYolk</font></span> yolk, <span><font color="#2b91af">OliveOil</font></span> oil)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">if</font></span> (yolk
== <span><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">throw</font></span><span><font color="#0000ff">new</font></span><span><font color="#2b91af">ArgumentNullException</font></span>(<span><font color="#a31515">"yolk"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">if</font></span> (oil
== <span><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">throw</font></span><span><font color="#0000ff">new</font></span><span><font color="#2b91af">ArgumentNullException</font></span>(<span><font color="#a31515">"oil"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">this</font></span>.mayo
= <span><font color="#0000ff">new</font></span><span><font color="#2b91af">Mayonnaise</font></span>(yolk,
oil);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span><font color="#2b91af">Export</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span><span><font color="#0000ff">virtual</font></span><span><font color="#2b91af">Mayonnaise</font></span> Mayonnaise</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">get</font></span> { <span><font color="#0000ff">return</font></span><span><font color="#0000ff">this</font></span>.mayo;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Doing it like this is always possible, but if you have a lot of types that you need
to compose, it becomes tedious having to define a lot of similar adapters. Fortunately,
we can take it a step further and generalize the idea of a MEF adapter to a small
set of generic classes.
</p>
        <p>
The EggYolkAdapter can be generalized as follows:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">class</font>
              </span>
              <span>
                <font color="#2b91af">MefAdapter</font>
              </span>&lt;T&gt; <span><font color="#0000ff">where</font></span> T
: <span><font color="#0000ff">new</font></span>()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">private</font></span><span><font color="#0000ff">readonly</font></span> T
export;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span> MefAdapter()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">this</font></span>.export
= <span><font color="#0000ff">new</font></span> T();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span><font color="#2b91af">Export</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span><span><font color="#0000ff">virtual</font></span> T
Export</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">get</font></span> { <span><font color="#0000ff">return</font></span><span><font color="#0000ff">this</font></span>.export;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Notice that I’ve more or less just replaced the EggYolk class with a type argument
(T). However, I also had to add the generic new() constraint, which is often quite
restrictive. However, to support a type like Mayonnaise, I can create another, similar
generic MEF adapter like this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">class</font>
              </span>
              <span>
                <font color="#2b91af">MefAdapter</font>
              </span>&lt;T1,
T2, TResult&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">private</font></span><span><font color="#0000ff">readonly</font></span><span><font color="#0000ff">static</font></span><span><font color="#2b91af">Func</font></span>&lt;T1,
T2, TResult&gt; createExport =</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#2b91af">FuncFactory</font></span>.Create&lt;T1,
T2, TResult&gt;();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">private</font></span><span><font color="#0000ff">readonly</font></span> TResult
export;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span><font color="#2b91af">ImportingConstructor</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span> MefAdapter(T1
arg1, T2 arg2)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">this</font></span>.export
= createExport(arg1, arg2);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
[<span><font color="#2b91af">Export</font></span>]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span><span><font color="#0000ff">virtual</font></span> TResult
Export</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">get</font></span> { <span><font color="#0000ff">return</font></span><span><font color="#0000ff">this</font></span>.export;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The major difference from the simple MefAdapter&lt;T&gt; is that we need slightly
more complicated code to invoke the constructor of TResult, which is expected to take
two constructor arguments of types T1 and T2. This work is delegated to a FuncFactory
that builds and compiles the appropriate delegate using an expression tree:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">internal</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">static</font>
              </span>
              <span>
                <font color="#2b91af">Func</font>
              </span>&lt;T1,
T2, TResult&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
Create&lt;T1, T2, TResult&gt;()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">var</font></span> arg1Exp
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#2b91af">Expression</font></span>.Parameter(<span><font color="#0000ff">typeof</font></span>(T1), <span><font color="#a31515">"arg1"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">var</font></span> arg2Exp
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#2b91af">Expression</font></span>.Parameter(<span><font color="#0000ff">typeof</font></span>(T2), <span><font color="#a31515">"arg2"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">var</font></span> ctorInfo
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">typeof</font></span>(TResult).GetConstructor(<span><font color="#0000ff">new</font></span>[]</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">typeof</font></span>(T1),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">typeof</font></span>(T2)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
});</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">var</font></span> ctorExp
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#2b91af">Expression</font></span>.New(ctorInfo,
arg1Exp, arg2Exp);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">return</font></span><span><font color="#2b91af">Expression</font></span>.Lambda&lt;<span><font color="#2b91af">Func</font></span>&lt;T1,
T2, TResult&gt;&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
ctorExp, arg1Exp, arg2Exp).Compile();</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
With a couple of MEF adapters, I can now compose a MEF Catalog <em>almost</em> like
I can with a real DI Container, and resolve the Mayonnaise class:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> catalog
= <span><font color="#0000ff">new</font></span><span><font color="#2b91af">TypeCatalog</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">typeof</font></span>(<span><font color="#2b91af">MefAdapter</font></span>&lt;<span><font color="#2b91af">OliveOil</font></span>&gt;),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">typeof</font></span>(<span><font color="#2b91af">MefAdapter</font></span>&lt;<span><font color="#2b91af">EggYolk</font></span>&gt;),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">typeof</font></span>(<span><font color="#2b91af">MefAdapter</font></span>&lt;<span><font color="#2b91af">EggYolk</font></span>, <span><font color="#2b91af">OliveOil</font></span>, <span><font color="#2b91af">Mayonnaise</font></span>&gt;)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
);</font>
          </pre>
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> container
= <span><font color="#0000ff">new</font></span><span><font color="#2b91af">CompositionContainer</font></span>(catalog);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> mayo
= container.GetExportedValue&lt;<span><font color="#2b91af">Mayonnaise</font></span>&gt;();</font>
          </pre>
        </div>
        <p>
If you want to change the Creation Policy to NonShared, you can derive from the MefAdapter
classes and annotate them with [PartCreationPolicy] attributes.
</p>
        <p>
I’d never voluntarily choose to use MEF like this, but if I was stuck with MEF in
a project and had to use it like a DI Container, I’d do something like this.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3421c846-492c-4970-b6f4-1b43c625a4cc" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Compose object graphs with confidence</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/03/04/ComposeObjectGraphsWithConfidence.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,df05c5b1-86bb-456c-a7b8-93cb78239424.aspx</id>
    <published>2011-03-04T12:15:10.305957+01:00</published>
    <updated>2011-03-04T12:15:10.305957+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
The main principle behind the <a href="http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx">Register
Resolve Release</a> pattern is that loosely coupled object graphs should be composed
as <em>a single action</em> in the entry point of the application (the Composition
Root). For request-based applications (web sites and services), we use a variation
where we compose <em>once</em> per request.
</p>
        <p>
It seems to me that a lot of people are apprehensive when they first hear about this
concept. It may sound reasonable from an architectural point of view, but isn’t it
horribly inefficient? A well-known example of such a concern is <a href="http://jeffreypalermo.com/">Jeffrey
Palermo</a>’s blog post <a href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/">Constructor
over-injection anti-pattern</a>. Is it really a good idea to compose a complete object
graph in one go? What if we don’t need part of the graph, or only need it later? Doesn’t
it adversely affect response times?
</p>
        <p>
Normally it doesn’t, and if it does, there are elegant ways to address the issue.
</p>
        <p>
In the rest of this blog post I will expand on this topic. To keep the discussion
as simple as possible, I’ll restrict my analysis to object trees instead of full graphs.
This is quite a reasonable simplification as we should strive to avoid circular dependencies,
but even in the case of full graphs the arguments and techniques put forward below
hold.
</p>
        <p>
Consider a simple tree composed of classes from three different assemblies:
</p>
        <p>
          <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Tree" border="0" alt="Tree" src="http://blog.ploeh.dk/content/binary/Windows-Live-Writer/Compose-object-graphs-with-confidence_921A/Tree_1.png" width="373" height="131" />
        </p>
        <p>
All the A classes (blue) are defined in the A assembly, B classes (green) in the B
assembly, and the C1 class (red) in the C assembly. In code we create the tree with
Constructor Injection like this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> t
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">new</font></span><span><font color="#2b91af">A1</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">new</font></span><span><font color="#2b91af">A2</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">new</font></span><span><font color="#2b91af">B1</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span><font color="#0000ff">new</font></span><span><font color="#2b91af">B2</font></span>()),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">new</font></span><span><font color="#2b91af">A3</font></span>()),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">new</font></span><span><font color="#2b91af">C1</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">new</font></span><span><font color="#2b91af">B3</font></span>()));</font>
          </pre>
        </div>
        <p>
Given the tree above, we can now address the most common concerns about composing
object trees in one go.
</p>
        <p>
          <strong>Will it be slow?</strong>
        </p>
        <p>
Most likely not. Keep in mind that <a href="http://blog.ploeh.dk/2011/03/03/InjectionConstructorsShouldBeSimple.aspx">Injection
Constructors should be very simple</a>, so not a lot of work is going on during composition.
Obviously just creating new object instances takes a bit of time in itself, but we
create objects instances all the time in .NET code, and it’s often a very fast operation.
</p>
        <p>
Even when using DI Containers, which perform a lot of (necessary) extra work when
creating objects, <a href="http://www.codinginstinct.com/2008/05/ioc-container-benchmark-rerevisted.html">we
can create tens of thousand trees per second</a>. Creation of objects simply isn’t
that big a deal.
</p>
        <p>
          <strong>But still: what about assembly loading?</strong>
        </p>
        <p>
I glossed over an important point in the above argument. While object creation is
fast, it sometimes takes a bit of time to load an assembly. The tree above uses classes
from three different assemblies, so to create the tree all three assemblies must be
loaded.
</p>
        <p>
In many cases that’s a performance hit you’ll have to take because <em>you need those
classes anyway</em>, but sometimes you might be concerned with taking this performance
hit too early. However, I make the claim that in the vast majority of cases, this
concern is irrelevant.
</p>
        <p>
In this particular context there are two different types of applications: Request-based
applications (web) and all the rest (desktop apps, daemons, batch-jobs, etc.).
</p>
        <p>
          <em>Request-based applications</em>
        </p>
        <p>
For request-based applications such as web sites and REST services, an object tree
must be composed for each request. However, all requests are served by the same AppDomain,
so once an assembly is loaded, it sticks around to be available for all subsequent
requests. Thus, the first few requests will suffer a performance penalty from having
to load all assemblies, but after that there will be no performance impact.
</p>
        <p>
In short, in request-based applications, you can compose object trees with confidence.
In only extremely rare cases should you have performance issues from composing the
entire tree in one go.
</p>
        <p>
          <em>Long-running applications</em>
        </p>
        <p>
For long-running applications the entire object tree must be composed at start-up.
For background services such as daemons and batch processes the start-up time probably
doesn’t matter much, but for desktop applications it can be of great importance.
</p>
        <p>
In some cases the application <em>requires</em> the entire tree to be immediately
available, in which case there’s not a lot you can do. Still, once all assemblies
have been loaded, actually creating the tree will be very fast.
</p>
        <p>
In other cases an entire branch of the tree may not be immediately required. As an
example, if the C1 node in the above graph isn’t needed right away, we could improve
start-up time if we could somehow defer creating that branch, because this would also
defer loading of the entire C assembly.
</p>
        <p>
          <strong>Deferred branches</strong>
        </p>
        <p>
Since object creation is fast, the only case where it makes sense to defer loading
of a branch is when creation of that branch causes an assembly to be loaded. If we
can defer creation of such a branch, we can also defer loading of the assembly, thus
improving the time it takes to compose the initial tree.
</p>
        <p>
Imagine that we wish to defer creation of the C1 branch of the above tree. It will
prevent the C assembly from being loaded because that assembly is not used in any
other place in the tree. However, it will not prevent the B assembly from being loaded,
since that assembly is also being used by the A2 node.
</p>
        <p>
Still, in those rare situations where it makes sense to defer creation of a branch,
we can make that cut into a part of the infrastructure of the tree. <a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx">I
originally described this technique</a> as a reaction to the above mentioned post
by Jeffrey Palermo, but here’s a restatement in the current context.
</p>
        <p>
We can defer creating the C1 node by wrapping it in a lazy implementation of the same
interface. The C1 node implements an interface called ISolo&lt;IMarker&gt;, so we
can wrap it in a Virtual Proxy that defers creation of C1 until it’s needed:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">class</font>
              </span>
              <span>
                <font color="#2b91af">LazySoloMarker</font>
              </span> : <span><font color="#2b91af">ISolo</font></span>&lt;<span><font color="#2b91af">IMarker</font></span>&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">private</font></span><span><font color="#0000ff">readonly</font></span><span><font color="#2b91af">Lazy</font></span>&lt;<span><font color="#2b91af">ISolo</font></span>&lt;<span><font color="#2b91af">IMarker</font></span>&gt;&gt;
lazy;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span> LazySoloMarker(<span><font color="#2b91af">Lazy</font></span>&lt;<span><font color="#2b91af">ISolo</font></span>&lt;<span><font color="#2b91af">IMarker</font></span>&gt;&gt;
lazy)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">if</font></span> (lazy
== <span><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">throw</font></span><span><font color="#0000ff">new</font></span><span><font color="#2b91af">ArgumentNullException</font></span>(<span><font color="#a31515">"lazy"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">this</font></span>.lazy
= lazy;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">   
#region</font>
              </font>
            </span>
            <font style="font-size: 10pt"> ISolo&lt;IMarker&gt; Members</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span><span><font color="#2b91af">IMarker</font></span> Item</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">get</font></span> { <span><font color="#0000ff">return</font></span><span><font color="#0000ff">this</font></span>.lazy.Value.Item;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span>
              <font style="font-size: 10pt" color="#0000ff">   
#endregion</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
This Virtual Proxy takes a Lazy&lt;ISolo&lt;IMarker&gt;&gt; as input and defers to
it to implement the members of the interface. This only causes the Value property
to be created when it’s first accessed – which may be long after the LazySoloMarker
instance was created.
</p>
        <p>
The tree can now be composed like this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> t
=</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">new</font></span><span><font color="#2b91af">A1</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">new</font></span><span><font color="#2b91af">A2</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">new</font></span><span><font color="#2b91af">B1</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span><font color="#0000ff">new</font></span><span><font color="#2b91af">B2</font></span>()),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">new</font></span><span><font color="#2b91af">A3</font></span>()),</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">new</font></span><span><font color="#2b91af">LazySoloMarker</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">new</font></span><span><font color="#2b91af">Lazy</font></span>&lt;<span><font color="#2b91af">ISolo</font></span>&lt;<span><font color="#2b91af">IMarker</font></span>&gt;&gt;(()
=&gt; <span><font color="#0000ff">new</font></span><span><font color="#2b91af">C1</font></span>(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">                <span><font color="#0000ff">new</font></span><span><font color="#2b91af">B3</font></span>()))));</font>
          </pre>
        </div>
        <p>
This retains all the original behavior of the original tree, but defers creation of
the C1 node until it’s needed for the first time.
</p>
        <p>
The bottom line is this: you can compose the entire object graph with confidence.
It’s not going to be a performance bottleneck.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=df05c5b1-86bb-456c-a7b8-93cb78239424" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Injection Constructors should be simple</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/03/03/InjectionConstructorsShouldBeSimple.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,f7498461-6e53-4990-aade-d893333c6a14.aspx</id>
    <published>2011-03-03T15:18:54.5405208+01:00</published>
    <updated>2011-03-03T15:18:54.5405208+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
The Constructor Injection design pattern is a extremely useful way to implement loose
coupling. It’s easy to understand and implement, but sometime perhaps a bit misunderstood.
</p>
        <p>
The pattern itself is easily described through an example:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">private</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">readonly</font>
              </span>
              <span>
                <font color="#2b91af">ISpecimenBuilder</font>
              </span> builder;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt"> SpecimenContext(<span><font color="#2b91af">ISpecimenBuilder</font></span> builder)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">if</font></span> (builder
== <span><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">throw</font></span><span><font color="#0000ff">new</font></span><span><font color="#2b91af">ArgumentNullException</font></span>(<span><font color="#a31515">"builder"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">this</font></span>.builder
= builder;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
The SpecimenContext constructor <em>statically declares</em> that it <em>requires</em> an
ISpecimenBuilder instance as an argument. To guarantee that the the builder field
is an invariant of the class, the constructor contains a Guard Clause before it assigns
the builder parameter to the builder field. This pattern can be repeated for each
constructor argument.
</p>
        <p>
It’s important to understand that when using Constructor Injection the constructor
should contain no additional logic.
</p>
        <blockquote>
          <p>
An Injection Constructor should do no more than receiving the dependencies.
</p>
        </blockquote>
        <p>
This is simply a rephrasing of <a href="http://blog.vuscode.com/">Nikola Malovic</a>’s <a href="http://blog.vuscode.com/malovicn/archive/2009/10/16/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection.aspx">4th
law of IoC</a>. There are several reasons for this rule of thumb:
</p>
        <ul>
          <li>
When we compose applications with Constructor Injection we often create substantial
object graphs, and we want to be able to create these graphs as efficiently as possible.
This is Nikola’s original argument. 
</li>
          <li>
In the odd (and not recommended) cases where you have circular dependencies, the injected
dependencies may not yet be fully initialized, so an attempt to invoke their members
at that time may result in an exception. This issue is similar to the <a href="http://blogs.msdn.com/b/brada/archive/2004/08/12/213951.aspx">issue
of invoking virtual members from the constructor</a>. Conceptually, an injected dependency
is equivalent to a virtual member. 
</li>
          <li>
With Constructor Injection, the constructor’s responsibility is to demand and receive
the dependencies. Thus, according to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> (SRP), it should not try to do something else as well.
Some readers might argue that I’m misusing the SRP here, but I think I’m simply applying
the underlying principle in a more granular context.</li>
        </ul>
        <p>
There’s no reason to feel constrained by this rule, as in any case the <a href="http://blog.ploeh.dk/2011/02/28/InterfacesAreAccessModifiers.aspx">constructor
is an implementation detail</a>. In loosely coupled code, the constructor is not part
of the overall application API. When we consider the API at that level, we are still
free to design the API as we’d like.
</p>
        <p>
Please notice that this rule is contextual: it applies to Services that use Constructor
Injection. Entities and Value Objects tend not to use DI, so their constructors are
covered by other rules.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f7498461-6e53-4990-aade-d893333c6a14" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Interfaces are access modifiers</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/02/28/InterfacesAreAccessModifiers.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,7218be6f-54a5-460a-8da4-8c098ce7d4fc.aspx</id>
    <published>2011-02-28T14:19:04.2224684+01:00</published>
    <updated>2011-02-28T14:19:04.2224684+01:00</updated>
    <category term="Dependency Injection" label="Dependency Injection" scheme="http://blog.ploeh.dk/CategoryView,category,DependencyInjection.aspx" />
    <category term="Software Design" label="Software Design" scheme="http://blog.ploeh.dk/CategoryView,category,SoftwareDesign.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p align="left">
.NET developers should by familiar with the <a href="http://msdn.microsoft.com/en-us/library/ms173121.aspx">standard
access modifiers</a> (public, protected, internal, private). However, in loosely coupled
code we can regard interface implementations as a fifth access modifier. This concept
was originally introduced to me by <a href="http://www.udidahan.com/?blog=true">Udi
Dahan</a> the only time I’ve had the pleasure of meeting him. That was many years
ago and while I didn’t grok it back then, I’ve subsequently come to appreciate it
quite a lot.
</p>
        <p align="left">
Although I can’t take credit for the idea, I’ve never seen it described, and it really
deserves to be.
</p>
        <p align="left">
The basic idea is simple:
</p>
        <blockquote>
          <p>
If a consumer respects the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov
Substitution Principle</a> (LSP), the only visible members are those belonging to
the interface. Thus, the interface represents a dimension of visibility.
</p>
        </blockquote>
        <p>
As an example, consider this simple interface from <a href="http://autofixture.codeplex.com/">AutoFixture</a>:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">interface</font>
              </span>
            </font>
            <span>
              <font style="font-size: 10pt" color="#2b91af">ISpecimenContext</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">object</font></span> Resolve(<span><font color="#0000ff">object</font></span> request);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
A well-behaved consumer can only invoke the Resolve method even though an implementation
may have additional public members:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">public</font>
              </font>
            </span>
            <font style="font-size: 10pt">
              <span>
                <font color="#0000ff">class</font>
              </span>
              <span>
                <font color="#2b91af">SpecimenContext</font>
              </span> : </font>
            <span>
              <font style="font-size: 10pt" color="#2b91af">ISpecimenContext</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">private</font></span><span><font color="#0000ff">readonly</font></span><span><font color="#2b91af">ISpecimenBuilder</font></span> builder;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span> SpecimenContext(<span><font color="#2b91af">ISpecimenBuilder</font></span> builder)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">if</font></span> (builder
== <span><font color="#0000ff">null</font></span>)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">            <span><font color="#0000ff">throw</font></span><span><font color="#0000ff">new</font></span><span><font color="#2b91af">ArgumentNullException</font></span>(<span><font color="#a31515">"builder"</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">this</font></span>.builder
= builder;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span><span><font color="#2b91af">ISpecimenBuilder</font></span> Builder</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">get</font></span> { <span><font color="#0000ff">return</font></span><span><font color="#0000ff">this</font></span>.builder;
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">   
#region</font>
              </font>
            </span>
            <font style="font-size: 10pt"> ISpecimenContext Members</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">public</font></span><span><font color="#0000ff">object</font></span> Resolve(<span><font color="#0000ff">object</font></span> request)</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
{</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">        <span><font color="#0000ff">return</font></span><span><font color="#0000ff">this</font></span>.Builder.Create(request, <span><font color="#0000ff">this</font></span>);</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
}</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt"> </font>
          </pre>
          <pre style="margin: 0px">
            <span>
              <font style="font-size: 10pt" color="#0000ff">   
#endregion</font>
            </span>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">}</font>
          </pre>
        </div>
        <p>
Even though the SpecimenContext class defines the Builder property, as well as a public
constructor, any consumer respecting the LSP will only see the Resolve method.
</p>
        <p>
In fact, the Builder property on the SpecimenContext class mostly exists to support
unit testing because I sometimes need to assert that a given instance of SpecimenContext
contains the expected ISpecimenBuilder. This doesn’t break encapsulation since the
Builder is exposed as a read-only property, and it more importantly <em>doesn’t pollute
the API</em>.
</p>
        <p>
To support unit testing (and whichever other clients might be interested in the encapsulated
ISpecimenBuilder) we have a public property that follows all framework design guidelines.
However, it’s essentially an implementation detail, so it’s not visible via the ISpecimenContext
interface.
</p>
        <p>
When writing loosely coupled code, I’ve increasingly begun to see the <em>interfaces
as the real API</em>. Most other (even public) members are pure implementation details.
If the members are public, I still demand that they follow the framework design guidelines,
but I don’t consider them parts of the API. It’s a very important distinction.
</p>
        <blockquote>
          <p>
The interfaces define the bulk of an application’s API. Most other types and members
are implementation details.
</p>
        </blockquote>
        <p>
An important corollary is that <em>constructors are implementation details too</em>,
since they can never by part of any interfaces.
</p>
        <p>
In that sense we can regard interfaces as a fifth access modifier – perhaps even the
most important one.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7218be6f-54a5-460a-8da4-8c098ce7d4fc" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Creating general populated lists with AutoFixture</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/02/08/CreatingGeneralPopulatedListsWithAutoFixture.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,50e30b32-9d57-4309-bbc5-9b0002965d06.aspx</id>
    <published>2011-02-08T15:53:16.1025246+01:00</published>
    <updated>2011-02-08T15:53:16.1025246+01:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
In <a href="http://blog.ploeh.dk/2011/02/07/CreatingSpecificPopulatedListsWithAutoFixture.aspx">my
previous post</a> I described how to customize a Fixture instance to populate lists
with items instead of returning empty lists. While it’s pretty easy to do so, the
drawback is that you have to do it explicitly for every type you want to influence.
In this post I will follow up by describing how to enable some general conventions
that simply populates all collections that the Fixture resolves.
</p>
        <blockquote>
          <p>
This post describes <a href="http://autofixture.codeplex.com/workitem/4199">a feature</a> that
will be available in <a href="http://autofixture.codeplex.com/">AutoFixture</a> 2.1.
It’s not available in AutoFixture 2.0, but is already available in the code repository.
Thus, if you can’t wait for AutoFixture 2.1 you can download the source and built
it.
</p>
        </blockquote>
        <p>
Instead of having to create multiple customizations for IEnumerable&lt;int&gt;, IList&lt;int&gt;,
List&lt;int&gt;, IEnumerable&lt;string&gt;, IList&lt;string&gt;, etc. you can simply
enable these general conventions as easy as this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> fixture
= <span><font color="#0000ff">new</font></span><span><font color="#2b91af">Fixture</font></span>()</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
.Customize(<span><font color="#0000ff">new</font></span><span><font color="#2b91af">MultipleCustomization</font></span>());</font>
          </pre>
        </div>
        <p>
Notice that enabling conventions for populating sequences and lists with ‘many’ items
is an optional customization that you must explicitly add.
</p>
        <blockquote>
          <p>
This feature must be explicitly enabled. There are several reasons for that:
</p>
          <ul>
            <li>
It would be a breaking change if AutoFixture suddenly started to behave like this
by default. 
</li>
            <li>
The MultipleCustomization targets not only concrete types such as List&lt;T&gt; and
Collection&lt;T&gt;, but also interfaces such as IEnumerable&lt;T&gt;, IList&lt;T&gt;
etc. Thus, if you also use <a href="http://blog.ploeh.dk/2010/08/19/AutoFixtureAsAnAutomockingContainer.aspx">AutoFixture
as an Auto-Mocking container</a>, I wanted to provide the ability to define which
customization takes precedence.</li>
          </ul>
        </blockquote>
        <p>
With that simple customization enabled, all requested IEnumerable&lt;T&gt; are now
populated. The following will give us a finite, but populated list of integers:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> integers
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateAnonymous&lt;<span><font color="#2b91af">IEnumerable</font></span>&lt;<span><font color="#0000ff">int</font></span>&gt;&gt;();</font>
          </pre>
        </div>
        <p>
This will give us a populated List&lt;int&gt;:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> list
= fixture.CreateAnonymous&lt;<span><font color="#2b91af">List</font></span>&lt;<span><font color="#0000ff">int</font></span>&gt;&gt;();</font>
          </pre>
        </div>
        <p>
This will give us a populated Collection&lt;int&gt;:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> collection
= </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateAnonymous&lt;<span><font color="#2b91af">Collection</font></span>&lt;<span><font color="#0000ff">int</font></span>&gt;&gt;();</font>
          </pre>
        </div>
        <p>
As implied above, it also handles common list interfaces, so this gives us a populated
IList&lt;T&gt;:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> list
= fixture.CreateAnonymous&lt;<span><font color="#2b91af">IList</font></span>&lt;<span><font color="#0000ff">int</font></span>&gt;&gt;();</font>
          </pre>
        </div>
        <p>
The exact number of ‘many’ is as always <a href="http://blog.ploeh.dk/2009/05/11/AnonymousSequencesWithAutoFixture.aspx">determined
by the Fixture’s RepeatCount</a>.
</p>
        <p>
As this code is still (at the time of publishing) in preview, I would love to get
feedback on this feature.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=50e30b32-9d57-4309-bbc5-9b0002965d06" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Creating specific populated lists with AutoFixture</title>
    <link rel="alternate" type="text/html" href="http://blog.ploeh.dk/2011/02/07/CreatingSpecificPopulatedListsWithAutoFixture.aspx" />
    <id>http://blog.ploeh.dk/PermaLink,guid,902ee5a9-6115-446b-89a7-d78e7f98b689.aspx</id>
    <published>2011-02-07T20:49:26.3157128+01:00</published>
    <updated>2011-02-08T15:54:45.1903855+01:00</updated>
    <category term="AutoFixture" label="AutoFixture" scheme="http://blog.ploeh.dk/CategoryView,category,AutoFixture.aspx" />
    <category term="Unit Testing" label="Unit Testing" scheme="http://blog.ploeh.dk/CategoryView,category,UnitTesting.aspx" />
    <author>
      <name>Mark Seemann</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
How do you get <a href="http://autofixture.codeplex.com/">AutoFixture</a> to create
populated lists or sequences of items? Recently I seem to have been getting this question
a lot, and luckily it’s quite easy to answer.
</p>
        <p>
Let’s first look at the standard AutoFixture behavior and API.
</p>
        <p>
You can ask AutoFixture to create an anonymous List like this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> list
= fixture.CreateAnonymous&lt;<span><font color="#2b91af">List</font></span>&lt;<span><font color="#0000ff">int</font></span>&gt;&gt;();</font>
          </pre>
        </div>
        <p>
Seen from AutoFixture’s point of view, List&lt;int&gt; is just a class like any other.
It has a default constructor, so AutoFixture just uses that and returns an instance.
You get back an instance, no exceptions are thrown, but the list is empty. What if
you’d rather want a populated list?
</p>
        <p>
There are many ways to go about this. A simple, low-level solution is to populate
the list after creation:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.AddManyTo(list);</font>
          </pre>
        </div>
        <p>
However, you may instead prefer getting a populated list right away. This is also
possible, but before we look at how to get there, I’d like to point out a feature
that surprisingly few users notice. You can <a href="http://blog.ploeh.dk/2009/05/11/AnonymousSequencesWithAutoFixture.aspx">create
many anonymous specimens at once</a>:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <span>
              <font color="#0000ff">
                <font style="font-size: 10pt">var</font>
              </font>
            </span>
            <font style="font-size: 10pt"> integers
= fixture.CreateMany&lt;<span><font color="#0000ff">int</font></span>&gt;();</font>
          </pre>
        </div>
        <p>
Armed with this knowledge, as well as the knowledge of <a href="http://blog.ploeh.dk/2010/04/06/MappingTypesWithAutoFixture.aspx">how
to map types</a>, we can now create this customization to map IEnumerable&lt;int&gt;
to CreateMany&lt;int&gt;:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Register(()
=&gt; fixture.CreateMany&lt;<span><font color="#0000ff">int</font></span>&gt;());</font>
          </pre>
        </div>
        <p>
The Register method is really a generic method, but since we have type inference,
we don’t have to write it out. However, since CreateMany&lt;int&gt;() returns IEnumerable&lt;int&gt;,
this is the type we register. Thus, every time we subsequently resolve IEnumerable&lt;int&gt;,
we will get back a populated sequence.
</p>
        <p>
Getting back to the original List&lt;int&gt; example, we can now customize it to a
populated list like this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Register(()
=&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateMany&lt;<span><font color="#0000ff">int</font></span>&gt;().ToList());</font>
          </pre>
        </div>
        <p>
Because the ToList() extension method returns List&lt;T&gt;, this call registers List&lt;int&gt;
so that we will get back a populated list of integers every time the fixture resolves
List&lt;int&gt;.
</p>
        <p>
What about other collection types that don’t have a nice LINQ extension method? Personally,
I never use Collection&lt;T&gt;, but if you wanted, you could customize it like this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Register(()
=&gt;</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">    <span><font color="#0000ff">new</font></span><span><font color="#2b91af">Collection</font></span>&lt;<span><font color="#0000ff">int</font></span>&gt;(</font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">       
fixture.CreateMany&lt;<span><font color="#0000ff">int</font></span>&gt;().ToList()));</font>
          </pre>
        </div>
        <p>
Since Collection&lt;T&gt; has a constructor overload that take IList&lt;T&gt; we can
customize the type to use this specific overload and populate it with ‘many’ items.
</p>
        <p>
Finally, we can combine all this to map from collection interfaces to populated lists.
As an example, we can map from IList&lt;int&gt; to a populated List&lt;int&gt; like
this:
</p>
        <div style="font-family: ; background: white">
          <pre style="margin: 0px">
            <font style="font-size: 10pt">fixture.Register&lt;<span><font color="#2b91af">IList</font></span>&lt;<span><font color="#0000ff">int</font></span>&gt;&gt;(()
=&gt; </font>
          </pre>
          <pre style="margin: 0px">
            <font style="font-size: 10pt">   
fixture.CreateMany&lt;<span><font color="#0000ff">int</font></span>&gt;().ToList());</font>
          </pre>
        </div>
        <p>
When we use the Register method to map types we can no longer rely on type inference.
Instead, we must explicitly register IList&lt;int&gt; against a delegate that creates
a populated List&lt;int&gt;. Because List&lt;int&gt; implements IList&lt;int&gt; this
compiles. Whenever this fixture instance resolves IList&lt;int&gt; it will create
a populated List&lt;int&gt;.
</p>
        <p>
All of this describes what you can do with the strongly typed API available in AutoFixture
2.0. It’s easy and very flexible, but the only important drawback is that it’s not
general. All of the customizations in this post specifically address lists and sequences
of integers, but not lists of any other type. What if you would like to expand this
sort of behavior to any List&lt;T&gt;, IEnumerable&lt;T&gt; etc?
</p>
        <p>
Stay tuned, because in <a href="http://blog.ploeh.dk/2011/02/08/CreatingGeneralPopulatedListsWithAutoFixture.aspx">the
next post I will describe how to do that</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=902ee5a9-6115-446b-89a7-d78e7f98b689" />
      </div>
    </content>
  </entry>
</feed>
