<?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>Androidsx &#187; java</title>
	<atom:link href="http://www.androidsx.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.androidsx.com</link>
	<description>Our Android apps and much more!</description>
	<lastBuildDate>Wed, 09 Jun 2010 20:55:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Don&#8217;t look for things. Ask for them!</title>
		<link>http://www.androidsx.com/dont-look-for-things-ask-for-them/</link>
		<comments>http://www.androidsx.com/dont-look-for-things-ask-for-them/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 11:04:07 +0000</pubDate>
		<dc:creator>Pablo Pera Mira</dc:creator>
				<category><![CDATA[software quality]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.androidsx.com/?p=75</guid>
		<description><![CDATA[Before our previous article, our code to model a mechanic used to look like this:
class Mechanic {
    private final Engine engine = ServiceLocator.getCar().getEngine();
    public void fixEngine() { /* ... */ }
}

Luckily, we applied some dependency injection, resulting in nicer code: testable, and with an explicit dependency on the ServiceLocator:
class [...]]]></description>
			<content:encoded><![CDATA[<p>Before our previous article, our code to model a mechanic used to look like this:</p>
<pre class="brush:java">class Mechanic {
    private final Engine engine = ServiceLocator.getCar().getEngine();
    public void fixEngine() { /* ... */ }
}
</pre>
<p>Luckily, we applied some dependency injection, resulting in nicer code: testable, and with an explicit dependency on the <code>ServiceLocator</code>:</p>
<pre class="brush:java">class Mechanic {
    private final Engine engine;
    public Mechanic(final ServiceLocator serviceLocator) {
        engine = serviceLocator.getCar().getEngine();
    }
    public void fixEngine() { /* ... */ }
}
</pre>
<p>However, does our mechanic care about the <code>ServiceLocator</code> at all? Not really, it doesn&#8217;t even store a reference to it! <strong>The mechanic just wants an engine</strong>.</p>
<p>There are some problems with this kind of code:</p>
<ul>
<li>The <code>ServiceLocator</code> probably has references to a lot of other classes in the system. By the transitive property, our <code>Mechanic</code> class is too coupled with the rest of the system: if you want to reuse it in a different project, you&#8217;d need to reference not only <code>Mechanic</code> and <code>Engine</code>, but also the <code>ServiceLocator</code> with all its dependencies.</li>
<li>The API is not clear. An API client knows that it&#8217;d need to provide the <code>ServiceLocator</code> (already an advantage respect to the Singleton-based case). What it doesn&#8217;t know is what the mechanic really needs (an engine). This fact is hidden in the source code.</li>
<li>The tests contain a lot of setup junk that masks its real purpose. For every test of the mechanic, you&#8217;d need to mock the ServiceLocator, and then make sure the appropriate reference can be retrieved from it (the <code>Engine</code>, in this case). When we test the class <code>Garage</code>, that needs a <code>Mechanic</code>, we&#8217;ll have to replicate this tedious setup there too.</li>
</ul>
<p>This is how the test looks like now:</p>
<pre class="brush:java">
@Test
public void testCantFixBrokenDownEngine() {
    final Engine engine = EngineFactory.buildBrokenEngine();
    final Car mockCark = Mockito.mock(Car.class);
    Mockito.when(mockCar.getEngine()).thenReturn(engine);
    final ServiceLocator mockServiceLocator = Mockito.mock(ServiceLocator.class);
    Mockito.when(mockServiceLocator.getCar()).thenReturn(car);
    final Mechanic mechanic = new Mechanic(mockServiceLocator);
    mechanic.fixEngine();
    assertFalse(engine.works());
}
</pre>
<p><strong>Why not just ask for what you need?</strong></p>
<pre class="brush:java">
class Mechanic {
    private final Engine engine;
    public Mechanic(final Engine engine) {
        this.engine = engine;
    }
    public void fixEngine() { /* ... */ }
}
</pre>
<pre class="brush:java">
@Test
public void testCantFixBrokenDownEngine() {
  Engine engine = EngineFactory.buildBrokenEngine();
  Mechanic mechanic = new Mechanic(engine);
  mechanic.fixEngine();
  assertFalse(engine.works());
}
</pre>
<p><strong>Everyone wins:</strong></p>
<p>API writers:</p>
<ul>
<li>Unaffected by ServiceLocator changes</li>
<li>In-code documentation is easier to write (what was your comment on the <code>Mechanic</code>&#8217;s constructor for the <code>ServiceLocator</code>)?</li>
</ul>
<p>Test writers:</p>
<ul>
<li>Tests are easy to read</li>
<li>Very little setup code</li>
<li>Unaffected by <code>ServiceLocator</code> changes</li>
</ul>
<p>API users:</p>
<ul>
<li>The API is clear: the mechanic needs an engine</li>
</ul>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.androidsx.com%2Fdont-look-for-things-ask-for-them%2F&amp;linkname=Don%26%238217%3Bt%20look%20for%20things.%20Ask%20for%20them%21"><img src="http://www.androidsx.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a><h3  class="related_post_title">Related posts</h3><ul class="related_post"><li><a href="http://www.androidsx.com/cant-test-that-singleton-try-dependency-injection/" title="Can&#8217;t test that Singleton? Try Dependency Injection!">Can&#8217;t test that Singleton? Try Dependency Injection!</a></li><li><a href="http://www.androidsx.com/how-to-write-untestable-code/" title="How to write untestable code">How to write untestable code</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.androidsx.com/dont-look-for-things-ask-for-them/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Can&#8217;t test that Singleton? Try Dependency Injection!</title>
		<link>http://www.androidsx.com/cant-test-that-singleton-try-dependency-injection/</link>
		<comments>http://www.androidsx.com/cant-test-that-singleton-try-dependency-injection/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 20:40:06 +0000</pubDate>
		<dc:creator>Pablo Pera Mira</dc:creator>
				<category><![CDATA[software quality]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.androidsx.com/?p=60</guid>
		<description><![CDATA[So you want to test this method:

public class Client {

    public int process(Params params) {
        final Server server = Server.getInstance();
        final Data data = server.retrieveDate(params);
        // do stuff
    [...]]]></description>
			<content:encoded><![CDATA[<p>So you want to test this method:</p>
<pre class="brush:java">
public class Client {

    public int process(Params params) {
        final Server server = Server.getInstance();
        final Data data = server.retrieveDate(params);
        // do stuff
    }
}
</pre>
<p>We don&#8217;t want to retrieve an instance of a real server for our little unit-test, so how can we test this method?</p>
<p><strong>It is hard to test code that uses singletons.</strong></p>
<p>We don&#8217;t control the creation of the singleton object, as it is performed inside a static method. There is no way to mock the object in order to test the behavior of our method in isolation.</p>
<p><strong>Refactor it to use Dependency Injection.</strong></p>
<p>You can refactor <code>Client</code> to avoid using the singleton pattern. Instead of obtaining the Server instance from the static <code>getInstance()</code> method, allow <code>Client</code> to accept it through its constructor.</p>
<pre class="brush:java">
public class Client {
    private final Server server;  

    public Client(Server server) {
        this.server = server;
    }  

    public int process(Params params) {
        final Data data = server.retrieveData(params);
        // do stuff
    }
}
</pre>
<p>Let&#8217;s write that test now:</p>
<pre class="brush:java">
@Test
public void testConnectionUpTime() {
    final Server mockServer = Mockito.mock(Server.class);
    final Params params = // ...
    Mockito.when(mockServer.process(params)).thenReturn(5);
    final Client client = new Client(mockServer);
    assertEquals(5, client.process(params));
}
</pre>
<p><strong>The code is now both clearer and testable.</strong></p>
<p>The dependency between the client and the server is now explicit: <code>Client client = new Client(server);</code>. There is no way a developer creates a client instance without noticing that a server instance must be configured: it is a parameter in the constructor.</p>
<p>The singleton allowed to create a client instance without configuring the server in advance. The object would be successfully created and the application would execute, until one of the methods runs into a non-configured/non-reachable/null server and fail at runtime :&#8217;-(</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.androidsx.com%2Fcant-test-that-singleton-try-dependency-injection%2F&amp;linkname=Can%26%238217%3Bt%20test%20that%20Singleton%3F%20Try%20Dependency%20Injection%21"><img src="http://www.androidsx.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a><h3  class="related_post_title">Related posts</h3><ul class="related_post"><li><a href="http://www.androidsx.com/dont-look-for-things-ask-for-them/" title="Don&#8217;t look for things. Ask for them!">Don&#8217;t look for things. Ask for them!</a></li><li><a href="http://www.androidsx.com/how-to-write-untestable-code/" title="How to write untestable code">How to write untestable code</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.androidsx.com/cant-test-that-singleton-try-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
