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

<channel>
	<title>Shizzle &#187; software design</title>
	<atom:link href="http://lenni.info/blog/tag/software-design/feed/" rel="self" type="application/rss+xml" />
	<link>http://lenni.info/blog</link>
	<description>My little notebook</description>
	<lastBuildDate>Wed, 09 May 2012 16:46:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Dependency injection for beginners</title>
		<link>http://lenni.info/blog/2010/02/dependency-injection-for-beginners/</link>
		<comments>http://lenni.info/blog/2010/02/dependency-injection-for-beginners/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 22:46:57 +0000</pubDate>
		<dc:creator>Leonard</dc:creator>
				<category><![CDATA[Mixed]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[modularisation]]></category>
		<category><![CDATA[software design]]></category>

		<guid isPermaLink="false">http://lenni.info/blog/?p=230</guid>
		<description><![CDATA[Pro-forma preamble When I started learning how dependency injection works it was extremely hard for me to understand. Once I got what it does I still didn&#8217;t quite get what the benefits of this technique were. I just thought it was some overly complex design pattern that is just making life difficult for the sake [...]]]></description>
			<content:encoded><![CDATA[<h3>Pro-forma preamble</h3>
<p>When I started learning how dependency injection works it was extremely hard for me to understand. Once I got what it does I still didn&#8217;t quite get what the benefits of this technique were. I just thought it was some overly complex design pattern that is just making life difficult for the sake of it. After all, what is so bad about using <code>new</code> anyway?</p>
<p>Well, in this blog post I want to share what I have learned about dependency injection since leaving university and a becoming full-time programmer last September. I hope I can help a newbie to understand a little more about this design approach. Don&#8217;t be frustrated, however, if you don&#8217;t get it straight away: It took me the best part of my first month to really dive into dependency injection even though I had read lots of articles and blog posts about the topic.</p>
<h3>Dependency injection vs. Inversion of control</h3>
<p>Some authors strangely claim that DI is the same thing as IoC. I however think that DI is a type of IoC, namely to tell the to be injected object what its dependencies are. Inversion of control, to me, means something more general: That there is a predefined workflow (the control part) that the developer hooks her own components into. This principle applies to virtually all libraries and frameworks. For example, your favourite web development framework allows you to write a request handler for a URL, but most likely you can&#8217;t change the nature of the request itself. You will always receive a <code>HttpRequest</code> as the input of your request handling code. Dependency injection however is a specialisation of this principle.</p>
<h3>Modules and dependencies</h3>
<p>When you start to build big systems you naturally tend to modularise. Lets take online shopping as an example. You have one module of your code handling the user input for an order and validating form fields; lets call this module the <code>OrderHandler</code>. Then you have another module, which opens a connection to your payment provider and checks that the credit card data the user just gave are actually kosher and the payment can go ahead. We call this module the <code>CreditCardPaymentService</code>.</p>
<p>So, when the OrderHandler has validated all the form fields it passes the data over to the <code>CreditCardPaymentService</code>. But before it can do that it needs to have or create an instance of the <code>CreditCardPaymentService</code>. In (pseudo-) code this would probably look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> OrderHandler:
   this.<span style="color: black;">payment_service</span> = <span style="color: #dc143c;">new</span> CreditCardPaymentService<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
   handle_request<span style="color: black;">&#40;</span>request<span style="color: black;">&#41;</span>:
     <span style="color: #808080; font-style: italic;"># do something to validate the user input...</span>
     payment_data = request.<span style="color: black;">get_parameters</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
     response = this.<span style="color: black;">payment_service</span>.<span style="color: black;">handle_payment</span><span style="color: black;">&#40;</span>payment_data<span style="color: black;">&#41;</span>
     <span style="color: #ff7700;font-weight:bold;">if</span> response.<span style="color: black;">successful</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
         <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #dc143c;">new</span> HttpResponse<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Payment accepted&quot;</span><span style="color: black;">&#41;</span>
     <span style="color: #ff7700;font-weight:bold;">else</span>:
         <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #dc143c;">new</span> HttpResponse<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Payment declined&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>So far, so good. But what happens when you have quite a few parts of your code taking orders and querying the PaymentService? They all call <code>new CreditCardPaymentService</code>.<br />
Now, your boss has decided your going to switch from your old credit card provider to Paypal. You write a new PaymentProvider that sends a request to their server and authorises the payment. When you actually want to switch over, you will have to replace all instances of <code>CreditCardPaymentProvider</code> with <code>PaypalPaymentProvider</code>. Once you do these kinds of thing a lot, you&#8217;ll end up thinking that there&#8217;s got to be a better way to do this.</p>
<h3>DI to the rescue</h3>
<p>What if all the different modules of your shopping website, instead of creating new instances of <code>PaymentProviders,</code> would instead be given (or <em>injected</em>) those modules?</p>
<p>Maybe we could rewrite the above code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> OrderHandler:
&nbsp;
 this.<span style="color: black;">payment_service</span>=<span style="color: #008000;">None</span>
&nbsp;
 set_payment_service<span style="color: black;">&#40;</span>payment_service<span style="color: black;">&#41;</span>:
    this.<span style="color: black;">payment_service</span>=payment_service
&nbsp;
 handle_request<span style="color: black;">&#40;</span>request<span style="color: black;">&#41;</span>:
    <span style="color: #808080; font-style: italic;"># do something to validate the user input...</span>
    payment_data = request.<span style="color: black;">get_parameters</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    response = this.<span style="color: black;">payment_service</span>.<span style="color: black;">handle_payment</span><span style="color: black;">&#40;</span>payment_data<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> response.<span style="color: black;">successful</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #dc143c;">new</span> HttpResponse<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Payment accepted&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #dc143c;">new</span> HttpResponse<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Payment declined&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Obviously now it is easy to exchange on payment provider with another one. The downside of this that you have to pre-configure the <code>OrderHandler</code> with some type of <code>PaymentProvider</code>. Most DI frameworks do this using Factories and assign each configured, ready-to-use object a string. A factory is supplied with some configuration file that defines those objects and their dependencies.<br />
Those config files could look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* objects.conf */</span>
<span style="color: #cc00cc;">#cc_order_handler</span><span style="color: #00AA00;">&#123;</span>
  class<span style="color: #00AA00;">:</span> OrderHandler
  payment_service<span style="color: #00AA00;">:</span> CreditCardPaymentService
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #cc00cc;">#paypal_order_handler</span><span style="color: #00AA00;">&#123;</span>
  class<span style="color: #00AA00;">:</span> OrderHandler
  payment_service<span style="color: #00AA00;">:</span> PaypalPaymentService
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>We now have a central piece of code that handles each module&#8217;s dependencies. It basically instantiates the OrderHandler, sets the right payment service and then gives this object to whoever wants to use it. If we wanted to fetch on of the order handlers we would do it like this.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">factory = <span style="color: #dc143c;">new</span> ObjectFactory<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;objects.conf&quot;</span><span style="color: black;">&#41;</span>
paypal_payment_handler = factory.<span style="color: black;">getObject</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;paypal_order_handler&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>What you have done now is to externalise the configuration process of  the <code>Handler</code> from inside it to the factory with calls the set_payment_provider method before it returns it to whoever is requesting the object.</p>
<p>As an added benefit we can now easily unit-test the <code>OrderHandler</code> by creating and injecting a fake PaymentService that always returns a positive response.</p>
<h3>Implementations</h3>
<p>This principle is currently used in a lot of enterprise Java applications. The most popular   framework that uses this pattern is <a href="http://www.springsource.org/">Spring</a>. Spring uses XML files for configuration and much of what I described above stems directly from Spring, which actually many more things and DI is just one, albeit central, aspect of the framework.</p>
<p>Another piece of code I also want to have a look at is Google&#8217;s <a href="http://code.google.com/p/google-guice/">Guice</a> which superficially looks less all-singing, all-dancing, but still very interesting.</p>
]]></content:encoded>
			<wfw:commentRss>http://lenni.info/blog/2010/02/dependency-injection-for-beginners/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

