<?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; software quality</title>
	<atom:link href="http://www.androidsx.com/category/software-quality/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>How to write untestable code</title>
		<link>http://www.androidsx.com/how-to-write-untestable-code/</link>
		<comments>http://www.androidsx.com/how-to-write-untestable-code/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 10:08:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[software quality]]></category>

		<guid isPermaLink="false">http://www.androidsx.com/?p=144</guid>
		<description><![CDATA[Say that we write code for a machine that it so powerful that rumors say it could generate a black hole. We need to be serious about security: we cannot let those evil international terrorists find out our black-hole-making secrets and blow half the Milky Way Galaxy.
If they managed to access our source code, they [...]]]></description>
			<content:encoded><![CDATA[<p>Say that we write code for a machine that it so powerful that <a href="http://www.foxnews.com/story/0,2933,538447,00.html?FORM=ZZNR3">rumors say it could generate a black hole</a>. We need to be serious about security: we cannot let those evil international terrorists find out our black-hole-making secrets and blow half the Milky Way Galaxy.</p>
<p>If they managed to access our source code, they could extend it and adapt it to their cruel use case, which would represent a huge threat for the humankind. In order to reduce risks, we should write code that is difficult to understand, to maintain and of course, to test. Here&#8217;s how:</p>
<ul>
<li><strong>Depend on concrete classes</strong> &#8211; Tie things down to concrete classes &#8211; avoid interfaces wherever possible: they let people substitute the concrete classes you&#8217;re using for their own classes which would implement the same contract in the interface. By depending on concrete implementation, we make sure that they&#8217;ll have a hard time testing whether their evil plans will release enough energy to toast their breakfast bread.</li>
<li><strong>Make your own dependencies</strong> &#8211; Instantiate objects using new in the middle of methods, don&#8217;t pass the object in. Anyone that wants to test that code is forced to use that concrete object you new&#8217;ed up: they can&#8217;t inject a dummy, fake, or other mock in to simplify the behavior or make assertions about what you do to it.</li>
<li><strong>Conditional slalom</strong> &#8211; Feel good when writing lengthy if branches and switch statements. These increase the number of possible execution paths that tests will need to cover when exercising the code under test. The higher the cyclomatic complexity, the harder it is to test and understand! Why use polymorphism instead of conditionals? Don&#8217;t make it so easy! Make the branching both deep and wide: if you&#8217;re not consistently going at least 5 conditionals deep, the patient terrorists might even find out what the code intends to do under all possible combinations.
<p>It is also known as the Arrow Antipattern:</p>
<pre class="brush:xml">
if a
    if b
        if c
            foo();
        else
            bar();
        endif
    endif
endif
</pre>
<p>Refactoring into something more suitable is usually possible: </p>
<pre class="brush:xml">
if a &#038;&#038; b
    if c
        foo();
    else
        bar();
    endif
endif
</pre>
</li>
<li><strong>Use global flags</strong> &#8211; Why call a method explicitly? Set a flag in one part of your code, in order to cause an effect in a totally different part of your application. The testers will go crazy trying to figure out why all of a sudden a conditional that was evaluating true one minute is all of a sudden evaluating to false. Not to mention the mess that using that system becomes: if we manage to keep the wikis safe from their hands, they&#8217;ll have a very hard time figuring out what system properties to set in order to get the deadly weapon working.</li>
<li><strong>Loop-switch sequence</strong> &#8211; By means of which a clear set of steps is implemented as a byzantine switch-within-a-loop. Fulfilling our mission to obfuscate the code , is much more difficult to decipher the intent and actual function of the code than the more straightforward refactored solution.
<p>This is a terrorist-safe code snippet:</p>
<pre class="brush:java">
// parse a key, a value, then three parameters
String key = null;
String value = null;
final List<String> params = new LinkedList<String>();

for (int i = 0; i < 5; i++) {
  switch (i) {
    case 0: key = stream.parse(); break;
    case 1: value = stream.parse(); break;
    default: params.add(stream.parse()); break;
  }
}
</pre>
<p>While this is too easy to understand:</p>
<pre class="brush:java">
// parse a key and value
final String key = stream.parse();
final String value = stream.parse();

// parse 3 parameters
final List<String> params = new LinkedList<String>();
for (int i = 0; i < 3; i++) {
  params.add(stream.parse());
}
</pre>
</li>
</ul>
<p><em>References: <a href="http://googletesting.blogspot.com/2008/07/how-to-write-3v1l-untestable-code.html">This post</a> on the <a href="http://googletesting.blogspot.com/">Google Testing Blog</a>, the <a href="http://c2.com/cgi/wiki?ArrowAntiPattern">Arrow AntiPattern</a> in <a href="http://c2.com/">Cunningham &#038; Cunningham</a> webpage.</em></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.androidsx.com%2Fhow-to-write-untestable-code%2F&amp;linkname=How%20to%20write%20untestable%20code"><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/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></ul>]]></content:encoded>
			<wfw:commentRss>http://www.androidsx.com/how-to-write-untestable-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>
