<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Making the Complex Simple &#187; Architecture</title>
	<atom:link href="http://simpleprogrammer.com/category/architecture/feed/" rel="self" type="application/rss+xml" />
	<link>http://simpleprogrammer.com</link>
	<description>Software Development from John Sonmez&#039;s Perspective</description>
	<lastBuildDate>Tue, 07 Feb 2012 17:47:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='simpleprogrammer.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Making the Complex Simple &#187; Architecture</title>
		<link>http://simpleprogrammer.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://simpleprogrammer.com/osd.xml" title="Making the Complex Simple" />
	<atom:link rel='hub' href='http://simpleprogrammer.com/?pushpress=hub'/>
		<item>
		<title>No Class is an Island</title>
		<link>http://simpleprogrammer.com/2012/01/05/no-class-is-an-island/</link>
		<comments>http://simpleprogrammer.com/2012/01/05/no-class-is-an-island/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 03:15:41 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1433</guid>
		<description><![CDATA[One of the biggest challenges I’ve found with any framework is to make it self-discoverable.&#160; It is often difficult to build a framework or API in a way that users of that framework can easily know what exists and when to use what. One of the main reasons why it is difficult to write a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1433&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the biggest challenges I’ve found with any framework is to make it self-discoverable.&#160; </p>
<p>It is often difficult to build a framework or API in a way that users of that framework can easily know what exists and when to use what.</p>
<p>One of the main reasons why it is difficult to write a good framework is that many developers tend to create classes that are very loosely connected to other classes in that framework with which they are intended to interact.</p>
<p><a href="http://complextosimple.files.wordpress.com/2012/01/island.jpg"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="104004A.TIF" border="0" alt="104004A.TIF" src="http://complextosimple.files.wordpress.com/2012/01/island_thumb.jpg?w=494&#038;h=389" width="494" height="389" /></a></p>
<h2>Defining the island</h2>
<p>When you create a series of classes, do you explicitly plan for those classes to depend on each other or do you try to design them in a way so that they are independent?</p>
<p>This question brings up the old topic of <a href="http://simpleprogrammer.com/2010/11/04/back-to-basics-cohesion-and-coupling-part-1/">loose coupling and tight cohesion</a>.</p>
<p>I consider a class to be an island if it is loosely coupled, but also loosely cohesive.</p>
<p>A class that is an island is a class that does its own thing with very little dependencies or very weak dependencies.</p>
<p>Imagine for a moment a <em>CurrencyConverter</em> class.</p>
<p>This class is designed to take an amount of one currency and convert it to another currency.</p>
<p>There are several ways we could create the API for this class.</p>
<p>Here is one of them:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:27a2886a-04c3-4dbb-acd7-8374d0eeaca6" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
public class CurrencyConverter
{
    CurrencyConverter(ICurrency destinationCurrency)
    { ... }

    ICurrency Convert(ICurrency sourceCurrency, decimal amount);
    { ... }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Now this seems like a pretty reasonable API, but there is a problem here.&#160; The problem is if you have a class that implements <em>ICurrency</em>, you don’t have any good way to know that this class exists.</p>
<p>If we don’t do anything else, this class might as well not exist at all.&#160; It is an island.</p>
<p>It can see classes it needs to use, but the classes that could benefit from <em>CurrencyConverter</em> don’t know it exists.</p>
<p>The developer that is using an <em>ICurrency</em> implementation has no good way to know that this convert exists.&#160; Most likely a developer will end up writing their own implementation of a currency converter.&#160; </p>
<p>Duplication! Bad!</p>
<h2>The date and time link</h2>
<p>You will often see this in code bases and frameworks.&#160; You will have many different utility folders or classes that help do date and time operations.</p>
<p>The problem is that no one really knows these utility classes exist and so everyone ends up rewriting the functionality all over your code base and you have a mess.</p>
<p>Take a look at your own project, see if you can find all the utility classes that deal with date, time or currency.&#160; Now check to see if those utility classes are being used everywhere they could be.&#160; Chances are they are not.</p>
<h2>Building bridges</h2>
<p>We need to build a bridge to the island so that everyone can enjoy the nice beaches.</p>
<p>No point building your wonderful <em>CurrencyConverter</em> if no one knows it exists, right?</p>
<p>So how do we solve this problem?</p>
<p>It definitely is a tricky problem to solve.</p>
<p>The best way I have found is to tie the dependent class back to its dependency.&#160; </p>
<p><strong>Yes, I am advocating circular dependencies!</strong></p>
<p>Don’t be alarmed, it is not that bad.&#160; All you have to do is make sure that your <em>ICurrency</em> interface has a reference to <em>CurrencyConverter</em> so that someone using <em>ICurrency</em> will know it exists.</p>
<p>Now there are many ways of doing this.&#160; Some involve using a base Currency class, others involve creating different static constructors for Currency classes.</p>
<p>I am going to show you a very simple example, just to make my point.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:edb3e7c2-a5e8-410b-afc4-b7812f320c87" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
public interface ICurrency
{
    ConvertUsing(CurrencyConverter converter);
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>It really is that simple.&#160; You have now built a bridge to the island that was <em>CurrencyConverter</em>.</p>
<p>Now when a developer types ‘.’ on an <em>ICurrency</em> implementation they will see a convert method that uses your converter and they will know it exists!&#160; Joy!</p>
<p>Again, there are many ways you could build this bridge.&#160; My intention is not to debate them here.</p>
<p>The point is… BUILD THE BRIDGE!</p>
<h2>But it is a circular dependency, that is bad</h2>
<p>Really?</p>
<p>It is worse than 5 implementations of currency conversion in your code base?</p>
<p>What we have really done here is build something that is extremely tightly cohesive.&#160; This is not necessarily a bad thing.</p>
<p>What we don’t want to do is to tightly couple the currency conversion to our billing system code.&#160; We don’t want to have some building system class being used by our <em>CurrencyConverter</em>.</p>
<h2>Applying the idea further</h2>
<p>The basic idea here is that every time you create a new class you should think about how someone will know it exists.</p>
<p>If the class is out there on its own and it is likely to be useful in the the future, you must do something to tether it back to its dependencies.</p>
<p>It is helpful to have the attitude that<strong> if a developer can’t discover your class by some other class through intelli-sense, your class might as well not exist.</strong></p>
<p>Every time I create a class, I try to think of two things:</p>
<ol>
<li>How will someone use this class</li>
<li>How will they know this class exists</li>
</ol>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1433/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1433&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2012/01/05/no-class-is-an-island/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2012/01/island_thumb.jpg" medium="image">
			<media:title type="html">104004A.TIF</media:title>
		</media:content>
	</item>
		<item>
		<title>Basic to Basics: Understanding IoC Part 2 (Creation)</title>
		<link>http://simpleprogrammer.com/2010/11/30/basic-to-basics-understanding-ioc-part-2-creation/</link>
		<comments>http://simpleprogrammer.com/2010/11/30/basic-to-basics-understanding-ioc-part-2-creation/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 03:51:53 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/11/30/basic-to-basics-understanding-ioc-part-2-creation/</guid>
		<description><![CDATA[In my last back to basics post we talked about what inversion of control (IoC) is in regards to inverting control of interfaces. We looked at how we can benefit from changing the control of the interface from the service to the client of that service. This time we are going to tackle the more [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1186&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://simpleprogrammer.com/2010/11/23/back-to-basics-understanding-ioc/">my last back to basics post</a> we talked about what inversion of control (IoC) is in regards to inverting control of interfaces.</p>
<p>We looked at how we can benefit from changing the control of the interface from the service to the client of that service.</p>
<p>This time we are going to tackle the more common form of IoC that is quite popular these days, and I’m going to show you why dependency injection is only one way to invert the control of the creation of objects in our code.</p>
<h2>What is creation inversion?</h2>
<p>In a normal everyday code we usually create objects by doing something like:</p>
<p>MyClass myObject = new MyClass();</p>
<p>We usually do this creation of objects inside of the class that is going to use or needs that object.</p>
<p>If we used interface inversion, we would probably end up with a declaration like:</p>
<p>IMyInterface myImplementation = new MyImplementation();</p>
<p>You can see that even though the interface may have been inverted we are still controlling the creation of the object from inside the class that uses the object.</p>
<p>Let’s withhold our judgment of whether this is a bad thing or not until we fully understand the idea of creation inversion and the problem it is trying to solve.</p>
<p><strong>So we can see clearly that the normal control is that objects that are used by a class are created by the class using the object.</strong></p>
<p><strong>If we wanted to invert this control, we would say that objects that are used by a class are created outside of the class using the object.</strong></p>
<p>There, you understand IoC in regards to creation.  If you create the object you are going to use inside your class, you are not inverting control.  If you create the object somewhere else, you are inverting control.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/take_control_pic.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="take_control_pic" src="http://complextosimple.files.wordpress.com/2010/11/take_control_pic_thumb.jpg?w=481&#038;h=481" border="0" alt="take_control_pic" width="481" height="481" /></a></p>
<h2>Before we talk about how, let’s talk about why</h2>
<p>Why would you want to invert control of the creation of your objects?</p>
<p>If you are familiar with design patterns, factory pattern should have just popped into your head when you read that statement.  If you are not familiar with design patterns, let me suggest either reading the original gang of four <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0201633612">Design Patterns book</a>, or the highly recommended <a href="http://www.amazon.com/gp/product/0596007124?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596007124">Head First Design Patterns</a>.</p>
<p>I mention the factory pattern because you might want to implement inversion of control for the same types of reasons why you would want to use the factory pattern.</p>
<p>Shh… I’ll tell you a little secret if you promise not to tell the cool IoC container / DI kids.  <strong>The factory pattern is inversion of control!</strong></p>
<p>Let’s use factory pattern to tell us why we would want to invert control.  The description of factory pattern is:</p>
<blockquote><p>Centralize creation of an object of a specific type choosing one of several implementations.</p></blockquote>
<p>From that description we can deduce that we might want to use the factory pattern or some other form of inversion of control anytime we have an object or interface that has several different implementations and we want to put the logic of choosing which implementation to use in a single location.</p>
<p>Let’s use the classic example of having a skinnable UI.</p>
<p>If we have a UI framework that includes classes like <em>Button</em>, <em>DropDownList</em>, <em>TextBox</em>, etc, and we want to make it so that we can have differently skinned implementations of each UI control, we don’t want to put a bunch of code into all of our screens in our application like:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6877a97d-0b1b-4a2f-a84a-3a0e13621c9a" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp; pad-line-numbers: true;">
Button button;
switch(UserSettings.UserSkinType)
{
   case UserSkinTypes.Normal:
        button = new Button();
        break;
   case UserSkinTypes.Fancy:
        button = new FancyButton();
        break;
   case UserSkinTypes.Gothic:
        button = new VampireButton();
}
</pre></p>
</div>
<p>&nbsp;</p>
<p>If we can somehow move the creation of the right kind of object outside of our classes and put it in one place, then we can eliminate all this duplication.  This prize comes at a price.  The price is control.  For convenience sake we must rip the control of the creation of button from our UI screens and give them to a central authority who doles out buttons at this whim.</p>
<p>We need a mediator that says to our UI screen classes, “You want a button?  I got button for ya, and you don’t need to know what kind, cause it’s none of your business.  All you need to know is it’ll be a button.”</p>
<p>I’ll harp on this more later, but I want to bring up the point here before we move on.  <strong>Why would you use inversion of control when you don’t have a problem of needing to select from more than one implementation of an interface or class?</strong></p>
<h2>How can I gets me some of this IoC goodness?</h2>
<p>So let’s talk about how to implement inversion of control.</p>
<p>I’m not going to cover every conceivable way that you could invert control in regards to creation, but I will focus on a few common ways to do so.</p>
<p><strong>Factory pattern</strong></p>
<p>Let’s start here since we already mentioned it.  In our case above we could easily create a button factory that would be able to hand us the correct kind of button.  We would put all the logic for determining which button to use inside of the factory and let it hand us the correct kind of button.  Our code from the above example would be simplified to:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:47b51fe9-4cfa-4092-9cb0-1be845947e1c" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
Button button = ButtonFactory.CreateButton();
</pre></p>
</div>
<p><strong> </strong></p>
<p><strong>Service locator</strong></p>
<p>A service locator is very much like a factory.  You can even use a service locator to get you the right kind of factory that can make your object.  The difference is a factory creates a specific kind of object and a service locator can create different kinds of objects.</p>
<p>Using a service locator pattern, we might rewrite our example as:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:1bab2f4e-91f2-4a31-98c5-5ba81d32ed51" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
Button button = ServiceLocator.Create(Button.class)
</pre></p>
</div>
<p>&nbsp;</p>
<p>(We could also use generics here and do Create&lt;Button&gt;())</p>
<p><strong>Dependency injection</strong></p>
<p>(Notice I’m not saying IoC container based dependency injection.  I’m talking about dependency injection in general here.  You can use an IoC container to do it, but it is not required.)</p>
<p>This is the one most people are most familiar with.  We can use a special class that maps interfaces to their implementations, and then injects those implementations into our class via one of several ways.</p>
<p>Some of the common ways to inject the implementation into the class are:</p>
<ul>
<li>Constructor injection – pass the dependency into your class via the constructor.</li>
<li>Setter injection – pass the dependency into your class by setting it on your class.</li>
<li>Interface injection – implement an interface that allows another class to call your class to give it the dependencies.</li>
</ul>
<p>Using constructor based dependency injection we could rewrite our example like:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:aafc117e-8fd0-4d8b-bc9a-86cd6ac723c0" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
Button button = GetTheRightDangButton();
OurScreen ourScreen = new OutScreen(button);
</pre></p>
</div>
<p>&nbsp;</p>
<p>Notice in this example, we are showing how to create our class.  We don’t have to do anything special inside our class besides provide a constructor that take our dependency.</p>
<h2>But dependency injection looks silly in this example</h2>
<p>Right you are!</p>
<p>What if we have more than one button we are going to use in our screen?  Seems pretty silly to put a single button in the constructor.</p>
<p>If you already know about IoC and dependency injection, there are two important things you should be taking away from this look back to the basics of creational IoC patterns.</p>
<ol>
<li>IoC doesn’t even require interfaces, it just requires that an object be created outside of the class that uses it.</li>
<li>IoC does not always mean IoC container and dependency injection.  Many times the best solution is to directly instantiate an object or use a factory or service locator.  (Especially when you are using multiple instances of a class.)</li>
</ol>
<p>Before embarking on an IoC journey, it is important to understand what problem you are trying to solve by introducing IoC and to understand the differences between using IoC to invert interfaces, using IoC to invert flow control, and using IoC to invert creation control.</p>
<p>In almost all cases the correct application of creational IoC involves solving one of two possible problems.</p>
<ol>
<li>I have multiple implementations of an interface or class and I need to be able to have the logic to choose which one all in one place.</li>
<li>I have only one implementation of an interface or a class, but I need to completely decouple the interface from the implementation for a really good reason.  (A really good reason is something like: “I am writing the code that will use the implementation of this interface, but another company is going to provide the implementation in another library.)</li>
</ol>
<p><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1186/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1186&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/30/basic-to-basics-understanding-ioc-part-2-creation/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/11/take_control_pic_thumb.jpg" medium="image">
			<media:title type="html">take_control_pic</media:title>
		</media:content>
	</item>
		<item>
		<title>Back to Basics: Understanding IoC</title>
		<link>http://simpleprogrammer.com/2010/11/23/back-to-basics-understanding-ioc/</link>
		<comments>http://simpleprogrammer.com/2010/11/23/back-to-basics-understanding-ioc/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 16:46:34 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/11/23/back-to-basics-understanding-ioc/</guid>
		<description><![CDATA[In my last back to basics post, we talked about dependency inversion and how it is the underlying principle that Inversion of Control or IoC is based upon. We also talked a little about IoC and the three main forms of control that can be inverted; interface, flow, and creation. In this post I want [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1182&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://http://simpleprogrammer.com/2010/11/16/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-2/">my last back to basics post</a>, we talked about dependency inversion and how it is the underlying principle that Inversion of Control or IoC is based upon.</p>
<p>We also talked a little about IoC and the three main forms of control that can be inverted; interface, flow, and creation.</p>
<p>In this post I want to dive a little deeper into IoC as it relates to interfaces and creation, we’ll ignore flow inversion for now, because it is often used in a way that is completely unrelated to the other two.</p>
<p>We’ll focus more on creation since we already covered interface inversion a bit and creation inversion is the “hot thing” right now.</p>
<h2>Interface inversion</h2>
<p>Why would we want to invert interfaces?</p>
<p>We covered much of the reasoning in my post on <a href="http://simpleprogrammer.com/2010/11/13/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-1/">dependency inversion</a>, but there are some important points that specifically relate to interfaces in programming that I would like to address here.</p>
<p>First we must understand what non-inverted interfaces are.</p>
<p>Let’s take an example.  Suppose I have a <em>Kangaroo</em> class that has several methods, among them is <em>Punch. </em>Normally, <em>Kangaroo</em> defines the interface that has to be used if you want to use the <em>Kangaroo</em> class.</p>
<p>By default the constructor for the class and the method signatures all make up an interface that the user of the <em>Kangaroo</em> class must adhere to in order to use the <em>Kangaroo</em> class.  The module that contains the Kangaroo class usually also would include the interfaces if one is defined.  In this case the interface would be something like <em>IKangaroo</em>.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/non-inverted.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="Non-inverted" src="http://complextosimple.files.wordpress.com/2010/11/non-inverted_thumb.png?w=500&#038;h=706" border="0" alt="Non-inverted" width="500" height="706" /></a></p>
<p>Why do I say this is normal and not inverted?  Because it makes sense that a class would define what it does and how to use it, not some other entity.</p>
<p>An inversion would be if some other class or module told <em>Kangaroo </em>what its interface needed to be.  <em>Kangaroo</em> would stop being an independent <strong>definer</strong> of a service it has to offer and instead become a <strong>provider</strong> of a service someone else wants.</p>
<p>From our narrow viewpoint of the <em>Kangaroo</em> class we don’t know what kind of interface to provide, so we have to assume it is something like <em>IKangaroo</em>.  The way we look at the Kangaroo class can completely change though, if we consider the <em>BoxingMatch</em> class.</p>
<p>If we create a <em>BoxingMatch</em> class, we really want that class to define the interface that all boxers must adhere to.  We don’t want to have to have the <em>BoxingMatch</em> class know how to make multiple classes with different interfaces box.  So within the module that the <em>BoxingMatch</em> class is defined, we define an interface called <em>IBoxer</em>.  Within the <em>BoxingMatch</em> class itself we use <em>IBoxer </em>instead of specific classes that we want to use in our boxing match.</p>
<p>Now we have given <em>Kangaroo</em> a suitable interface to implement.  <em>IKangaroo</em> hardly makes sense, but <em>IBoxer</em> gives our Kangaroo a purpose.  Our little <em>Kangaroo</em> class is providing a service.  He can box!</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/inverted.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="Inverted" src="http://complextosimple.files.wordpress.com/2010/11/inverted_thumb.png?w=498&#038;h=367" border="0" alt="Inverted" width="498" height="367" /></a></p>
<p>In this example you can see that we have inverted the control of the interface.  <strong>Instead of letting the provider of the interface define that interface, we have made the user of the interface define it.</strong></p>
<p>The value we gained here is that we have given control to the higher level module and reduced the complexity of its logic by preventing it from having to deal with every different interface defined by classes that can box.</p>
<h2>Up next creation inversion</h2>
<p>I’m going to end this post here, since creation inversion is going to be a longer topic, and I am on vacation right now.</p>
<p>In my next post we’ll cover creation inversion and talk about how it relates to Dependency Injection or DI.</p>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1182/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1182&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/23/back-to-basics-understanding-ioc/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/11/non-inverted_thumb.png" medium="image">
			<media:title type="html">Non-inverted</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/11/inverted_thumb.png" medium="image">
			<media:title type="html">Inverted</media:title>
		</media:content>
	</item>
		<item>
		<title>Book Review: Enterprise Integration Patterns</title>
		<link>http://simpleprogrammer.com/2010/11/19/book-review-enterprise-integration-patterns/</link>
		<comments>http://simpleprogrammer.com/2010/11/19/book-review-enterprise-integration-patterns/#comments</comments>
		<pubDate>Fri, 19 Nov 2010 23:56:39 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Book Review]]></category>
		<category><![CDATA[Infrastructure]]></category>
		<category><![CDATA[Messaging]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/11/19/book-review-enterprise-integration-patterns/</guid>
		<description><![CDATA[So I’ve had Enterprise Integration Patterns sitting on my bookshelf for quite a while now.&#160; I had skimmed it a few times, but never really gave it a read. It’s a hefty book that you could definitely use to cause some major kidney trauma to an unsuspecting DBA if you sneak up on him from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1177&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>So I’ve had <a href="http://www.amazon.com/gp/product/0321200683?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321200683">Enterprise Integration Patterns</a> sitting on my bookshelf for quite a while now.&#160; I had skimmed it a few times, but never really gave it a read.</p>
<p>It’s a hefty book that you could definitely use to cause some major kidney trauma to an unsuspecting DBA if you sneak up on him from behind and jab the pointy end of the book into his unprotected backside.</p>
<p><a href="http://www.amazon.com/gp/product/0321200683?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321200683"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="book_cover" border="0" alt="book_cover" src="http://complextosimple.files.wordpress.com/2010/11/book_cover.gif?w=283&#038;h=370" width="283" height="370" /></a></p>
<p>I finally got around to reading this because it is one of my last remaining analog books.&#160; It is part of my quest to cleanse my life of all possessions that are not digital or are not monitors.</p>
<p>This book is really about messaging.&#160; Don’t let the title fool you.&#160; Definitely consider picking up this book if you want to use a messaging platform like BizTalk, MSMQ, or JMS to integrate several applications together.</p>
<p><strong>The good:</strong></p>
<ul>
<li>This book is extremely detailed about each messaging pattern, when to use it, and how to implement it.&#160; If you are seriously going to consider implementing a messaging solution, you need this book.&#160; Honestly, I have done some messaging without it and now that I have read it, I feel like I really missed the whole point before.</li>
<li>Multi-language / technology.&#160; This book is generalized enough to not push you in a language or technology decision, but has specific examples in Java and C#.</li>
<li>Simple to understand.&#160; I was rushing through this book because I wanted to get through it and I found that I was picking up pretty much every concept being thrown.</li>
<li>Excellent reference.&#160; I can see using this book in the future to go back and solve some sort of problem dealing with messaging.</li>
<li>Broken down into perfect size pieces.&#160; If you read this book, you should have all the tools you need to solve any kind of complex messaging scenario.&#160; By thinking of messaging in terms of the patterns or blocks in this book, very complex problems become much simpler.</li>
</ul>
<p><strong>The bad:</strong></p>
<ul>
<li>It is freaking long.&#160; Seriously.&#160; This is a long book.&#160; It has some diagrams and some code, but it is long.&#160; Get ready for an adventure.</li>
<li>It’s a little dry, probably because it is so long.&#160; Some of the code examples are a bit repetitive, and no one ever wants to see XML soap bindings on pages in a book.</li>
</ul>
<p><strong>What I learned:</strong></p>
<p>I have to say that I really did learn a large amount of information from this book.&#160; I really feel like I got a good understanding of how to apply messaging patterns to various sorts of problems.</p>
<p>I feel like this book gave me a really big toolbox of all the possible tools that I would need to solve any messaging pattern.</p>
<p>I also learned just how easy it is to use MSMQ and JMS and throw messages on a pipe.&#160; It’s really not that bad.</p>
<p>After having used BizTalk a while ago and not really understanding what it was or what it was trying to do besides allow you to change file formats between a bunch of different clients, I feel like this book definitely opened up my eyes to the true value of a solution like that.&#160; If I had a BizTalk project now, I am sure I would be much more effective after reading this book.</p>
<p>Overall, I would definitely recommend that every developer that is working with messaging read this book.&#160; Even if you are not, I would still recommend reading it so that you can have your eyes opened up to how messaging can solve many of the problems we try to solve in create-ftp-batch-cron-jobish ways.</p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.&#160; Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.&#160; Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1177/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1177&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/19/book-review-enterprise-integration-patterns/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/11/book_cover.gif" medium="image">
			<media:title type="html">book_cover</media:title>
		</media:content>
	</item>
		<item>
		<title>Basic to Basics: What is Dependency Inversion? Is it IoC? Part 2</title>
		<link>http://simpleprogrammer.com/2010/11/16/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-2/</link>
		<comments>http://simpleprogrammer.com/2010/11/16/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-2/#comments</comments>
		<pubDate>Tue, 16 Nov 2010 16:00:57 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1173</guid>
		<description><![CDATA[In my previous post on dependency inversion, I talked about what dependency inversion is and gave some examples in the real world. This post is going to focus much more on the details and how it relates to code. Back to your code… Now let’s look at a code example to see how dependency inversion [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1173&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://simpleprogrammer.com/2010/11/13/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-1">previous post on dependency inversion</a>, I talked about what dependency inversion is and gave some examples in the real world.</p>
<p>This post is going to focus much more on the details and how it relates to code.</p>
<h2>Back to your code…</h2>
<p>Now let’s look at a code example to see how dependency inversion helps us out. Let’s say you are creating a high level module for parsing log files and storing some basic information into a database.</p>
<p>In this case you want to be able to handle several different log files from a number of different sources and write some common data they all share to a database.<br />
One approach to this kind of problem is to have your module handle each kind of log file based on what kind of data and format it contains and where it is. Using this approach, in your module you would handle various kinds of log files based on the interface those individual log files present to you. (When I use interface here, I am not talking about the language construct, but the concept of how we interface with something.)</p>
<p>Using this approach, in our module we might have a switch statement or series of if-else statements that lead us to a different code path depending on what kind of log file we are processing. For one log file we might open up a file on disk, and read a line, then split that line based on some delimiter. For another perhaps we open a database connection and read some rows.</p>
<p>The problem is the log files are defining the interface our higher level code has to use. They are in effect “in control” of our code, because they are dictating the behavior our code must conform to.</p>
<p>We can invert this control, and invert the dependencies by specifying an interface that the log files we process must conform to. We don’t even have to use a language level interface.</p>
<p>We could simply create a data class called <em>LogFile</em> that is the input to our module. Anyone who wanted to use our module would first have to convert their files to our format.</p>
<p>We could also create an <em>ILogFileSource</em> interface that classes could implement to contain the logic of parsing log files from different sources. Our module would depend on <em>ILogFileSource</em> and specify what kind of methods and data it needs to parse the log files instead of the other way around.</p>
<p>The key point here is that our high level module should be controlling the interface (non language construct kind) that the lower level modules need to adhere to instead of being at the whim of the interfaces of each lower level module.</p>
<p><strong>One way to think of this is that lower level modules provide a service to higher level modules. The higher level modules specifies the interfaces for that service and the lower level module provides that service.</strong></p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/room-service.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="room-service" src="http://complextosimple.files.wordpress.com/2010/11/room-service_thumb.jpg?w=497&#038;h=315" border="0" alt="room-service" width="497" height="315" /></a></p>
<p>One thing I want to point out in this example is that we knew there would be more than one log file source. If we were writing a log file parsing module that was only ever going to work against one source it might not be worth trying to invert this dependency because we wouldn’t see any benefit from doing so. It isn’t very hard for us to write out code as cleanly as possible working with one source and then refactor it later to invert the dependencies once we have additional sources.</p>
<p><strong>Just because you can invert dependencies doesn’t mean you should.</strong></p>
<p>In this case since we are always writing to a database, I don’t feel any particular need to invert our dependency on writing out the log files. However, there is some real value in encapsulating all of our code that interacts with the database into one place, but that is for another post.</p>
<h2>Notice we haven’t talked about unit testing yet</h2>
<p>&nbsp;</p>
<p>You see the problem of dependency inversion and inversion of control has nothing specifically to do with unit testing.</p>
<p>Simply slapping an interface on top of a class and injecting it into another class may help with unit testing, but it doesn’t necessarily invert control or dependencies.</p>
<p>I want to use the log parsing example to illustrate my point. Let’s say we had created our log parser to have a switch statement to handle each type of log file, and now we want to unit test the code.</p>
<p>There is no reason why we can’t create <em>IDatabaseLogFile</em>, <em>ICSVFileSystemLogFile</em>, <em>IEventLogLogFile</em> and <em>IAnNotReallyDoingIoCLogFile</em>, pass them all into the constructor of our <em>LogFileParser</em> as dependencies and then write our unit tests passing in mocks of each.</p>
<p>That in an extreme example for sure, but the point is slapping an interface onto a class does not an IoC make.</p>
<p>We shouldn’t be trying to implement this principle to make it easier to write unit tests. Difficult to write unit tests should give us hints like:</p>
<ul>
<li>Our class is trying to do too much</li>
<li>Our class has lots of different dependencies</li>
<li>Our class requires a lot of setup to do work</li>
<li>Our class is just like this other class that does the same thing only for a different input</li>
</ul>
<p>All of these kinds of hints tell us that we might want to invert control and invert dependencies to improve the overall design of our class, not because it makes it easier to test. (Although it should also make it easier to test.)</p>
<h2>Ok, ok, so is dependency inversion the same as inversion of control or what?</h2>
<p>&nbsp;</p>
<p>Short answer: yes.</p>
<p>It depends on what you mean by control. There are three basic “controls” that can be inverted.</p>
<ol>
<li>The control of the interface. (How do these two systems, modules, or classes, interact with each other and exchange data?)</li>
<li>The control of the flow. (What controls the flow the program? This control inversion happens when we go from procedural to event driven.)</li>
<li>The control of dependency creation and binding. (This is the kind of inversion of control IoC containers do. This inversion is passing the control of the actual creation of and selection of dependencies to a 3rd party which is neutral to either of the other 2 involved.)</li>
</ol>
<p>Each of these 3 is a specific form of dependency inversion and may even involve multiple kinds of dependencies being inverted.</p>
<p><strong>So when someone says “inversion of control”, you should be thinking “what control is being inverted here?” </strong></p>
<p>Dependency inversion is a principle that we use in architecting software.</p>
<p>Inversion of control is a specific pattern that is applied to do so.</p>
<p>Most people only think of inversion of control as #3 above, inverting the control of dependency creation and bind. This is where IoC containers and dependency injection take root.</p>
<h2>What can we learn from this?</h2>
<p>My goal is that we stop grouping the concepts of inversion of control and dependency inversion automatically with dependency injection.</p>
<p>We have learned that dependency inversion is the core principle that guides many of the other practices that have derived from it.</p>
<p>Whenever we apply a pattern we should be looking for the core principle it is tied to and what problem it is helping us solve.</p>
<p>With this base understanding of dependency inversion and inversion of control, we have the prerequisite knowledge to look at dependency injection and understand better what specific problem it tries to solve. (Which I will cover in another post.)</p>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1173/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1173&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/16/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/11/room-service_thumb.jpg" medium="image">
			<media:title type="html">room-service</media:title>
		</media:content>
	</item>
		<item>
		<title>Basic to Basics: What is Dependency Inversion? Is it IoC? Part 1</title>
		<link>http://simpleprogrammer.com/2010/11/13/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-1/</link>
		<comments>http://simpleprogrammer.com/2010/11/13/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-1/#comments</comments>
		<pubDate>Sun, 14 Nov 2010 03:23:02 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/11/13/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-1/</guid>
		<description><![CDATA[Today we are going to talk about one of the most confusing topics of all and see if we can unravel the mess of Dependency Inversion, Inversion of Control and Dependency Injection. It’s not completely important that we understand the specifics of each of these names, because many people end up using them interchangeably.  It’s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1170&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today we are going to talk about one of the most confusing topics of all and see if we can unravel the mess of Dependency Inversion, Inversion of Control and Dependency Injection.</p>
<p>It’s not completely important that we understand the specifics of each of these names, because many people end up using them interchangeably.  It’s pretty unlikely that we are going to correct all that in this blog post.</p>
<p>What is important is that we understand the concepts and ideas behind each of these topics and understand what architectural problems each one is trying to solve.</p>
<p>Today, we are going to focus on Dependency Inversion and get a little bit into inversion of control.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/inverted-bookshelf.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="Inverted-Bookshelf" src="http://complextosimple.files.wordpress.com/2010/11/inverted-bookshelf_thumb.jpg?w=493&#038;h=330" border="0" alt="Inverted-Bookshelf" width="493" height="330" /></a></p>
<h2>Dependency inversion is the root</h2>
<p>It all started with this simple concept introduced by <a href="http://www.objectmentor.com/omTeam/martin_r.html">Uncle Bob</a> in his article in the C++ Report of May 1996, <a href="http://www.objectmentor.com/resources/articles/dip.pdf">The Dependency Inversion Principle</a>.</p>
<p>If you have the time to read through that article, do yourself a favor and do it.  You don’t need to know much C++ to understand it, and it really sheds a light on the problem Bob was trying to solve.</p>
<p>Bob talks about this principle in his excellent book, &#8220;<em><a href="http://www.amazon.com/gp/product/0131857258?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0131857258">Agile Software Development, Principles, Patterns, and Practices, and Agile Principles, Patterns, and Practices in C#”</a></em></p>
<p>This principle is actually very simply stated:</p>
<ol>
<li><strong>High-level modules should not depend on low-level modules. Both should depend on abstractions.</strong></li>
<li><strong>Abstractions should not depend upon details. Details should depend upon abstractions.</strong></li>
</ol>
<p>I think this concept is easily misunderstood and misapplied, because the reason why we apply this principle is often neglected.</p>
<p>If you are familiar with IoC and Dependency Injection, you can see how both are based from this definition of Dependency Inversion.</p>
<h2>What problem does dependency inversion solve?</h2>
<p>Dependency inversion solves the problem of higher level modules being dependent on and coupled to the interfaces of lower level modules and their details.</p>
<p>Let me give you a real world example of a current problem that could be solved by dependency inversion.</p>
<p>Take a look around your house and count up all the devices that have batteries that must be charged somehow.</p>
<p>Things like:</p>
<ul>
<li>Digital camera</li>
<li>Cell phone</li>
<li>Camcorder (flip cam)</li>
<li>Wireless headphones</li>
<li>Game controllers</li>
</ul>
<p>What do all of these things have in common?  They don’t have a charging interface in common.  Some use micro-usb, some use mini-usb, some use their own funky plug.</p>
<p>So as a result, you can’t just have one thing that charged all your devices.  You have to have a different thing for each device.  Your home’s “charging mobile devices module” is dependent on the device.  If you change your cell phone, you need a new charger.  If you upgrade your camera, you need a new charger.</p>
<p>The dependency is going the wrong way.  Lower-level appliances are defining the interface that your home has to use to charge them.  Your home’s charging capability should define the interface the devices have to use.  The dependency should be inverted.  It would make your life a lot easier.</p>
<p>Let’s look at one more example of a place where I would bet dependency inversion is used.  Now, I don’t know about Walmart’s IT structure, but I would venture to guess that when they receive invoices from all of their many distributors the invoices come in the file format that Walmart specifies and not the other way around.</p>
<p>I would bet that Walmart specifies the schema for all of the data it receives from its many business partners.  Let’s assume they do.  In this case they have inverted the dependency, actually they have inverted the control.  Instead of their vendors controlling their interface, Walmart controls the vendors through their interface.</p>
<p>What this means is that every time the vendor changes their internal system they have to still conform to Walmarts interface instead of Walmart having to make changes to accommodate each vendors changes to their format.</p>
<h2>To be continued</h2>
<p>In my <a href="http://simpleprogrammer.com/2010/11/16/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-2/">http://simpleprogrammer.com/2010/11/16/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-2/<a href="http://simpleprogrammer.com/2010/11/16/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-2/">#mce_temp_url#</a></a> I am going to actually give a code example of dependency inversion, address unit tests and finally answer the question of whether dependency inversion is the same thing as inversion of control.</p>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1170/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1170&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/13/basic-to-basics-what-is-dependency-inversion-is-it-ioc-part-1/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/11/inverted-bookshelf_thumb.jpg" medium="image">
			<media:title type="html">Inverted-Bookshelf</media:title>
		</media:content>
	</item>
		<item>
		<title>Back to Basics: Cohesion and Coupling Part 2</title>
		<link>http://simpleprogrammer.com/2010/11/09/back-to-basics-cohesion-and-coupling-part-2/</link>
		<comments>http://simpleprogrammer.com/2010/11/09/back-to-basics-cohesion-and-coupling-part-2/#comments</comments>
		<pubDate>Tue, 09 Nov 2010 16:00:47 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1165</guid>
		<description><![CDATA[This post is a continuation of my post on cohesion and coupling, it is part of a series of back to basics posts examining and questioning some of the core principles and practices of software development. In my last post I talked about what cohesion and coupling are and I talked about some of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1165&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post is a continuation of my post <a href="http://simpleprogrammer.com/2010/11/04/back-to-basics-cohesion-and-coupling-part-1/">on cohesion and coupling</a>, it is part of a series of <a href="http://simpleprogrammer.com/2010/10/30/getting-back-to-basics-introduction-and-why/">back to basics</a> posts examining and questioning some of the core principles and practices of software development.</p>
<p>In my last post I talked about what cohesion and coupling are and I talked about some of the benefits of each.</p>
<p>Now I want to take a look at the actual application of cohesion and decoupling on software systems.</p>
<h2>Granularity affects cohesion and coupling</h2>
<p>Here is the key misunderstanding with cohesion and decoupling.</p>
<p><strong>Cohesion and decoupling are completely relative to the granularity of what is a module.</strong></p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/marbles.jpg"><img style="display:inline;" title="MARBLES" src="http://complextosimple.files.wordpress.com/2010/11/marbles_thumb.jpg?w=480&#038;h=340" alt="MARBLES" width="480" height="340" /></a></p>
<p>From here on out, I won’t say class or software or system, I am going to say module when referring to cohesion and coupling.</p>
<p>See, the problem is that we need to be able to define what a module is in order to determine if something is loosely coupled or highly cohesive.</p>
<p>Let me give you an example.  Let’s take that linked list class we talked about above.  If we define a module to be any class in our code, then it is pretty decoupled.  But, if we define a module to be any class or primitive type in the system, suddenly our linked list implementation is going to be dependent on many other things.  Now all the variables we declare in our class are dependencies on things like the Array and the String class or integer implementations.</p>
<p>When we zoom deep down into the above level of what a module is we end up with many more dependencies which represent tighter coupling.</p>
<p>What about cohesion?  Consider if you will, <a href="http://wolfbyte-net.blogspot.com/2007/09/if-something-is-worth-doing.html">Enterprise FizzBuzz</a>.  This is an implementation of the FizzBuzz problem:</p>
<ul>
<li>Print the numbers from 1 to 100</li>
<li>If the number is divisible by 3 print &#8220;Fizz&#8221; instead</li>
<li>If the number is divisible by 5 print &#8220;Buzz&#8221; instead</li>
<li>If the number is divisible 3 and 5 print &#8220;FizzBuzz&#8221; instead</li>
</ul>
<p>It is an implementation of this simple problem using 3 assemblies and 16+ classes.  If we consider a module to be a class, it is not very cohesive at all, since the responsibilities of what should be in a single method or two are spread out across 16.  If we consider a module to be an assembly, it still isn’t very cohesive.</p>
<p>We have to zoom all the way out to the module is a program level before this software becomes cohesive, but at that level it is very coupled to all the the various other frameworks that it depends on.</p>
<p>There are two important takeaways from this section:</p>
<ol>
<li>How we define a module when looking at software affects cohesion and coupling.</li>
<li>The granularity we use to build the software affects cohesion and coupling.  (This one was hidden in the enterprise FizzBuzz example.  In this case the author of the code defined a responsibility to be something very very small.)</li>
</ol>
<p>To summarize, we can look at code from different levels of zooming in and out and determine its coupling and cohesiveness.  We can also build software as different size “Lego blocks” which has the same effect.</p>
<h2>When cohesion and coupling are inversely related</h2>
<p>With that background, we can finally answer the question of whether or not it is possible to achieve high cohesion and loose coupling.</p>
<p>The answer is “to a degree.”</p>
<p>If we try to push too far into the loose coupling zone, we will find that we end up making our definition of a responsibility very very small at which point we lose the quality of cohesion.</p>
<p>I’m going to pick on <a href="http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/">overuse of interfaces</a> again to give you an example.</p>
<p>Consider what happens when we create an interface to “reduce coupling” so that we can create unit tests.  We end up decreasing cohesion because the class our class was referencing (one jump), now is an interface which is implemented by a class (two jumps.)</p>
<p>Now consider what happens when we add a dependency injection module or even just a factory to get the implementation.  Our once simple and highly cohesive implementation is spread out across an interface which is implemented by a class that we have to look up in a factory which contains some sort of a mapping file to map the interface to the implementation. (3-4 jumps.)</p>
<p>I know this concept seems very strange, but let me see if I can explain it with a real world example.</p>
<p>Consider again the highly cohesive baseball.  It’s already at the optimum coupling of 0.  It doesn’t depend on anything else.  But, if we wanted to we could try to decouple it.  How?  We have to zoom in to a point where we could consider that the outer stitching is coupled to the casing which is coupled to the inner ball.</p>
<p>We could decouple that baseball by taking it apart and design some kind of interface which allows for different kinds of binding mechanisms for the outer shell and some kind of substrate to prevent the outer shell from directly touching the inner ball.</p>
<p>If we did that we’d have pieces of the ball lying all over the place and it wouldn’t be very cohesive or even functional.</p>
<p>We can do that exact thing with software.  There is a point where we have achieved the maximum qualities of loose coupling and high cohesion, and we can try to push decoupling at the cost of cohesion.</p>
<h2>Cohesion is more important</h2>
<p>It probably appears that I am saying that cohesion is more important than decoupling, and actually I am.</p>
<p>Why?</p>
<p>If you remember the advantages of tight cohesion and loose coupling, you might have realized that most of the advantages are the same except tight cohesion gives us the benefit of increased understanding.</p>
<p>I tend to value understanding and simplicity in software above most other things, because they aid the most in maintenance and debugging.</p>
<p>It is very important that we consider cohesion when we seek to increase decoupling.  It also can help give us a very clear measure of when we have maximized decoupling.  <strong>At the point where any more decoupling will harm cohesion, we are done.</strong></p>
<h2>So is dependency injection bad?</h2>
<p>No, not at all.  Dependency injection and other methods of decoupling have their places, but it is very important that we don’t just blindly use them for every class in every situation.</p>
<p>We have to be conscious of what we are losing in cohesion and understandability when we consider using any kind of framework or pattern to decouple our software.</p>
<p>I’ll pick on one more thing here, since I think it is not very obvious.  Consider how good a message bus can be for integrating different applications together.  Messaging systems can decouple the different applications that need to communicate with each other making them highly cohesive and very loosely coupled.</p>
<p>Now, consider how bad a message bus can be inside of an application.  I know it is a fairly popular solution for decoupling events, commands, and other communication within an application, but many times the cost of the decoupling is a very high hit to cohesion and understandability.</p>
<p>Don’t get me wrong, sometimes an internal message bus is a good solution for an application, but in many cases it is going to hurt you more than help you.</p>
<h2>It’s all about right sized Lego blocks</h2>
<p><a href="http://www.hanselman.com/blog/">Scott Hanselman</a> often likes to talk about “right sized Lego blocks”, and I agree with him 100%.  Figuring out how to appropriately decouple your application while maintaining cohesion is all about figuring out what the ideal size of a module is.</p>
<p>Sometimes the answer might even be to split your application into multiple applications.</p>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1165/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1165&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/09/back-to-basics-cohesion-and-coupling-part-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/11/marbles_thumb.jpg" medium="image">
			<media:title type="html">MARBLES</media:title>
		</media:content>
	</item>
		<item>
		<title>A Simple Wrapper To Make Things More Fluent</title>
		<link>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/</link>
		<comments>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 15:52:35 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/</guid>
		<description><![CDATA[This post is really a continuation from my last post on using a method that takes an Action to address cross cutting concerns, like logging, without having to go to a full blown AOP implementation. Someone mentioned in the comments that it wasn’t very clear exactly what was going on with the final code.&#160; I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1135&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post is really a continuation from my <a href="http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/">last post</a> on using a method that takes an <em>Action</em> to address cross cutting concerns, like logging, without having to go to a full blown AOP implementation.</p>
<p>Someone mentioned in the comments that it wasn’t very clear exactly what was going on with the final code.&#160; I tend to agree that this:</p>
<p><strong>LogOnError(_riceCooker.Cook);</strong></p>
<p>… is not very clear.</p>
<p>Really, there are two problems with this code that I can see.</p>
<ol>
<li>It is not clear what this is going to do or whether or not <em>LogOnError</em> or <em>Cook</em> is the method we are concerned about.</li>
<li>It’s not very self-discoverable at all.&#160; If we had a library of useful wrapper methods like these, we wouldn’t have a good intellisense way to know what they are.</li>
</ol>
<p>I can solve both of those issues, but doing so starts to move us into a weird zone where I am not quite sure I feel comfortable.&#160; But, nevertheless, in the name of science…</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/10/wrapped.jpg"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="wrapped" border="0" alt="wrapped" src="http://complextosimple.files.wordpress.com/2010/10/wrapped_thumb.jpg?w=478&#038;h=327" width="478" height="327" /></a></p>
<h2>Let’s start backwards</h2>
<p>Liking fluent interfaces, here is the kind of syntax that I would prefer to be able to use:</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).With.LogOnError();</strong></p>
<p>It is a little bit longer syntax, but I like it for a few reasons:</p>
<ol>
<li>It clearly indicates what is going on here.&#160; We are wrapping a method call using a wrapper.&#160; We are wrapping with a method called <em>LogOnError</em>.</li>
<li>You get intellisense all the way.&#160; The correct implementation of this, should let me Type <em>With</em> + ‘.’ and then see a list of all the possible wrapping methods I have implemented.&#160; This makes the wrapping set of methods self-discoverable.</li>
</ol>
<p>I really like the idea of being able to easily change the functionality of the wrapping just by changing the last part of the line.&#160; For example, if we had implemented a wrapping method that was <em>LogAndAbortOnError(),</em> we could change our code to use that pretty easily.</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).With.LogAndAbortOnError();</strong></p>
<p>If we implement this correctly, intellisense will give us our options.</p>
<h2>Making it so</h2>
<p>Creating a fluent syntax in C# can often involve quite a bit of magic and voodoo.&#160; I always like to gather my reagents before embarking on such a journey.</p>
<p>So grab a live chicken, a stapler, and a sharp knife and let’s go!</p>
<p>First step, let’s simplify this.&#160; The <em>With</em> is nice, but it is just for flow, we don’t really need it.&#160; So let’s figure out how to implement our syntax without the <em>With</em> and add it in afterwards.</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).LogOnError();</strong></p>
<p>First the easy way.</p>
<ol>
<li>Create a static <em>Wrapper</em> class with a <em>Wrap</em> method that takes an <em>Action</em> and returns an <em>Action</em>.&#160; (We’ll use this to convert whatever we pass in to an <em>Action</em>, so that we can use a Lambda expression or any method call there.)</li>
<li>Create a static extension method that operates on an <em>Action</em>.&#160; Call it <em>LogOnError</em>.</li>
</ol>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:c1efd5ff-3981-41d4-ac9f-e6cba38cbda6" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true;">
public static class Wrapper
{
    public static Action Wrap(Action action)
    {
        return action;
    }
        
    public static void LogOnError(this Action action)
    {
        try
        {
            action();
        }
        catch (Exception exception)
        {
            // Log the exception here
        }
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Not too bad.&#160; Not a large amount of magic going on here.&#160; Just using an extension method.</p>
<p>But, we already have a problem.&#160; Using a plain old <em>Action</em> is going to give us too many choices in the intellisense drop down.&#160; It could make it hard to know what our real options are and when we try and add the <em>With</em> syntax later, we will need to use a property off of an object we return from the <em>Wrap</em> method.</p>
<h2></h2>
<h2></h2>
<h2></h2>
<h2>Making it better</h2>
<p>We can fix this by actually wrapping the <em>Action</em> with a custom type that we can add our methods to.</p>
<p>Instead of <em>Wrap</em> returning an <em>Action</em>, it will return a <em>WrappedAction</em>.</p>
<p><div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:bb8046ee-1e26-44d7-88bd-a474ed8d1273" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public static class Wrapper
{
    public static WrappedAction Wrap(Action action)
    {
        return new WrappedAction() {Action = action};
    }
        
    public static void LogOnError(this WrappedAction wrappedAction)
    {
        try
        {
            wrappedAction.Action();
        }
        catch (Exception exception)
        {
            // Log the exception here
        }
    }

    public class WrappedAction
    {
        public Action Action { get; set; }
    }
}
</pre>
</pre>
</div>
<p>Looking better.&#160; Now when we put a ‘.’ at the end of our <em>Wrap</em> call we only see <em>LogOnError</em> as an option.</p>
<p>We can be sure now that if we create an extension method for a <em>WrappedAction</em>, we will make sure that method is self-discoverable.&#160; Before, the generic <em>Action</em> extension&#160; method could make our method show up places that we don’t want it to and can get lost in the other methods on <em>Action</em>.</p>
<h2></h2>
<h2>Making it done</h2>
<p>The last thing we need to do is add the <em>With</em>.</p>
<p>Ideally, when we hit the ‘.’ on the end of the <em>Wrap</em> method, we want to see <em>With</em> as an option.&#160; When we hit the ‘.’ on the end of the <em>With</em> property, we want to see <em>LogOnError</em> as an option.</p>
<p>In order to accomplish this we need to:</p>
<ol>
<li>Add a <em>With</em> property to the <em>WrappedAction</em>.</li>
<li>Have the <em>With</em> property be of a new type (<em>WrappedActionTarget</em>) so that we can add our extension methods for that new type.</li>
<li>Change the extension method to operate on the new type.</li>
</ol>
<p>Here is what we end up with:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2c3a8ddf-389d-40bb-bc75-56c4aeb0ed07" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public static class Wrapper
{
    public static WrappedAction Wrap(Action action)
    {
        return new WrappedAction() { Action = action };
    }

    public static void LogOnError(this WrapperMethodTarget target)
    {
        try
        {
            target.WrappedAction.Action();
        }
        catch (Exception)
        {
            Console.Write(&quot;Logging this error&quot;);
        }
    }
}

public class WrapperMethodTarget
{
    public WrappedAction WrappedAction { get; set; }
}

public class WrappedAction
{
    public Action Action { get; set; }

    public WrapperMethodTarget With
    {
        get
        {
            return new WrapperMethodTarget() { WrappedAction = this };
        }
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Now we can use the syntax of:</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).With.LogOnError();</strong></p>
<p>We can move that <em>LogOnError</em> method out to another class, or create new extension methods somewhere else.&#160; I just put it in there to avoid creating another class.</p>
<h2>Is this really practical?</h2>
<p>I don’t know.&#160; To be honest, I was playing around with creating extension methods that work on Actions and I came up with this way to use them.</p>
<p>I could see making a wrapping library that had different kinds of ways you would wrap method calls built into it.&#160; It could allow you to specify how you log in a configuration and then you would get all of this common stuff automatically.</p>
<p>Even if it is not practical, it’s pretty fun, and it demonstrates the power of <em>Action</em>, or rather functional programming in general.</p>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.&#160; Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.&#160; Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1135&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/10/wrapped_thumb.jpg" medium="image">
			<media:title type="html">wrapped</media:title>
		</media:content>
	</item>
		<item>
		<title>Aspect Oriented Programming with Action&lt;&gt;</title>
		<link>http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/</link>
		<comments>http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/#comments</comments>
		<pubDate>Sat, 09 Oct 2010 19:42:06 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Language]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/10/09/aspect-oriented-programming-with-action/</guid>
		<description><![CDATA[Aspect Oriented Programming (AOP) is a pretty great concept. It is a little difficult to implement though. To be honest, I don’t think I’ve ever really seen it successfully implemented.  I mean sure, I’ve seen examples of how you could use it for “cross-cutting” concerns like logging. The problem is it is usually pretty difficult [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1131&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented Programming</a> (AOP) is a pretty great concept.</p>
<p>It is a little difficult to implement though.</p>
<p>To be honest, I don’t think I’ve ever really seen it successfully implemented.  I mean sure, I’ve seen examples of how you could use it for “cross-cutting” concerns like logging.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/10/mad_scientist.gif"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="Mad_scientist" src="http://complextosimple.files.wordpress.com/2010/10/mad_scientist_thumb.gif?w=464&#038;h=617" border="0" alt="Mad_scientist" width="464" height="617" /></a></p>
<p>The problem is it is usually pretty difficult to use, and the only real practical application I can ever come up with is logging.  I know, it is probably just my lack of knowledge in the area, but if you bear with me I’ll show you a neat little trick you can use to address cross-cutting concerns by doing something similar to what AOP does using Action&lt;&gt;.</p>
<h2>Putting it all in one place</h2>
<p>The main problem AOP tries to solve is taking aspects of your software that exist in many different places and condensing them into one place for you to maintain.</p>
<p>Exception handling and logging tend to be the most infamous of these cross-cutting concerns.  Many places in your code you no doubt have many instances where you catch an exception and the only thing you can really do is log it.</p>
<p>I’m going to show you a little easy way to do that using Action&lt;&gt;.</p>
<p>Giving credit where credit is due, I got this idea from some code that a coworker of mine, Subha Tarafdar, wrote.  (He is a genius.)</p>
<p>He wrote some code to basically do what I am going to show you, but with retrying database queries.  He was able to reduce many places in the code base where we had repeated logic to retry executing database queries when getting a deadlock or timeout.</p>
<h2>Does this code belong to you?</h2>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:f2d7eb61-812a-4fd5-8561-9629ccd7d142" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp; pad-line-numbers: true;">
public void MakeRice()
{
    try
    {
        _riceCooker.Cook();
    }
    catch (Exception exception)
    {
        // Don't care if this fails,
        // there is nothing we can do about it.
        Logger.Log(exception.Message);
    }
}
</pre></p>
</div>
<p>&nbsp;</p>
<p>Ignore that I am catching a general exception here.  It is a bad practice, but sometimes all you are going to do is log whatever bad thing happens and move on.</p>
<p>It’s pretty common to do something in a try block and catch an exception only to log it.</p>
<p>Think about how many times this code or something similar to it might be sprinkled throughout your code base.</p>
<h2>Action&lt;&gt; to the rescue</h2>
<p>If you’re not familiar with Action&lt;&gt; take a look at <a href="http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/">this post</a> I did that gives a very simple explanation for how it works.</p>
<p>We can take the logic of the try, catch, and log exceptions and put it into a method that only varies by what action we do.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a2364bb0-20c6-4565-9562-ea07d996bc33" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public static void LogOnFailure(Action action)
{
    try
    {
        action();
    }
    catch (Exception exception)
    {
        Logger.Log(exception.Message);
    }
}
</pre></p>
</div>
<p>&nbsp;</p>
<p><a href="http://simpleprogrammer.com/2010/01/29/static-methods-will-shock-you/">I’m not a big fan</a> of static methods but in certain cases they make sense.  The alternative is to have all of this code sprinkled throughout your code base.</p>
<p>Now that we have this method, we can do anything we want and know that if there is an error it will be logged.</p>
<p>Check this out:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:75210c50-8eaa-4d5b-805c-8e172cc97c60" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
LogOnFailure(_riceCooker.Cook);
LogOnFailure(KickACat);
LogOnFailure(() =&gt;
                    {
                        Wakeup();
                        SmellTheRoses();
                    }
            );
</pre></p>
</div>
<p>&nbsp;</p>
<p>And if you decide you want to change how you log the error or what you do on it, you can change it all in one place.</p>
<h2>Not just for logging</h2>
<p>You can apply this kind of solution in many places where you have cross cutting concerns in your code base.</p>
<p>Here are a few suggestions for places you might consider this kind of a solution:</p>
<ul>
<li>Retrying on failure logic</li>
<li>Using an alternative service for a failure (web service “A” failed, but we can use web service “B”)</li>
<li>Database connection and connection closing logic.  (Open connection, do something, close connection.)</li>
</ul>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1131/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1131&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/10/mad_scientist_thumb.gif" medium="image">
			<media:title type="html">Mad_scientist</media:title>
		</media:content>
	</item>
		<item>
		<title>Refactoring Step-Wise vs Wrapping and Delegating</title>
		<link>http://simpleprogrammer.com/2010/09/17/refactoring-step-wise-vs-wrapping-and-delegating/</link>
		<comments>http://simpleprogrammer.com/2010/09/17/refactoring-step-wise-vs-wrapping-and-delegating/#comments</comments>
		<pubDate>Fri, 17 Sep 2010 16:03:49 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Legacy Code]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1104</guid>
		<description><![CDATA[In working with legacy code, I often come across the problem of having to refactor classes that contain static methods, or are entirely static methods. I talked about refactoring helper classes before, but this is slightly different. In this case I want to talk about refactoring classes that you want to keep around, but have [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1104&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In working with legacy code, I often come across the problem of having to refactor classes that contain static methods, or are entirely static methods.</p>
<p>I talked about <a href="http://simpleprogrammer.com/2010/04/14/how-to-refactor-the-helper-class/">refactoring helper classes</a> before, but this is slightly different.</p>
<p>In this case I want to talk about refactoring classes that you want to keep around, but have all or many static members.&#160; A good example of this is some kind of service class that returns data from the database.</p>
<p>It’s not always very clear whether that kind of class really is some sort of helper class.&#160; It is a bit of a judgment call.&#160; If you do find a helper class though, <a href="http://simpleprogrammer.com/2010/04/12/should-i-leave-that-helper-class/">don’t just leave it there</a>.</p>
<p>So, basically if you have determined the class you are working with is going to stay, but it does have static methods and you need to get rid of them, because you are doing dependency injection or mocking, read on.</p>
<h2>Defining the two approaches</h2>
<p>What do I mean by step-wise refactoring?</p>
<p>Here is the basic outline of the first approach:</p>
<ol>
<li>Make the method you need to be non-static, non static. </li>
<li>Add an interface with just that one method in it. </li>
<li>Implement the interface. </li>
<li>Change the references to that method to use the interface instead. </li>
</ol>
<p>Let’s take a look at an example:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3e715816-2010-49ac-9b88-b8170d8761c3" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true;">
public static class LostOrderService
{
    public static IEnumerable&lt;Orders&gt; GetLostOrders(int customerId)
    {        
    }

    public static IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
    {
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>If we are interested in the <em>GetLostOrders</em> method, we can apply steps 1-3 to get:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:1163a834-9009-49e6-a720-ea143c8c47f4" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public interface ILostOrderService
{
    IEnumerable&lt;Orders&gt; GetLostOrders(int customerId);
}
    
public class LostOrderService : ILostOrderService
{
    public IEnumerable&lt;Orders&gt; GetLostOrders(int customerId)
    {        
    }

    [Obsolete(&quot;If you touch this refactor to make it not static. 
                      Be a man, do the right thing.&quot;)] 
    public static IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
    {
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Now we can go in and change references in our code for just that one method.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6c7852f0-f108-4ff1-a4f1-b53078cf3db6" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public void ProcessLostOrders()
{
    var orders = LostOrderService.GetLostOrders(_customerId);
    foreach(var order on orders)
    {
        ReprocessOrder();
    }

}

// Refactored becomes:

public void ProcessLostOrders(ILostOrderService lostOrderService)
{
    var orders = lostOrderService.GetLostOrders(_customerId);
    foreach(var order on orders)
    {
        ReprocessOrder();
    }

}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Now let’s look at the 2nd technique, wrapping and delegating.&#160; Here is the outline of the wrapping and delegating approach:</p>
<ol>
<li>Create a wrapper class that’s going to be used to wrap the static classes calls.</li>
<li>Implement all the methods in the static class as non-static methods in the wrapper class.&#160; Each method just delegates to the static method in the static class.</li>
<li>Create an interface which contains all the methods.</li>
<li>Have the wrapper class implement the interface.</li>
</ol>
<p>Here is an example of doing it this way, given the same original code as the first example:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6e093146-d38a-4fe8-9954-5870f5cb1f60" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public interface ILostOrderService
{
    IEnumerable&lt;Orders&gt; GetLostOrders(int customerId);
    IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
}

public class LostOrderServiceWrapper : ILostOrderService
{
    public IEnumerable&lt;Orders&gt; GetLostOrders(int customerId)
    {      
        LostOrderService.GetLostOrders(customerId);
    }

    public IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
    {
        LostOrderService.GetCustomerWithLostOrders();
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>The references to the <em>LostOrderService</em> will be refactored exactly the same as in the first example, so I won’t include it here.</p>
<p>You can see in this example, we didn’t touch <em>LostOrderService</em> itself.&#160; Except, you probably want to put an Obsolete attribute on the class to tell users to not use this, but use the wrapper class instead.</p>
<h2>Which is more bettah?</h2>
<p>I’ve tended to use the wrapping and delegating approach in the past, but I am starting to think the step-wise approach is better for a few reasons.</p>
<ul>
<li>The step-wise approach is a bit more obvious to someone later using the class.&#160; When you wrap and delegate, someone has to know there is a wrapper class.&#160; With the step-wise approach, there is no choice.</li>
<li>With the step-wise approach, you are actually getting rid of the <a href="http://simpleprogrammer.com/2010/01/29/static-methods-will-shock-you/">bad and evil static methods</a>.&#160; When you wrap and delegate, you are still leaving them there, just hiding them behind a wrapper.</li>
</ul>
<p>To me, the wrapping approach feels more like I am working around things rather than cleaning them up.&#160; I also feel like someone can see what I started and pick it up from there step-by-step.&#160; Where with the wrapping approach, the mess may never get cleaned up, because there is a workaround.</p>
<h2>Where wrap and delegate shines</h2>
<p>There is a place that wrap and delegate wins hands down though.</p>
<p>If you don’t have control over the source code of the static class or static calls, you cannot do the step-wise approach.</p>
<p>The wrap and delegate approach can be a lifesaver when you are dealing with static references in your code to an external library that you can not change.&#160; You can simply wrap the external library calls and instead reference the wrapper in your code.&#160; Now you can actually unit test that code.</p>
<p>Anytime you are using an external library, you should consider putting some kind of protective wrapper around it.&#160; You never know when you may want to replace it or upgrade the library.&#160; You don’t want to go hunting through all your code looking for references.</p>
<p>So, while either way will work, I prefer to use the step-wise method if I have access to the source code of the static class.</p>
<p>What do you think?&#160; Do you have any other solutions?</p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.&#160; Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.&#160; Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1104/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1104&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/09/17/refactoring-step-wise-vs-wrapping-and-delegating/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
	</channel>
</rss>
