<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Coding Miscellanea</title>
	<atom:link href="http://joger.net/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://joger.net</link>
	<description>Because writing it down yet another time helps learning it...</description>
	<lastBuildDate>Thu, 29 Mar 2012 00:04:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>C++11 Explorations, Episode 00, Prelude</title>
		<link>http://joger.net/?p=192</link>
		<comments>http://joger.net/?p=192#comments</comments>
		<pubDate>Thu, 29 Mar 2012 00:04:10 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://joger.net/?p=192</guid>
		<description><![CDATA[I&#8217;ve been thinking for some time now that I should test drive the new C++11 features a bit more seriously, but I&#8217;ve not really had the spare time to do it or I just haven&#8217;t managed to decide on exactly how I wanted to do it. Now that I&#8217;ve installed Visual Studio 11 Beta, which [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been thinking for some time now that I should test drive the new C++11 features a bit more seriously, but I&#8217;ve not really had the spare time to do it or I just haven&#8217;t managed to decide on exactly how I wanted to do it. Now that I&#8217;ve installed Visual Studio 11 Beta, which already ships with a lot of all the new C++11 features, I decided to just jump in head-first.</p>
<p>So, this is the deal:</p>
<ul>
<li>I&#8217;ll walk my way (slowly) through the new features that interest me the most, using the VS11 implementation of C++11.</li>
<li>I&#8217;ll divide my journey into small-ish pieces that are easy enough to also blog about.</li>
<li>I&#8217;ll take lots of detours into neighboring areas as I create supporting infrastructure to accomplish what I want and need.</li>
<li>I&#8217;ll create &#8220;something real&#8221; without using any off-the-shelf libraries or tools, because I want to be self-sufficient using C++11, good old general C++ and a large portion of what I consider best practices.</li>
</ul>
<p>Provided that VS11 supports these items, this is what I want to look closer at:</p>
<ul>
<li>Rvalue references and move constructors</li>
<li>Type inference: <strong>auto</strong>, <strong>decltype</strong></li>
<li>Range-based for-loop</li>
<li>Lambda functions</li>
<li>Explicit overrides</li>
<li>Null pointer constant</li>
<li>Strongly typed enumerations</li>
<li>Explicitly defaulted and deleted special member functions</li>
<li>Static assertions</li>
<li>Multithreading: <strong>std::thread</strong>, <strong>std::mutex</strong>, <strong>std::recursive_mutex</strong>, <strong>std::condition_variable</strong>, <strong>std::condition_variable_any</strong>, <strong>std::lock_guard</strong>, <strong>std::unique_lock</strong>, <strong>std::async</strong>, <strong>std::packaged_task</strong>, <strong>std::future</strong>, <strong>std::promise</strong></li>
<li>Hash sets: <strong>std::unordered_set</strong>, <strong>std::unordered_multiset</strong>, <strong>std::unordered_map</strong>, <strong>std::unordered_multimap</strong></li>
<li>Smart pointers: <strong>std::unique_ptr​</strong>, <strong>​std::shared_ptr</strong>, <strong>std::weak_ptr</strong>​</li>
<li>Extensible random number facility: 3 generators and a number of distributions</li>
</ul>
<p>Where applicable, I will also look at the features from a performance perspective, what magic the compiler manages to pull off and what differences we&#8217;ll get at an assembly level by choosing to do this instead of that.</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=192</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing a custom C++ iterator type</title>
		<link>http://joger.net/?p=188</link>
		<comments>http://joger.net/?p=188#comments</comments>
		<pubDate>Mon, 27 Jun 2011 23:00:39 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://joger.net/?p=188</guid>
		<description><![CDATA[For my own reference, and possibly others&#8217;, here&#8217;s a cookbook example of a custom C++ iterator type to use when the implementation details of a particular container is unimportant and the normal C++ algorithms should be used on iterator begin and end ranges. class custom_iterator : public std::iterator&#60;std::input_iterator_tag, exposed_type&#62; { public: custom_iterator(something_that_initializes_the_type_exposer&#38; initializer) : exposer_(initializer) [...]]]></description>
			<content:encoded><![CDATA[<p>For my own reference, and possibly others&#8217;, here&#8217;s a cookbook example of a custom C++ iterator type to use when the implementation details of a particular container is unimportant and the normal C++ algorithms should be used on iterator begin and end ranges.</p>
<pre class="prettyprint ">
class custom_iterator : public std::iterator&lt;std::input_iterator_tag, exposed_type&gt;
{
public:

    custom_iterator(something_that_initializes_the_type_exposer&amp; initializer)
        : exposer_(initializer)
    {
    }

    reference operator*()
    {
        return exposer_.ref();
    }

    const reference operator*() const
    {
        return exposer_.ref();
    }

    pointer operator-&gt;()
    {
        return exposer_.ptr();
    }

    const pointer operator-&gt;() const
    {
        return exposer_.ptr();
    }

    custom_iterator&amp; operator++()
    {
        ++it_;

        return *this;
    }

    bool operator==(const custom_iterator&amp; other) const
    {
        return it_ == other.it_;
    }

    bool operator!=(const custom_iterator&amp; other) const
    {
        return !(*this == other);
    }

private:

    something_that_exposes_the_type exposer_;
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=188</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Fourier transform, the FFT and the DFT</title>
		<link>http://joger.net/?p=186</link>
		<comments>http://joger.net/?p=186#comments</comments>
		<pubDate>Tue, 31 May 2011 21:37:00 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Link tips]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://joger.net/?p=186</guid>
		<description><![CDATA[That title sounds like the beginning of a joke; &#8220;&#8230; was out for a stroll in the park. Then &#8230;&#8221; but of course it&#8217;s not. For varius reasons, none of which are interesting to others right now, I recently felt a deep need to refresh my university knowledge on the Fourier transform (decomposition of a [...]]]></description>
			<content:encoded><![CDATA[<p>That title sounds like the beginning of a joke; &#8220;&#8230; was out for a stroll in the park. Then &#8230;&#8221; but of course it&#8217;s not.</p>
<p>For varius reasons, none of which are interesting to others right now, I recently felt a deep need to refresh my university knowledge on the Fourier transform (decomposition of a signal into its constituent frequencies), the DFT (discretization of a Fourier transform) and the FFT (swift computation of the DFT).</p>
<p>I found a, simply stated, fantastic visual set of explanations of what all of this is actually about, for those that doesn&#8217;t settle with numbers alone:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Fourier_transform" target="_blank">Wikipedia on the Fourier transform</a> (the theory behind the visuals below)</li>
<li><a href="http://altdevblogaday.org/2011/05/17/understanding-the-fourier-transform/" target="_blank">Understanding the Fourier transform</a>&nbsp;(loads of good comments follows the blog post)</li>
<li><a href="http://fixplz.blourp.com/blog/=dfts" target="_blank">Animations for DFT</a>&nbsp;(linked from the comments mentioned above)</li>
<li><a href="http://hascanvas.com/fftvisualize2" target="_blank">fftvisualize</a> (linked from the comments mentioned above)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=186</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uncle Bob on TDD and pair programming</title>
		<link>http://joger.net/?p=185</link>
		<comments>http://joger.net/?p=185#comments</comments>
		<pubDate>Tue, 31 May 2011 21:12:05 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Link tips]]></category>
		<category><![CDATA[Pair programming]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[XP]]></category>

		<guid isPermaLink="false">http://joger.net/?p=185</guid>
		<description><![CDATA[An interesting dialog-like write-up from Robert C. &#8220;Uncle Bob&#8221; Martin describing an actual pair programming session solving an actual real-life problem: http://www.objectmentor.com/resources/articles/xpepisode.htm Far, far from most other canned TDD example scenarios out there. Read it!]]></description>
			<content:encoded><![CDATA[<p>An interesting dialog-like write-up from Robert C. &#8220;Uncle Bob&#8221; Martin describing an actual pair programming session solving an actual real-life problem:</p>
<p><a href="http://www.objectmentor.com/resources/articles/xpepisode.htm">http://www.objectmentor.com/resources/articles/xpepisode.htm</a></p>
<p>Far, far from most other canned TDD example scenarios out there. Read it!</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=185</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Knuth line-breaking algorithm on e-books</title>
		<link>http://joger.net/?p=183</link>
		<comments>http://joger.net/?p=183#comments</comments>
		<pubDate>Tue, 31 May 2011 20:48:31 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Link tips]]></category>

		<guid isPermaLink="false">http://joger.net/?p=183</guid>
		<description><![CDATA[Applying the same line-breaking algorithm that Donald Knuth came up with, in his seminal work with the TeX typesetting engine, to e-book reading experiences: http://www.dirigibleflightcraft.com/kindle/ Oh, my&#8230; want it.]]></description>
			<content:encoded><![CDATA[<p>Applying the same line-breaking algorithm that Donald Knuth came up with, in his seminal work with the TeX typesetting engine, to e-book reading experiences:</p>
<p><a href="http://www.dirigibleflightcraft.com/kindle/">http://www.dirigibleflightcraft.com/kindle/</a></p>
<p>Oh, my&#8230; want it.</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=183</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a really simple IOC container: WeeContainer</title>
		<link>http://joger.net/?p=154</link>
		<comments>http://joger.net/?p=154#comments</comments>
		<pubDate>Thu, 19 May 2011 23:00:29 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Patterns and Idioms]]></category>

		<guid isPermaLink="false">http://joger.net/?p=154</guid>
		<description><![CDATA[I&#8217;ve already described why I had to take the plunge into the sea of implementing my own IOC container. It wasn&#8217;t becuase I didn&#8217;t like the available alternatives &#8211; I can assure you that I can never write anything that beats the proven ones already out there. If there wasn&#8217;t for these two things&#8230; First, [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve already described <a href="http://joger.net/?p=106">why I had to take the plunge</a> into the sea of implementing my own IOC container. It wasn&#8217;t becuase I didn&#8217;t like the available alternatives &#8211; I can assure you that I can never write anything that beats the proven ones already out there. If there wasn&#8217;t for these two things&#8230;</p>
<ul>
<li><b>First</b>, since I do most of my professional activities with the .NET Compact Framework on handheld devices, I needed an IOC container that supported my main platform. Only <a href="http://ninject.org/">Ninject</a> did that at the time.</li>
<li><b>Second</b>, the container I choose cannot fail miserably for several of my main usage scenarios. Ninject <a href="http://stackoverflow.com/q/5260191/6345">did that</a>.</li>
</ul>
<p>Therefore I set out to write my own IOC container with no more bells and whistles than I needed while waiting for the Ninject bug to be fixed. I&#8217;m now using my container, the WeeContainer, in production and Ninject still has the bug. So I guess my call was appropriate &#8211; it wasn&#8217;t a case of <a href="http://en.wikipedia.org/wiki/YAGNI">YAGNI</a>.</p>
<p>In this post I&#8217;ll look deeper into the implementation of WeeContainer to show just how little one need to do if the feature set is kept at a minimum. I&#8217;ll attack the codebase outside-in, jumping onto the public interface of WeeContainer and working my way into its not so deep core.</p>
<p>This is the state of WeeContainer:</p>
<pre class="prettyprint ">
public sealed class WeeContainer
{
    private readonly Dictionary&lt;Type, BindingTarget&gt; targets = new Dictionary&lt;Type, BindingTarget&gt;();
    private readonly Lifetime defaultLifetime;
    ...
}
</pre>
<p>We see that the container has a dictionary, mapping a Type to a BindingTarget. There&#8217;s also a default lifetime that will be used for all resolved dependencies unless no other lifetime is explicitly set.</p>
<p>The default lifetime cannot be changed after construction of the container &#8211; I see no practical benefit to allow the default lifetime to be changed halfway through the process of registering dependencies at the application composition root. At least no benefit that can keep the implementation complexity at a minimum while the client code readability is kept at a maximum.</p>
<p>Why is a Type mapped to a BindingTarget in the dictionary then? When a client asks the container to resolve a dependency of type T, the container is checked for an entry with the Type of T as key. The value of the dictionary entry with that key is a BindingTarget instance that defines everything that is needed to get an instance of the sought dependency.</p>
<p>This is how WeeContainer is constructed:</p>
<pre class="prettyprint ">
public sealed class WeeContainer
{
    ...
    public WeeContainer()
        : this(Lifetime.Transient)
    {
    }

    public WeeContainer(Lifetime defaultLifetime)
    {
        Precondition.IsInRange(defaultLifetime, Lifetime.Transient, Lifetime.Singleton, &quot;lifetime&quot;);

        this.defaultLifetime = defaultLifetime;
    }
    ...
}
</pre>
<p>All that is done during construction is setting the default lifetime. Note the use of the utility contract method Precondition.IsInRange to guarantee that the container is in a usable state after construction.</p>
<p>To register a dependency, one uses the first of only two public methods of WeeContainer (obviously except for the constructors):</p>
<pre class="prettyprint ">
public sealed class WeeContainer
{
    ...
    public IBindingTarget Bind&lt;T&gt;()
    {
        return this.targets.Create(typeof(T), () =&gt; new BindingTarget(typeof(T), this.defaultLifetime));
    }
    ...
}
</pre>
<p>The utility DictionaryExtensions.Create&lt;TKey, TValue&gt; method that is used above is a sibling of DictionaryExtensions.GetOrCreate&lt;TKey, TValue&gt;. In WeeContainer.Bind&lt;T&gt; a mapping between the Type of type T to a BindingTarget with the default lifetime is added. This BindingTarget is returned as an IBindingTarget.</p>
<ul>
<li>If the returned IBindingTarget isn&#8217;t further used by the client, then this dependency will resolve its own type, <i>e.g.</i>, calling Bind&lt;Foo&gt;() will resolve an actual Foo instance with the default lifetime.</li>
<li>If the dependency should map an abstract type to a concrete type, then IBindingTarget.To&lt;T&gt;() must be called, <i>e.g.</i>, calling Bind&lt;IFoo&gt;().To&lt;Foo&gt;() will resolve a concrete Foo instance with the default lifetime when an IFoo instance is requested.</li>
<li>If the resolved dependency shouldn&#8217;t have the default lifetime, then IBindingTarget.With&lt;T&gt;() or IBindingSource.With&lt;T&gt;() must be called. The IBindingSource instance is returned when calling IBindingTarget.To&lt;T&gt;().</li>
</ul>
<p>The main purpose of the IBindingTarget and IBindingSource interfaces is to facilitate the WeeContainer fluent interface:</p>
<pre class="prettyprint ">
var container = new WeeContainer();

container.Bind&lt;Foo&gt;();                          // Using default lifetime.
container.Bind&lt;IBar&gt;().To&lt;Bar&gt;();               // Using default lifetime.

container.Bind&lt;Baz&gt;().With(Lifetime.Singleton); // Not using default lifetime.

container.Bind&lt;IFoobar&gt;().With(Lifetime.Singleton).To&lt;Foobar&gt;(); // Same effect as next line. The To/With order doesn't matter.
container.Bind&lt;IBaz&gt;().To&lt;Baz&gt;().With(Lifetime.Singleton);       // Same effect as previous line. The To/With order doesn't matter.
</pre>
<p>To resolve a dependency, one uses the second public method of WeeContainer:</p>
<pre class="prettyprint ">
public sealed class WeeContainer
{
    ...
    public T Resolve&lt;T&gt;()
    {
        return (T)Resolve(typeof(T));
    }
    ...
}
</pre>
<p>This method just delegates the work to the private method Resolve(Type):</p>
<pre class="prettyprint ">
private object Resolve(Type targetType)
{
    var target = default(BindingTarget);
    var targetExists = this.targets.TryGetValue(targetType, out target);
    Precondition.IsTrue(targetExists, &quot;targetExists&quot;);

    return target.Singleton ?? CreateInstance(target);
}
</pre>
<p>This method first checks the contract that the requested type must have been previously registered with the container. Then a quick check to see if the found BindingTarget represents an already created dependency with singleton lifetime. If so, then it&#8217;s immediately returned, otherwise a new instance of the type defined by the BindingTarget is created in CreateInstance:</p>
<pre class="prettyprint ">
private object CreateInstance(BindingTarget target)
{
    var constructors = target.Source.Type.GetConstructors();
    Precondition.IsNotNullOrEmpty(constructors, &quot;constructors&quot;);

    var parameters = constructors[0].GetParameters();
    var instance = parameters.Length &gt; 0 ?
                   constructors[0].Invoke(parameters
                                          .Select(parameter =&gt; Resolve(parameter.ParameterType))
                                          .ToArray()) :
                   Activator.CreateInstance(target.Source.Type);

    if (target.Lifetime == Lifetime.Singleton &amp;&amp; target.Singleton == null)
    {
        target.Singleton = instance;
    }

    return instance;
}
</pre>
<p>This method actually contains most of the intelligence that can be attributed to WeeContainer and the original idea for this isn&#8217;t my own. I&#8217;ve previously mentioned that I started things off with Ken Egozi’s blog post <a href="http://kenegozi.com/blog/2008/01/17/its-my-turn-to-build-an-ioc-container-in-15-minutes-and-33-lines">It’s My Turn To Build An IoC Container In 15 Minutes and 33 Lines</a> and Ayende Rahien’s prequel <a href="http://ayende.com/blog/2886/building-an-ioc-container-in-15-lines-of-code">Building an IoC container in 15 lines of code</a>. What I did was applying my own coding style to it, added basic lifetime management and made it use a fluent interface.</p>
<p>Anyway, in WeeContainer.CreateInstance I begin by using reflection on the source type to check the contract that a registered source type must be constructible, <i>i.e.</i>, it must have at least one public constructor.</p>
<p>Then the first constructor is examined for its parameters, and this is a limitation of WeeContainer: <strong>Only</strong> the first found constructor is examined. This will rule out types with overloaded constructors, but since that&#8217;s something I generally don&#8217;t use, it&#8217;s not a problem for me. As stated before: the container has <strong>what I need</strong>, nothing more.</p>
<ul>
<li>If the constructor has no parameters, then an instance of the type is constructed using System.Activator.CreateInstance.</li>
<li>If the constructor has parameters, then instances of the parameter types are recursively created by calling WeeContainer.Resolve(Type) for all of them.</li>
</ul>
<p>When an instance has been created, it&#8217;ll be attached to a BindingTarget if its lifetime is Lifetime.Singleton so that the return statement in WeeContainer.Resolve(Type)</p>
<pre class="prettyprint ">
return target.Singleton ?? CreateInstance(target);
</pre>
<p>can be shortcut when possible. And this is really all there is to it.</p>
<p>All of the above, including NUnit dependencies, can be fetched from the Mercurial repository at <a href="https://joger.googlecode.com">https://joger.googlecode.com</a> or cloned with <strong>hg clone https://joger.googlecode.com/hg/ joger</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=154</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Podcast recommendation: CodeCast on Technical Debt</title>
		<link>http://joger.net/?p=143</link>
		<comments>http://joger.net/?p=143#comments</comments>
		<pubDate>Thu, 19 May 2011 23:00:02 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Patterns and Idioms]]></category>
		<category><![CDATA[Podcasts]]></category>

		<guid isPermaLink="false">http://joger.net/?p=143</guid>
		<description><![CDATA[If you&#8217;ve set out to listen to one and only one podcast entry this year and haven&#8217;t yet picked one, then this is the one you should choose: CodeCast Episode 105: Technical Debt with Gary Short and Markus Egger So. Spot. On.]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve set out to listen to one and only one podcast entry this year and haven&#8217;t yet picked one, then this is the one you should choose:</p>
<p><a href="http://www.code-magazine.com/CodeCast/Index.aspx?messageid=9ec20768-7e06-4921-945a-5750d31bb107">CodeCast Episode 105: Technical Debt with Gary Short and Markus Egger</a></p>
<p>So. Spot. On.</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=143</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using a fluent interface in the IOC container</title>
		<link>http://joger.net/?p=138</link>
		<comments>http://joger.net/?p=138#comments</comments>
		<pubDate>Wed, 18 May 2011 23:00:32 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Patterns and Idioms]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://joger.net/?p=138</guid>
		<description><![CDATA[In a previous post, Assembling a utility assembly, part 2: IOC Container, I wrote I thought of adding support for a more fluent interface, since &#8220;all the other ones do it&#8221; &#8230; But I decided that I didn’t need it. Well, hmmm&#8230; After that post I was a bit curious how things would actually look, [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous post, <a href="http://joger.net/?p=106">Assembling a utility assembly, part 2: IOC Container</a>, I wrote</p>
<blockquote><p>
I thought of adding support for a more fluent interface, since &#8220;all the other ones do it&#8221; &#8230; But I decided that I didn’t need it.
</p></blockquote>
<p>Well, hmmm&#8230; After that post I was a bit curious how things would actually look, design-wise, if they were fluent-ized. So I changed the design and then I didn&#8217;t want to go back, because I liked the new one better.</p>
<p>The old way of registering types with the IOC container:</p>
<pre class="prettyprint ">
public sealed class WeeContainer
{
    ...
    public void Bind&lt;TTarget&gt;() { ... }
    public void Bind&lt;TTarget&gt;(Lifetime lifetime) { ... }

    public void Bind&lt;TTarget, TSource&gt;() { ... }
    public void Bind&lt;TTarget, TSource&gt;(Lifetime lifetime) { ... }
    ...
}
</pre>
<p>And the new way:</p>
<pre class="prettyprint ">
public sealed class WeeContainer
{
    ...
    public IBindingTarget Bind&lt;T&gt;() { ... }
    ...
}
</pre>
<p>The most obvious difference between the old and new WeeContainer is that its public interface has become much lighter. This has a cost associated with it: The new design has introduced several new types that add complexity to the code base and that requires new tests.</p>
<p>Using the new WeeContainer is probably easier, since there&#8217;s only one public method that registers types with the container. Before, there were four methods to choose from.</p>
<p>If a type should be resolved by itself, meaning that it&#8217;s instantiatable, using the default lifetime, then calling WeeContainer.Bind&lt;T&gt;() is enough. But if it should be resolved by another type or use another lifetime, then the return value from WeeContainer.Bind&lt;T&gt;() needs to be used, namely the IBindingTarget:</p>
<pre class="prettyprint ">
public interface IBindingTarget
{
    IBindingSource To&lt;T&gt;();
    IBindingTarget With(Lifetime lifetime);
}
</pre>
<p>From IBindingTarget we can conclude that a type registered with WeeContainer.Bind&lt;T&gt;() can get a lifetime other than the default if IBindingTarget.With(Lifetime) is called. The type can also be resolved by another type by calling IBindingTarget.To&lt;T&gt;():</p>
<pre class="prettyprint ">
var container = new WeeContainer();
container.Bind&lt;Foo&gt;().With(Lifetime.Singleton);
container.Bind&lt;IBar&gt;().To&lt;Bar&gt;();
</pre>
<p>Since IBindingTarget.With(Lifetime) returns the IBindingTarget instance, we can fluently add a call to IBindingTarget.To&lt;T&gt;():</p>
<pre class="prettyprint ">
container.Bind&lt;IBar&gt;().With(Lifetime.Singleton).To&lt;Bar&gt;();
</pre>
<p>As you can see, IBindingTarget.To&lt;T&gt;() returns an IBindingSource instance:</p>
<pre class="prettyprint ">
public interface IBindingSource
{
    void With(Lifetime lifetime);
}
</pre>
<p>This interface makes it possible to change the order of the above fluent call to</p>
<pre class="prettyprint ">
container.Bind&lt;IBar&gt;().To&lt;Bar&gt;().With(Lifetime.Singleton);
</pre>
<p>which often feels more natural.</p>
<p>I will look at the implementation of this new fluent interface for WeeContainer and its friends in another post.</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=138</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Assembling a utility assembly, part 3: IDictionary extension methods</title>
		<link>http://joger.net/?p=120</link>
		<comments>http://joger.net/?p=120#comments</comments>
		<pubDate>Tue, 17 May 2011 23:00:21 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Patterns and Idioms]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://joger.net/?p=120</guid>
		<description><![CDATA[Something that I find myself repeating too often to be funny is the collection get or create idiom, especially when dealing with dictionaries: public sealed class Frobblarium { private readonly Dictionary&#60;string, Frobble&#62; frobbles; ... public Frobble GetNamedFrobble(string name) { Frobble frobble; if (!this.frobbles.TryGetValue(name, out frobble)) { frobble = new Frobble(); this.frobbles[name] = frobble; } return [...]]]></description>
			<content:encoded><![CDATA[<p>Something that I find myself repeating too often to be funny is the collection <strong>get or create</strong> idiom, especially when dealing with dictionaries:</p>
<pre class="prettyprint ">
public sealed class Frobblarium
{
    private readonly Dictionary&lt;string, Frobble&gt; frobbles;
    ...
    public Frobble GetNamedFrobble(string name)
    {
        Frobble frobble;

        if (!this.frobbles.TryGetValue(name, out frobble))
        {
            frobble = new Frobble();
            this.frobbles[name] = frobble;
        }

        return frobble;
    }
}
</pre>
<p>The codeblock inside GetNamedFrobble just drives me crazy every time I have to write it manually. Therefore I added some extension methods to overcome this hangup. With those, all that&#8217;s left on the manual side of it is this:</p>
<pre class="prettyprint ">
public sealed class Frobblarium
{
    private readonly Dictionary&lt;string, Frobble&gt; frobbles;
    ...
    public Frobble GetNamedFrobble(string name)
    {
        return this.frobbles.GetOrCreate(name);
    }
}
</pre>
<p>So much lighter on both eyes and fingers! The GetOrCreate used above will create the dictionary value by invoking its default constructor. There are two overloaded GetOrCreate extension methods: One that takes a default value to insert into the dictionary if the key doesn&#8217;t exist, instead of creating a new value:</p>
<pre class="prettyprint ">
public sealed class Frobblarium
{
    private readonly Dictionary&lt;string, Frobble&gt; frobbles;
    private static readonly Frobble defaultFrobble;
    ...
    public Frobble GetNamedFrobble(string name)
    {
        return this.frobbles.GetOrCreate(name, defaultFrobble);
    }
}
</pre>
<p>The other takes a Func&lt;T&gt; delegate that is used to create a new value (in some other way than by using the default constructor) if the key doesn&#8217;t exist.</p>
<pre class="prettyprint ">
public sealed class Frobblarium
{
    private readonly Dictionary&lt;string, Frobble&gt; frobbles;
    ...
    public Frobble GetNamedFrobble(string name)
    {
        return this.frobbles.GetOrCreate(name, () =&gt; new Frobble { Name = name });
    }
}
</pre>
<p>Implementation:</p>
<pre class="prettyprint ">
public static class DictionaryExtensions
{
    public static TValue GetOrCreate&lt;TKey, TValue&gt;(this IDictionary&lt;TKey, TValue&gt; dictionary, TKey key)
        where TValue : new()
    {
        TValue value;

        if (!dictionary.TryGetValue(key, out value))
        {
            value = new TValue();
            dictionary[key] = value;
        }

        return value;
    }

    public static TValue GetOrCreate&lt;TKey, TValue&gt;(this IDictionary&lt;TKey, TValue&gt; dictionary, TKey key, TValue missingValue)
    {
        TValue value;

        if (!dictionary.TryGetValue(key, out value))
        {
            value = missingValue;
            dictionary[key] = value;
        }

        return value;
    }

    public static TValue GetOrCreate&lt;TKey, TValue&gt;(this IDictionary&lt;TKey, TValue&gt; dictionary, TKey key, Func&lt;TValue&gt; valueProvider)
    {
        TValue value;

        if (!dictionary.TryGetValue(key, out value))
        {
            value = valueProvider();
            dictionary[key] = value;
        }

        return value;
    }
}
</pre>
<p>A couple of tests for the extension methods:</p>
<pre class="prettyprint ">
[TestFixture]
sealed class DictionaryExtensionsTest
{
    [Test]
    public void getorcreate_existing_key_returns_its_value()
    {
        var sut = new Dictionary&lt;int, object&gt;();
        sut[1] = new object();
        sut[3] = new object();
        sut[5] = new object();
        var beforeCount = sut.Count;

        var actual1 = sut.GetOrCreate(1);
        var actual3 = sut.GetOrCreate(3);
        var actual5 = sut.GetOrCreate(5);
        var afterCount = sut.Count;

        Assert.AreSame(sut[1], actual1);
        Assert.AreSame(sut[3], actual3);
        Assert.AreSame(sut[5], actual5);
        Assert.AreEqual(beforeCount, afterCount);
    }

    [Test]
    public void getorcreate_missing_key_returns_new_value()
    {
        var sut = new Dictionary&lt;int, object&gt;();
        sut[1] = new object();
        sut[3] = new object();
        sut[5] = new object();
        var beforeCount = sut.Count;

        var actual0 = sut.GetOrCreate(0);
        var missingValue = new object();
        var actual2 = sut.GetOrCreate(2, missingValue);
        var providedValue = new object();
        var actual4 = sut.GetOrCreate(4, () =&gt; providedValue);
        var afterCount = sut.Count;

        Assert.AreSame(sut[0], actual0);
        Assert.AreSame(sut[2], actual2);
        Assert.AreSame(sut[2], missingValue);
        Assert.AreSame(sut[4], actual4);
        Assert.AreSame(sut[4], providedValue);

        Assert.AreNotSame(sut[1], actual0);
        Assert.AreNotSame(sut[3], actual0);
        Assert.AreNotSame(sut[5], actual0);

        Assert.AreNotSame(sut[1], actual2);
        Assert.AreNotSame(sut[3], actual2);
        Assert.AreNotSame(sut[5], actual2);

        Assert.AreNotSame(sut[1], actual4);
        Assert.AreNotSame(sut[3], actual4);
        Assert.AreNotSame(sut[5], actual4);

        Assert.AreEqual(beforeCount + 3, afterCount);
    }
}
</pre>
<p>All of the above, including NUnit dependencies, can be fetched from the Mercurial repository at <a href="https://joger.googlecode.com">https://joger.googlecode.com</a> or cloned with <strong>hg clone https://joger.googlecode.com/hg/ joger</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=120</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Assembling a utility assembly, part 2: IOC Container</title>
		<link>http://joger.net/?p=106</link>
		<comments>http://joger.net/?p=106#comments</comments>
		<pubDate>Mon, 16 May 2011 23:00:05 +0000</pubDate>
		<dc:creator>Johann Gerell</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Patterns and Idioms]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://joger.net/?p=106</guid>
		<description><![CDATA[Yes, an IOC container. I know that you shouldn&#8217;t do it. And if you do it, you&#8217;ll get it wrong. But what if there&#8217;s no other option out there than rolling up your sleeves and get your hands dirty? I&#8217;ve mentioned that most of my professional development activities circle around Windows Mobile and Windows CE [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, an IOC container. I know that you shouldn&#8217;t do it. And if you do it, you&#8217;ll get it wrong. But what if there&#8217;s no other option out there than rolling up your sleeves and get your hands dirty?</p>
<p>I&#8217;ve mentioned that most of my professional development activities circle around Windows Mobile and Windows CE devices using the .NET Compact Framework. Some time ago when I wanted to take the plunge and start using a proper, established and tested IOC container from out there instead of my hand-rolled manual IOC, I found that none of them supported the .NET Compact Framework. Except one: <a href="http://ninject.org/" alt="Ninject">Ninject</a>.</p>
<p>As happy as I was to find at least one IOC container that I could finally swap out my manual IOC for, as sad I became when I could not use it all the way: I tracked down a devious failure in my application as being <a href="http://stackoverflow.com/questions/5260191/ninject-fails-to-resolve-interface-type-when-the-concrete-type-derives-from-an-ab">a bug in the way Ninject handles attributes</a>. This was a showstopper. <a href="http://stackoverflow.com/users/448580/remo-gloor">Remo Gloor</a> of the Ninject project commented on my Stack Oveflow question that he added the issue to their backlog. But I couldn&#8217;t wait for the next Ninject version to happen and I didn&#8217;t ever want to go back to the manual IOC I had been doing up until lately &#8211; the code base size just wasn&#8217;t small enough any more.</p>
<p>So, I decided to look into this myself. I decided that I only needed something that could do these basic things:</p>
<ul>
<li>Automatically resolve types bound to themselves. Think <strong>concrete</strong> types.</li>
<li>Automatically resolve types bound to other types. Think <strong>abstract</strong> types vs <strong>concrete</strong> types.</li>
<li>Either create a new instance every time a type is resolved, or resuse one single instance. Think <strong>transient</strong> and <strong>singleton</strong> lifetimes or scopes.</li>
<li>Present a simple interface.</li>
</ul>
<p>What were the minimum required amount of building blocks required to fulfill my basic requirements?</p>
<p>I found Ken Egozi&#8217;s blog post <a href="http://kenegozi.com/blog/2008/01/17/its-my-turn-to-build-an-ioc-container-in-15-minutes-and-33-lines">It&#8217;s My Turn To Build An IoC Container In 15 Minutes and 33 Lines</a> which referenced Ayende Rahien&#8217;s prequel <a href="http://ayende.com/blog/2886/building-an-ioc-container-in-15-lines-of-code">Building an IoC container in 15 lines of code</a>. By judging their writings in those posts, neither of the containers was actually meant to be used. But I <strong>had to</strong> make something that could be used. Enter the WeeContainer.</p>
<p>Functionality-wise, I started with Ken Egozi&#8217;s code and added the basic feature of choosing a <strong>scope</strong> (lifetime) for a <strong>binding</strong> (defines the source type that maps to a target type): <strong>transient</strong> or <strong>singleton</strong>. I had no more lifetime needs than that in the applications I was working on.</p>
<p>Presenting a simple interface was just an issue of choosing proper names and not exposing anything that wasn&#8217;t needed. I settled on the following idea:</p>
<pre class="prettyprint ">
public sealed class WeeContainer
{
    public BindingScope DefaultScope { get; set; }

    public void Bind&lt;TTarget&gt;() { ... }
    public void Bind&lt;TTarget&gt;(BindingScope scope) { ... }

    public void Bind&lt;TTarget, TSource&gt;() { ... }
    public void Bind&lt;TTarget, TSource&gt;(BindingScope scope) { ... }

    public TTarget Resolve&lt;TTarget&gt;() { ... }
}
</pre>
<p>I thought of adding support for a more fluent interface, since &#8220;all the other ones do it&#8221;, to support this:</p>
<pre class="prettyprint ">
Bind&lt;Target&gt;().To&lt;Source&gt;().As(BindingScope.Singleton);
</pre>
<p>But I decided that I didn&#8217;t need it. I just find</p>
<pre class="prettyprint ">
Bind&lt;Target, Source&gt;(BindingScope.Singleton);
</pre>
<p>easier to both read and write.</p>
<p>Based on my current codebase I decided that the default scope should be transient. Setting a different scope at bind time shouldn&#8217;t change the default scope and changing the default scope after a binding has been made shouldn&#8217;t affect that binding&#8217;s scope, only the coming ones&#8217;:</p>
<pre class="prettyprint ">
[Test]
public void default_scope_is_transient_by_default()
{
    var sut = new WeeContainer();
    var expected = BindingScope.Transient;
    var actual = sut.DefaultScope;

    Assert.AreEqual(expected, actual);
}

[Test]
public void default_scope_is_not_changed_when_bind_has_other_scope()
{
    var sut = new WeeContainer();
    var expected = sut.DefaultScope;

    Assert.AreNotEqual(expected, BindingScope.Singleton);

    sut.Bind&lt;List&lt;int&gt;&gt;(BindingScope.Singleton);
    var resolved = sut.Resolve&lt;List&lt;int&gt;&gt;();
    var actual = sut.DefaultScope;

    Assert.AreEqual(expected, actual);
}

[Test]
public void changing_default_scope_does_not_change_previous_binds()
{
    var sut = new WeeContainer();
    Assert.AreEqual(sut.DefaultScope, BindingScope.Transient);
    sut.Bind&lt;IList&lt;int&gt;, List&lt;int&gt;&gt;();
    var resolved1 = sut.Resolve&lt;IList&lt;int&gt;&gt;();
    sut.DefaultScope = BindingScope.Singleton;
    var resolved2 = sut.Resolve&lt;IList&lt;int&gt;&gt;();

    Assert.AreNotSame(resolved1, resolved2);
}

[Test]
public void changing_default_scope_changes_coming_binds()
{
    var sut = new WeeContainer();
    Assert.AreEqual(sut.DefaultScope, BindingScope.Transient);
    sut.DefaultScope = BindingScope.Singleton;
    sut.Bind&lt;IList&lt;int&gt;, List&lt;int&gt;&gt;();
    var resolved1 = sut.Resolve&lt;IList&lt;int&gt;&gt;();
    var resolved2 = sut.Resolve&lt;IList&lt;int&gt;&gt;();

    Assert.AreSame(resolved1, resolved2);
}
</pre>
<p>Furthermore, if I introduce a bug in my code I want the code to fail fast and hard to make it easier to find it and minimize the risk that it makes damage to important data. Therefore early checks must be done to verify that types can actually be instantiated:</p>
<pre class="prettyprint ">
class NoPublicCtor : IDisposable
{
    private NoPublicCtor() { }

    public void Dispose()
    {
    }
}

[Test]
public void binding_to_type_without_public_ctor_throws()
{
    var sut = new WeeContainer();

    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;NoPublicCtor&gt;());
    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;NoPublicCtor&gt;(BindingScope.Singleton));
    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;IDisposable, NoPublicCtor&gt;());
    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;IDisposable, NoPublicCtor&gt;(BindingScope.Singleton));
}

[Test]
public void binding_to_abstract_type_throws()
{
    var sut = new WeeContainer();

    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;IList&gt;());
    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;IEnumerable, IList&gt;());
    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;IList&gt;(BindingScope.Singleton));
    Assert.Throws&lt;AgumentException&gt;(() =&gt; sut.Bind&lt;IEnumerable, IList&gt;(BindingScope.Singleton));
}
</pre>
<p>I think the WeeContainer is good enough while waiting for Ninject to be fixed. I&#8217;ll look at the implementation details of WeeContainer in another post. All of the above with more tests, including NUnit dependencies, can be fetched from the Mercurial repository at <a href="https://joger.googlecode.com">https://joger.googlecode.com</a> or cloned with <b>hg clone https://joger.googlecode.com/hg/ joger</b>.</p>
]]></content:encoded>
			<wfw:commentRss>http://joger.net/?feed=rss2&#038;p=106</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
