<?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>Miško Hevery &#187; Rant</title>
	<atom:link href="http://misko.hevery.com/category/rant/feed/" rel="self" type="application/rss+xml" />
	<link>http://misko.hevery.com</link>
	<description>Testability Explorer</description>
	<lastBuildDate>Fri, 30 Jul 2010 02:29:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Static Methods are Death to Testability</title>
		<link>http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/</link>
		<comments>http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 14:44:31 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[OO]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=352</guid>
		<description><![CDATA[by Miško Hevery
Recently many of you, after reading Guide to Testability, wrote to telling me there is nothing wrong with static methods. After all what can be easier to test than Math.abs()! And Math.abs() is static method! If abs() was on instance method, one would have to instantiate the object first, and that may prove to [...]]]></description>
			<content:encoded><![CDATA[<p>by <a href="http://misko.hevery.com/about/">Miško Hevery</a></p>
<p>Recently many of you, after reading <a href="http://misko.hevery.com/code-reviewers-guide/">Guide to Testability</a>, wrote to telling me there is nothing wrong with static methods. After all what can be easier to test than <span style="font-family: 'courier new', courier;">Math.abs()</span>! And <span style="font-family: 'courier new', courier;">Math.abs()</span> is static method! If <span style="font-family: 'courier new', courier;">abs()</span> was on instance method, one would have to instantiate the object first, and that may prove to be a problem. (See <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">how to think about the new operator</a>, and <a href="http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/">class does real work</a>)</p>
<p>The basic issue with static methods is they are procedural code. I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation. During the instantiation I <strong>wire</strong> the dependencies with mocks/friendlies which replace the real dependencies. With procedural programing there is <strong>nothing to &#8220;wire&#8221;</strong> since there are no objects, the code and data are separate.</p>
<p>Here is another way of thinking about it. Unit-testing needs seams, seams is where we prevent the execution of normal code path and is how we achieve isolation of the class under test. seams work through polymorphism, we override/implement class/interface  and than wire the class under test differently in order to take control of the execution flow. With static methods there is nothing to override. Yes, static methods are easy to call, but if the static method calls another static method there is no way to overrider the called method dependency.</p>
<p>Lets do a mental exercise. Suppose your application has nothing but static methods. (Yes, code like that is possible to write, it is called procedural programming.) Now imagine the call graph of that application. If you try to execute a leaf method, you will have no issue setting up its state, and asserting all of the corner cases. The reason is that a leaf method makes no further calls. As you move further away from the leaves and closer to the root <span style="font-family: 'courier new', courier;">main()</span> method it will be harder and harder to set up the state in your test and harder to assert things. Many things will become impossible to assert. Your tests will get progressively larger. Once you reach the <span style="font-family: 'courier new', courier;">main()</span> method you  no longer have a unit-test (as your unit is the whole application) you now have a scenario test. Imagine that the application you are trying to test is a word processor. There is not much you can assert from the main method. </p>
<p>We have already covered that <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">global state is bad</a> and how it makes your application <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">hard to understand</a>. If your application has no global state than all of the input for your static method must come from its arguments. Chances are very good that you can move the method as an instance method to one of the method&#8217;s arguments. (As in <span style="font-family: 'courier new', courier;">method(a,b) </span>becomes <span style="font-family: 'courier new', courier;">a.method(b)</span>.) Once you move it you realized that that is where the method should have been to begin with. The use of static methods becomes even worse problem when the static methods start accessing the global state of the application. What about methods which take no arguments? Well, either methodX() returns a constant in which case there is nothing to test; it accesses global state, which is bad; or it is a factory.</p>
<p>Sometimes a static methods is a factory for other objects. This further exuberates the testing problem. In tests we rely on the fact that we can wire objects differently replacing important dependencies with mocks. Once a <span style="font-family: 'courier new', courier;">new</span> operator is called we can not override the method with a sub-class. A caller of such a static factory is permanently bound to the concrete classes which the static factory method produced. In other words the damage of the static method is far beyond the static method itself. Butting object graph wiring and construction code into static method is extra bad, since object graph wiring is how we isolate things for testing.</p>
<p>&#8220;So leaf methods are ok to be static but other methods should not be?&#8221; I like to go a step further and simply say, static methods are not OK. The issue is that a methods starts off being a leaf and over time more and more code is added to them and they lose their positions as a leafs. It is way to easy to turn a leaf method into none-leaf method, the other way around is not so easy. Therefore a static leaf method is a slippery slope which is waiting to grow and become a problem. Static methods are procedural! In OO language stick to OO. And as far as <span style="font-family: 'courier new', courier;">Math.abs(-5)</span> goes, I think Java got it wrong. I really want to write <span style="font-family: 'courier new', courier;">-5.abs()</span>. Ruby got that one right.</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/feed/</wfw:commentRss>
		<slash:comments>42</slash:comments>
		</item>
		<item>
		<title>My main() Method Is Better Than Yours</title>
		<link>http://misko.hevery.com/2008/08/29/my-main-method-is-better-than-yours/</link>
		<comments>http://misko.hevery.com/2008/08/29/my-main-method-is-better-than-yours/#comments</comments>
		<pubDate>Sat, 30 Aug 2008 00:53:35 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Advice]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=195</guid>
		<description><![CDATA[By Miško Hevery
People are good at turning concrete examples into generalization. The other way around, it does not work so well. So when I write about general concepts it is hard for people to know how to translate the general concept into concrete code. To remedy this I will try to show few examples of [...]]]></description>
			<content:encoded><![CDATA[<p>By <a href="http://www.testabilityexplorer.org/about">Miško Hevery</a></p>
<p>People are good at turning concrete examples into generalization. The other way around, it does not work so well. So when I write about general concepts it is hard for people to know how to translate the general concept into concrete code. To remedy this I will try to show few examples of how to build a web application from ground up. But I can&#8217;t fit all of that into a single blog post &#8230; So lets get started at the beginning&#8230;</p>
<p>Here is what your main method should look like (no matter how complex your application) if you are using GUICE: (<a href="http://code.google.com/p/unit-test-teaching-examples/source/browse/trunk/src/di/webserver/GuiceDI.java">src</a>)</p>
<pre>public static void main(String[] args)
  throws Exception {
    // Creation Phase
    Injector injector = Guice.createInjector(
             new CalculatorServerModule(args));
    Server server = injector.getInstance(Server.class);
    // Run Phase
    server.start();
}</pre>
<p>Or if you want to do manual dependency injection: (<a href="http://code.google.com/p/unit-test-teaching-examples/source/browse/trunk/src/di/webserver/ManualDI.java?r=6">src</a>)</p>
<pre>public static void main(String[] args)
  throws Exception {
    // Creation Phase
    Server server = new ServerFactory(args)
                               .createServer();
    // Run Phase
    server.start();
}</pre>
<p>The truth is I don&#8217;t know how to test the main method. The main method is static and as a result there are no places where we can inject test-doubles. (I know we can fight static with static, but we already said that global state is bad <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">here</a>, <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">here</a> and <a href="http://misko.hevery.com/2008/07/24/how-to-write-3v1l-untestable-code/">here</a>). The reason we can&#8217;t test this is that the moment you execute the main method the whole application runs, and that is not what we want and there is nothing we can do to prevent that.</p>
<p>But the method is so short that I don&#8217;t bother testing it since it has some really cool properties:</p>
<ol>
<li>Notice how the creation-phase contains the code which builds the object graph of the application. The last line runs the application. The separation is very important. We can test the ServerFactory in isolation. Passing it different arguments and than asserting that the correct object graph got built. But, in order to do that the Factory class should do nothing but object graph construction. The object constructors better do nothing but field assignments. No reading of files, starting of threads, or any other work which would cause problems in unit-test. All we do is simply instantiate some graph of objects. The graph construction is controlled by the command line arguments which we passed into the constructor. So we can test creation-phase in isolation with unit-test. (Same applies for GUICE example)</li>
<li>The last line gets the application running. Here is where you can do all of your fun threads, file IO etc code. However, because the application is build from lots of objects collaborating together it is easy to test each object in isolation. In test I just instantiate the Server and pass in some test doubles in the constructor to mock out the not so interesting/hard to test code.</li>
</ol>
<p>As you can see we have a clear separation of the object graph construction responsibility from the application logic code. If you were to examine the code in more detail you would find that all of the new operators have migrated from the run-phase  to creation-phase (See <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">How to Think About the “new” Operator</a>) And that is very important. New operator in application code is enemy of testing, but new in tests and factories is your friend. (The reason is that in tests we want to use test-doubles which are usually a subclass or an implementation of the parent class. If application code calls new than you can never replace that new with a subclass or different implementation.) The key is that the object creation responsibility and the the application code are two different responsibilities and they should not be mixed. Especially in the main method!</p>
<p>A good way to think about this is that you want to design your application such that you can control the application behavior by controlling the way you wire the objects together (Object collaborator graph). Whether you wire in a InMemory, File or Database repository, PopServer or IMAPServer, LDAP or file based authentication. All these different behaviors should manifest themselves as different object graphs. The knowledge of how to wire the objects together should be stored in your factory class. If you want to prevent something from running in a test, you don&#8217;t place an if statement in front of it. Instead you wire up a different graph of objects. You wire NullAthenticator in place of LDAPAuthenticator. Wiring your objects differently is how the tests determines what gets run and what gets mocked out. This is why it is important for the tests to have control of the new operators (or putting it differently the application code does not have the new operators). This is why we don&#8217;t know how to test the main method. Main method is static and hence procedural. I don&#8217;t know how to test procedural code since there is nothing to wire differently. I can&#8217;t wire the call graph different in procedural world to prevent things from executing, the call graph is determined at compile time.</p>
<p>In my experience that main method usually is some of the scariest code I have seen. Full of singleton initialization and threads. Completely untestable. What you want is that each object simply declares its dependencies in its constructor. (Here is the list of things I need to know about) Then when you start to write the Factory it will practically write itself. You simply try to new the object you need to return, which declares its dependencies, you in turn try to new those dependencies, etc&#8230; If there are some singletons you just have to make sure that you call the new operator only once. But more on factories in our next blog post&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/08/29/my-main-method-is-better-than-yours/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Root Cause of Singletons</title>
		<link>http://misko.hevery.com/2008/08/25/root-cause-of-singletons/</link>
		<comments>http://misko.hevery.com/2008/08/25/root-cause-of-singletons/#comments</comments>
		<pubDate>Tue, 26 Aug 2008 05:00:57 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Advice]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=192</guid>
		<description><![CDATA[Since I have gotten lots of love/hate mail on the Singletons are Pathological Liars and Where Have All the Singletons Gone I feel obliged to to do some root cause analysis.
Lets get the definition right. There is Singleton the design pattern (Notice the capital &#8220;S&#8221; as in name of something) and there is a singleton [...]]]></description>
			<content:encoded><![CDATA[<p>Since I have gotten lots of love/hate mail on the <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">Singletons are Pathological Liars</a> and <a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">Where Have All the Singletons Gone</a> I feel obliged to to do some root cause analysis.</p>
<p>Lets get the definition right. There is Singleton the design pattern (Notice the capital &#8220;S&#8221; as in name of something) and there is a singleton as in one of something (notice the lower case &#8220;s&#8221;). There is nothing wrong with having a single instance of a class, lots of reasons why you may want to do that. However, when I complain about the Singletons, I complain about the design pattern. Specifically: (1) private constructor and (2) global instance variable which refers to the singleton. So from now on when I say Singleton, I mean the design (anti)pattern.</p>
<p>I would say that at this point most developers recognize that global state is harmful to your application design. Singletons have global instance variable which points to the singleton. The instance is global. The trouble with global variables is that they are transitive. It is not just the global variable marked with static which is global but any other variable/object which is reachable by traversing the object graph. All of it is global! Singletons, usually are complex objects which contain a lot of state. As a result all of the state of Singleton is global as well. I like to say that &#8220;Singletons are global state in sheep&#8217;s clothing.&#8221; Most developers agree that global state is bad, but they love their Singletons.</p>
<p>The moment you traverse a global variable your API lies about its true dependencies (see: <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">Singletons are Pathological Liars</a>) The root problem is not the Singleton design pattern, the root problem here is the global reference to singleton. But the moment you get rid of the global variable you get rid of the Singleton design pattern. So from my point of view blaming Singletons or blaming global state is one and the same. You can&#8217;t have a Singleton design pattern and at the same time not have the global state.</p>
<p>Someone pointed out that any design pattern can be abused. I agree, but with Singleton design pattern, I don&#8217;t know how I can possibly use it in a good way. The global reference and hence the global state is ever so present. Now, in my line of work I don&#8217;t see too much global state in classical sense of the word, but I see a lot of global state masquerading as Singletons. Hence, I complain about Singletons. If I would complain about global state no one would care, as that is old news.</p>
<p>Now, there is one kind of Singleton which is OK. That is a singleton where all of the reachable objects are immutable. If all objects are immutable than Singleton has no global state, as everything is constant. But it is so easy to turn this kind of singleton into mutable one, it is very slippery slope. Therefore, I am against these Singletons too, not because they are bad, but because it is very easy for them to go bad. (As a side note Java enumeration are just these kind of singletons. As long as you don&#8217;t put state into your enumeration you are OK, so please don&#8217;t.)</p>
<p>The other kind of Singletons, which are semi-acceptable are those which don&#8217;t effect the execution of your code. Logging is perfect example. It is loaded with Singletons and global state. It is acceptable (as in it will not hurt you) because your application does not behave any different whether or not a given logger is enabled. The information here flows one way: From your application into the logger. Even thought loggers are global state since no information flows from loggers into your application, loggers are acceptable. You should still inject your logger if you want your test to assert that something is getting logged, but in general Loggers are not harmful despite being full of state.</p>
<p>So the root cause is &#8220;GLOBAL STATE!&#8221; Keep in mind that global state is transitive, so any object which is reachable from a global variable is global as well. It is not possible to have a Singleton and not have a global state. Therefore, Singleton design patter can not be used in &#8220;the right way.&#8221; Now you could have a immutable singleton, but outside of limited use as enumerations, they have little value. Most applications are full of Singletons which have lots of global state, and where the information flows both directions.</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/08/25/root-cause-of-singletons/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Where Have All the Singletons Gone?</title>
		<link>http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/</link>
		<comments>http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 18:48:41 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Advice]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=181</guid>
		<description><![CDATA[by Miško Hevery
In Singletons are Pathological Liars we discussed the problems of having singletons in your code. Let&#8217;s build on that and answer the question &#8220;If I don&#8217;t have singletons how do I ensure there is only one instance of X and how do I get X to all of the places it is needed?&#8221;
An [...]]]></description>
			<content:encoded><![CDATA[<p>by <a href="http://misko.hevery.com/about/">Miško Hevery</a></p>
<p>In <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">Singletons are Pathological Liars</a> we discussed the problems of having singletons in your code. Let&#8217;s build on that and answer the question &#8220;If I don&#8217;t have singletons how do I ensure there is only one instance of X and how do I get X to all of the places it is needed?&#8221;</p>
<p>An OO application is a graph of objects. There are three different kinds of graphs I think of when I design an application</p>
<ol>
<li><strong>Collaborator Graph</strong>: T<span style="border-collapse: collapse; font-family: Arial;">his is the </span>graph of objects that would be emitted if you serialized your application. This shows which objects are aware of which others. (through object&#8217;s fields)</li>
<li><strong>Construction Graph</strong>: This graph shows which object created which other ones.</li>
<li><strong>Call Graph</strong>: This graph shows <span style="border-collapse: collapse;">which other methods each method calls</span>. A stack-trace would be a single slice through this graph.</li>
</ol>
<p>If the new operators are mixed with application logic (see: <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">How to Think About the new Operator</a>) then the Constructor Graph and the Collaborator Graph tend to be one and the same. However, in an application which uses Dependency Injection the two graphs are completely independent. Lets have a closer look at our CreditCardProcessor example. Suppose this is our collaborator graph which we need to execute a request.</p>
<p><a href="http://misko.hevery.com/wp-content/uploads/2008/08/colaboratorgraph.png"><img class="aligncenter size-full wp-image-182" title="Colaborator Graph" src="http://misko.hevery.com/wp-content/uploads/2008/08/colaboratorgraph.png" alt="" width="457" height="330" /></a><br />
The above shows the application collaborator graph. The letter (S/R) in the corner designates object lifetime; either Singleton or Request scope. Now, just to be clear, there is nothing wrong with having a single instance of a class. The problem arises only when the singleton is available through a global &#8220;instance&#8221; variable as in Singleton.getInstance().</p>
<p>The HTTP request would come to AuthenticatorPage which would collaborate with Authenticator to make sure the user is valid and forward a valid request onto ChargePage which would then try to load the user from UserRepository and create the credit card transaction which would be processed by CrediCardProcessor. This in turn would collaborate with OfflineQueue to get the work done.</p>
<p>Now, in order to have a testable codebase we have to make sure that we don&#8217;t mix the object construction with application logic. So all of the above objects should rarely call the new operator (value objects are OK). Instead each of the objects above would declare its collaborators in the constructor. AuthenticatorPage would ask for ChargePage and Authenticator. ChargePage would ask for CreditCardProcessor and UserRepository. And so on. We have moved the problem of construction elsewhere.</p>
<p>In our tests it is now easy to instantiate the graph of objects and substitute test-doubles for our collaborators. For example if we would like to test the AuthenticatorPage, we would instantiate a real AuthenticatorPage with mock ChargePage and mock Authenticator. We would than assert that a request which comes in causes appropriate calls on Authenticator and ChargePage only if authentication is successful. If the AuthenticatorPage were to get a reference to Authenticator from global state or by constructing it, we would not be able to replace the Authenticator with a test-double. (This is why it is so important not to mix object construction with application logic. In the unit-test what you instantiate is a sub-set of the whole application. Hence the instantiation logic has to be separate from application logic! Otherwise, it&#8217;s a non-starter.)</p>
<p>So now the problem is, how do we construct the graph of objects?<br />
<img class="aligncenter size-full wp-image-183" title="Constructor Graph" src="http://misko.hevery.com/wp-content/uploads/2008/08/constructorgraph.png" alt="" width="488" height="482" /></p>
<p>In short we move all of the new operators to a factory. We group all of the objects of similar lifetime into a single factory. In our case all of the singletons end up in ApplicationFactory and all of the Pages end up in RequestFactory. The main method of our application instantiates an ApplicationFactory. When we call build() the ApplicationFactory in turn instantiates its list of objects (Database, OfflineQueue, Authenticator, UserRepository, CreditCardProcessor and RequestFactory). Because each of the objects declares its dependency, the ApplicationFactory is forced to instantiate the objects in the right order. In our case it must instantiate the Database first and than pass the reference to UserRepository and OfflineQueue. (The code will simply not compile any other way.)</p>
<p>Notice that when we create a RequestFactory we must pass in references to the Authenticator, UserRepository and CreditCardProcessor. This is because when we call build() on RequestFactory it will try to instantiate AuthenticatorPage which needs the Authenticator. So we need to pass the Authenticator into the constructor of RequestFactory and so on.</p>
<p>At run-time an HTTP request comes in. The servlet has a reference to RequestFactory and calls build(). The servlet now has a reference to the AuthenticatorPage and it can dispatch the request for processing.</p>
<p>Important things to notice:</p>
<ul>
<li>Every object only has references to what it needs directly! No passing around of objects which are not directly needed by the code. There is no global state at all. Dependencies are obvious since each object only asks for what it needs.</li>
<li>If an object needs a reference to a new dependency it simply declares it. This change only affects the corresponding factory, and as a result, it is very isolated.</li>
<li>All of the new operators end up in the factories; application logic is devoid of new operators.</li>
<li>You group all of the objects with the same lifetime into a single factory (If the factory gets too big you can break it up into more classes, but you can still think of it as a single factory)</li>
<li>The problem of &#8220;how do I ensure that I only have one of something&#8221; is nicely sidestepped. You instantiate only a single ApplicationFactory in your main, and as a result, you only instantiate a single instance of all of your singletons.</li>
</ul>
<p><span style="border-collapse: collapse;"><span style="font-family: Arial;">Now the factories become largely a series of object creations</span></span>. Totally boring stuff, so boring a computer could generate the code. Simply look at the constructor and recursively instantiate whatever the constructor wants. Wait, a computer can generate it! Its called <a href="http://www.picocontainer.org/web/scoping.html">PicoContainer</a> or <a href="http://code.google.com/p/google-guice/">GUICE</a>! So you don&#8217;t actually have to write the factories.</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Changing Developer Behavior &#8211; Part 1</title>
		<link>http://misko.hevery.com/2008/08/19/changing-developer-behavior-part-1/</link>
		<comments>http://misko.hevery.com/2008/08/19/changing-developer-behavior-part-1/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 19:52:59 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Advice]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability Explorer]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=177</guid>
		<description><![CDATA[by Miško Hevery &#124; 19 August 2008 &#124; republished from alphaITjournal

So you&#8217;ve figured out a better way of doing things, but how do you get everyone to change the way they work and start writing code in this better way? This is something I face daily in my line of work as a best practices [...]]]></description>
			<content:encoded><![CDATA[<p>by Miško Hevery | <em>19 August 2008 | republished from <a href="http://www.alphaitjournal.com/2008/08/hevery-changing-developer-behaviour.html">alphaITjournal</a><br />
</em></p>
<p>So you&#8217;ve figured out a better way of doing things, but how do you get everyone to change the way they work and start writing code in this better way? This is something I face daily in my line of work as a best practices coach. Here are my battle tested tricks which work even after I leave the project.</p>
<p><strong><span style="font-size: x-small;">What usually happens</span></strong></p>
<p>Most change initiatives fail because people don&#8217;t appreciate the reasons for making a change, or because they get demotivated by the progress of change.</p>
<p>Think about what usually happens.  Suppose that you have recently discovered the benefits of <a id="bcdo" title="dependency-injection" href="http://martinfowler.com/articles/injection.html">dependency injection</a>. The dependency injection principle requires that object creation code be kept separate from application logic.  Dependencies should be found through the constructor, not by creating them or looking them up in global state. This makes code more maintainable and easier to test, which results in a higher quality codebase. Armed with all of these benefits you decide to implement this on your project. As the lead of the project you give a tech talk to the team on the benefits of dependency injection. Developers come to your tech talk, you all take a vote and everyone agrees that this is what needs to be done.  Everybody goes back to their workstations full of enthusiasm.  People attempt dependency injection in the first few changes they make and you are excited, but a month later everyone is back to their old routine and nothing has changed. How can we break this cycle and achieve lasting change?</p>
<p><strong><span style="font-size: x-small;">Step 1: Get Buy-In</span></strong></p>
<p>The first step is to make sure that everyone is willing to try something new. Although buy-in meetings don&#8217;t achieve anything tangible, they help people understand the reasons why a particular goal is important, and it gives the entire team the opportunity to collectively decide to go after it.</p>
<p>But buy-in isn&#8217;t enough.  We must have some way of knowing that we are implementing the change. To do that, we can use a metric as a proxy for the goal. This makes progress measurable, keeps the goal front-and-center for developers, and lets us know when we&#8217;re done and can declare victory.  Without a metric, we risk losing direction (how do we know our steps are making things better?), losing motivation (individual steps are too small to be seen against the big goal) and losing any sense of accomplishment (because there is always something that can be improved, we don&#8217;t know when we are done with this round of improvements).</p>
<p><strong><span style="font-size: x-small;">Step 2: Define Your Goal in Terms of an Objective Metric</span></strong></p>
<p>The next step is to have a measurable number that gives us an indication of where we are and where we want to be. Although it doesn&#8217;t matter whether this number is an exact measure or just a proxy, it must be repeatable and calculable in an objective way at each stage of adoption.</p>
<p>In Java, byte-code analysis tools are a great way to get to a metric. These can measure very specific things, such as the total number of calls to deprecated APIs or classes/methods which we want to remove.  They can also be used to apply heuristic rules to code, such as determining whether it breaks the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a>, contains excessively deep inheritance, or has too many lines of code in methods or classes.  There are a lot of open source tools available that can measure attributes of code, including <a id="xy55" title="ASM" href="http://asm.objectweb.org/">ASM</a> to write your own metrics, <a id="dxz0" title="JDepend" href="http://clarkware.com/software/JDepend.html">JDepend</a> / <a id="c1vc" title="Japan" href="http://japan.sourceforge.net/">Japan</a> for dependency enforcement, <a id="b85_" title="Panopticode" href="http://www.panopticode.org/">Panopticode</a> for code-quality metrics, and <a id="d-im" title="Testability Explorer" href="http://code.google.com/p/testability-explorer/">Testability Explorer</a> for identifying code that is hard to test.</p>
<p>There are some interesting side-effects to using metrics.  One is that people may initially debate the value of making a change, but the moment there&#8217;s a number &#8211; even if it is a home-grown formula &#8211; the arguments stop.  Another is that management is more likely to support the change: anything that can be measured conveys a sense of visibility and tangible benefit that an unmeasurable change cannot.  Again, these are side-effects, not risks:  having already established team buy-in in the previous step, we&#8217;re not &#8220;managing to a number&#8221; and missing the point of making the change. We&#8217;re simply bringing attention to the progress we&#8217;re making toward that change.</p>
<p>In the example above, we want to get developers to do dependency injection. I developed a metric and corresponding open-source tool called <a id="zylt" title="Testability Explorer" href="http://code.google.com/p/testability-explorer/">Testability Explorer</a> which measures the smallest number of conditions which cannot be mocked out in a test. The idea is that code where branches can be isolated will be easier to test than code where the logic cannot be isolated.  In the latter case, one test will exercise a lot of code and will most likely require complex setup, assertions and tear down. The best metrics are those where gaming the metric produces the desirable outcome in the code. In <a id="w:3l" title="Testability Explorer" href="http://code.google.com/p/testability-explorer/">Testability Explorer</a>, using dependency injection is a good way to improve the score, which is exactly what we are trying to achieve.</p>
<p><strong><span style="font-size: x-small;">Checkpoint: Socially Acceptable, but Not Yet Sustainable</span></strong></p>
<p>Buy-in reinforced with metrics make our proposed change scientific as well as socially acceptable.  But this isn&#8217;t enough: it must be constantly reinforced.  <a href="http://misko.hevery.com/2008/09/10/changing-developer-behaviour-part-ii/">Part II</a> of this series will present ways to make progress toward change highly visible yet subtly encouraged with each and every commit.</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/08/19/changing-developer-behavior-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Singletons are Pathological Liars</title>
		<link>http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/</link>
		<comments>http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 17:43:03 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Advice]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=162</guid>
		<description><![CDATA[by Miško Hevery
So you join a new project, which has an extensive mature code base. Your new lead asks you to implement a new feature, and, as a good developer, you start by writing a test. But since you are new to the project, you do a lot of exploratory &#8220;What happens if I execute [...]]]></description>
			<content:encoded><![CDATA[<p>by <a href="../2008/08/14/about/">Miško Hevery</a></p>
<p>So you join a new project, which has an extensive mature code base. Your new lead asks you to implement a new feature, and, as a good developer, you start by writing a test. But since you are new to the project, you do a lot of exploratory &#8220;What happens if I execute this method&#8221; tests. You start by writing this:</p>
<pre>testCreditCardCharge() {
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(100);
}</pre>
<p>This code:</p>
<ul>
<li>Only works when you run as part of the suite.</li>
<li>When run in isolation, throws NullPointerException.</li>
<li>When you get your credit card bill, you are out $100 for every time the test runs.</li>
</ul>
<p>Now, I want to focus on the last point. How in the world did the test cause an actual charge on my credit card? Charging a credit card is not easy. The test needs to talk to a third party credit card web-service. It needs to know the URL for the web-service. It needs to authenticate, pass the credentials, and identify who the merchant is. None of this information is present in the test. Worse yet, since I don&#8217;t even know where that information is present, how do I mock out the external dependencies so that every run does not result in $100 actually being charged? And as a new developer, how was I supposed to know that what I was about to do was going to result in me being $100 poorer? That is &#8220;Spooky action at a distance!&#8221;</p>
<p>But why do I get NullPointerException in isolation while the test works fine when run as part of the suite? And how do I fix it? Short of digging through lots of source code, you go and ask the more senior and wiser people on the project. After a lot of digging, you learn that you need to initialize the CreditCardProcessor.</p>
<pre>testCreditCardCharge() {
  CreditCardProcessor.init();
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(100);
}</pre>
<p>You run the test again; still no success, and you get a different exception. Again, you chat with the senior and wiser members of the project. Someone tells you that the CreditCardProcessor needs an OfflineQueue to run.</p>
<pre>testCreditCardCharge() {
  OfflineQueue.init();
  CreditCardProcessor.init();
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(100);
}</pre>
<p>Excited, you run the test again: nothing. Yet another exception. You go in search of answers and come back with the knowledge that the Database needs to be initialized in order for the Queue to store the data.</p>
<pre>testCreditCardCharge() {
  Database.init();
  OfflineQueue.init();
  CreditCardProcessor.init();
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(100);
}</pre>
<p>Finally, the test passes in isolation, and again you are out $100. (Chances are that the test will now fail in the suite, so you will have to surround your initialization logic with &#8220;if not initialized then initialize&#8221; code.)</p>
<p>The problem is that the APIs are pathological liars. The credit card pretends that you can just instantiate it and call the charge method. But secretly, it collaborates with the CreditCardProcessor. The CreditCardProcessor API says that it can be initialized in isolation, but in reality, it needs the OfflineQueue. The OflineQueue needs the database. To the developers who wrote this code, it is obvious that the CreditCard needs the CreditCardProcessor. They wrote the code that way. But to anyone new on the project, this is a total mystery, and it hinders the learning curve.</p>
<p>But there is more! When I see the code above, as far as I can tell, the three init statements and the credit card instantiation are independent. They can happen in any order. So when I am re-factoring code, it is likely that I will move and rearrange the order as a side-effect of cleaning up something else. I could easily end up with something like this:</p>
<pre>testCreditCardCharge() {
  CreditCardProcessor.init();
  OfflineQueue.init();
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(100);
  Database.init();
}</pre>
<p>The code just stopped working, but I had no way to knowing that ahead of time. Most developers would be able to guess that these statements are related in this simple example, but on a real project, the initialization code is usually spread over many classes, and you might very well initialize hundreds of objects. The exact order of initialization becomes a mystery.</p>
<p>How do we fix that? Easy! Have the API declare the dependency!</p>
<pre>testCreditCardCharge() {
  Database db = Database();
  OfflineQueue q = OfflineQueue(db);
  CreditCardProcessor ccp = new CreditCardProcessor(q);
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(ccp, 100);
}</pre>
<p>Since the CreditCard charge method declares that it needs a CreditCardProcessor, I don&#8217;t have to  go ask anyone about that. The code will simply not compile without it. I have a clear hint that I need to instantiate a CreditCardProcessor. When I try to instantiate the CreditCardProcessor, I am faced with supplying an OfflineQueue. In turn, when trying to instantiate the OfflineQueue, I need to create a Database. The order of instantiation is clear! Not only is it clear, but it is impossible to place the statements in the wrong order, as the code will not compile. Finally, explicit reference passing makes all of the objects subject to garbage collection at the end of the test; therefore, this test can not cause any other test to fail when run in the suite.</p>
<p>The best benefit is that now, you have seams where you can mock out the collaborators so that you don&#8217;t keep getting charged $100 each time you run the test. You even have choices. You can mock out CreditCardProcessor, or you can use a real CreditCardProcessor and mock out OfflineQueue, and so on.</p>
<p>Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.</p>
<p>Think of it another way. You can live in a society where everyone (every class) declares who their friends (collaborators) are. If I know that Joe knows Mary but neither Mary nor Joe knows Tim, then it is safe for me to assume that if I give some information to Joe he may give it to Mary, but under no circumstances will Tim get hold of it. Now, imagine that everyone (every class) declares some of their friends (collaborators), but other friends (collaborators which are singletons) are kept secret. Now you are left wondering how in the world did Tim got hold of the information you gave to Joe.</p>
<p>Here is the interesting part. If you are the person who built the relationships (code) originally, you know the true dependencies, but anyone who comes after you is baffled, since the friends which are declared are not the sole friends of objects, and information flows in some secret paths which are not clear to you. You live in a society full of liars.</p>
<p>[ Follow up: <a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">Where Have All the Singletons Gone</a> ]</p>
<p>[ Follow up: <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">Root Cause of Singletons</a> ]</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/feed/</wfw:commentRss>
		<slash:comments>47</slash:comments>
		</item>
		<item>
		<title>Top 10 things which make your code hard to test</title>
		<link>http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/</link>
		<comments>http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 21:24:01 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Advice]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=139</guid>
		<description><![CDATA[by Miško Hevery
So you decided to finally give this testing thing a try. But somehow you just can&#8217;t figure out how to write a unit-test for your class. Well there are no tricks to writing tests, there are only tricks to writing testable code. If I gave you testable code you would have no problems [...]]]></description>
			<content:encoded><![CDATA[<p>by <a href="../about/">Miško Hevery</a></p>
<p>So you decided to finally give this testing thing a try. But somehow you just can&#8217;t figure out how to write a unit-test for your class. Well there are no tricks to writing tests, there are only tricks to writing testable code. If I gave you testable code you would have no problems writing a test for it. But, somehow you look at your code and you say, &#8220;I understand how to write tests for your code, but my code is different <em>&lt;insert excuse here&gt;</em>&#8220;. Well your code is different because you violated one or more of the following things. (I will go into the details of each in a separate blog posts)</p>
<ol>
<li><strong>Mixing object graph construction with application logic</strong>: In a test the thing you want to do is to instantiate a portion (ideally just the class under test) of your application and apply some stimulus to the class and assert that the expected behavior was observed.  In order to instantiate the a class in isolation we have to make sure that the class itself does not instantiate other objects (and those objects do not instantiate more objects and so on). Most developers freely mix the &#8220;new&#8221; operator with the application logic. In order to have a testable code-base your application should have two kinds of classes. The factories, these are full of the &#8220;new&#8221; operators and are responsible for building the object graph of your application, but don&#8217;t do anything. And the application logic classes which are devoid of the &#8220;new&#8221; operator and are responsible for doing work. In test we want to test the application logic. And because the application logic is devoid of the &#8220;new&#8221; operator, we can easily construct an object graph useful for testing where we can strategically replace the real classes for test doubles. (see: <a title="Permanent Link to How to Think About the “new” Operator with Respect to Unit Testing" rel="bookmark" href="../2008/07/08/how-to-think-about-the-new-operator/">How to Think About the “new” Operator with Respect to Unit Testing</a>)</li>
<li><strong>Ask for things, Don&#8217;t look for things (aka Dependency Injection / Law of Demeter)</strong>: OK, you got rid of your new operators in you application code. But how do I get a hold of the dependencies. Simple: Just ask for all of the collaborators you need in your constructor. If you are a House class then in your constructor you will ask for the Kitchen, LivingRoom, and BedRoom, you will not call the &#8220;new&#8221; operator on those classes (see 1). Only ask for things you directly need, If you are a CarEngine, don&#8217;t ask for FuelTank, only ask for Fuel. Don&#8217;t pass in a context/registry/service-locator. So if you are a LoginPage, don&#8217;t ask for UserContext, instead ask for the User and the Athenticator. Finally don&#8217;t mix the responsibility of work with configuration, If you are an Authenticator class don&#8217;t pass in a path of the configuration information which you read inside the constructor to configure yourself, just ask for the configuration object and let some other class worry about reading the object from the disk. In your tests you will not want to write a configuration into a disk just so that your object can read it in again. (see: <a title="Permanent Link to Breaking the Law of Demeter is Like Looking for a Needle in the Haystack" rel="bookmark" href="../2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">Breaking the Law of Demeter is Like Looking for a Needle in the Haystack</a>)</li>
<li><strong>Doing work in constructor</strong>: A class under tests can have tens of tests. Each test instantiates a slightly different object graph and than applies some stimulus and asserts a response.  As you can see the most common operation you will do in tests is instantiation of object graphs, so make it easy on yourself and make the constructors do no work (other than assigning all of the dependencies into the fields). Any work you do in a constructor, you will have to successfully navigate through on every instantiation (read every test). This may be benign, or it may be something really complex like reading configuration information from the disk. But it is not just a direct test for the class which will have to pay this price, it will also be any related test which tries to instantiate your class indirectly as part of some larger object graph which the test is trying to create.</li>
<li><strong>Global State</strong>: Global state is bad from theoretical, maintainability, and understandability point of view, but is tolerable at run-time as long as you have one instance of your application. However, each test is a small instantiation of your application in contrast to one instance of application in production. The global state persists from one test to the next and creates mass confusion. Tests run in isolation but not together. Worse yet, tests fail together but problems can not be reproduced in isolation. Order of the tests matters. The APIs are not clear about the order of initialization and object instantiation, and so on. I hope that by now most developers agree that global state should be treated like GOTO.</li>
<li><strong>Singletons (global state in sheep&#8217;s clothing)</strong>: It amazes me that many developers will agree that global state is bad yet their code is full of singletons. (Singletons which enforce their own singletoness through private constructor and a global instance variable) The core of the issue is that the global instance variables have transitive property! All of the internal objects of the singleton are global as well (and the internals of those objects are global as well&#8230; recursively). Singletons are by far the most subtle and insidious thing in unit-testing. I will post more blogs on this topic later as I am sure it will create comments from both sides. (see: <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">Singletons are Pathological Lairs</a>)</li>
<li><strong>Static methods: (or living in a procedural world)</strong>: The key to testing is the presence of seams (places where you can divert the normal execution flow). Seams are essentially polymorphism (Polymorphism: at compile-time the method your are calling can not be determined). Seams are needed so that you can isolate the unit of test. If you build an application with nothing but static methods you have procedural application. Procedural code has no seams, at compile-time it is clear which method calls which other method. I don&#8217;t know how to test application without seams. How much a static method will hurt from a testing point of view depends on where it is in you application call graph. A leaf method such as Math.abs() is not a problem since the execution call graph ends there. But if you pick a method in a core of your application logic than everything behind the method becomes hard to test, since there is no way to insert test doubles (and there are no seams). Additionally it is really easy for a leaf method to stop being a leaf and than a method which was OK as static no longer is. I don&#8217;t know how to unit-test the main method!</li>
<li><strong>Favor composition over inheritance</strong>: At run-time you can not chose a different inheritance, but you can chose a different composition, this is important for tests as we want to test thing in isolation. Many developers use inheritance as code reuse which is wrong. Whether or not inheritance is appropriate depends on whether polymorphism is going on. Inheriting from AuthenticatedServlet will make your sub-class very hard to test since every test will have to mock out the authentication. This will clutter the focus of test, with the things we have to do to successfully navigate the super class. But what if AuthenticatedServlet inherits from DbTransactionServlet? (that gets so much harder)</li>
<li><strong>Favor polymorphism over conditionals</strong>: If you see a switch statement you should think polymorphisms. If you see the same if condition repeated in many places in your class you should again think polymorphism. Polymorphism will break your complex class into several smaller simpler classes which clearly define which pieces of the code are related and execute together. This helps testing since simpler/smaller class is easier to test.</li>
<li><strong>Mixing Service Objects with Value Objects</strong>: There should be two kinds of objects in your application. (1) Value-objects, these tend to have lots of getters / setters and are very easy to construct are never mocked, and probably don&#8217;t need an interface. (Example: LinkedList, Map, User, EmailAddress, Email, CreditCard, etc&#8230;). (2) Service-objects which do the interesting work, their constructors ask for lots of other objects for colaboration, are good candidates for mocking, tend to have an interface and tend to have multiple implementations (Example: MailServer, CreditCardProcessor, UserAthenticator, AddressValidator). A value-object should never take a service object in its constructor (since than it is not easy to construct). Value-objects are the leafs of your application graph and tend to be created freely with the &#8220;new&#8221; operator directly in line with your business logic (exception to point 1 since they are leafs). Service-objects are harder to construct and as a result are never constructed with a new operator in-line, (instead use factory / DI-framework) for the object graph construction. Service-objects don&#8217;t take value-objects in their constructors since DI-frameworks tend to be unaware about the how to create a value-object. From a testing point of view we like value-objects since we can just create them on the fly and assert on their state. Service-objects are harder to test since their state is not clear and they are all about collaboration and as a result we are forced to use mocking, something which we want to minimize. Mixing the two creates a hybrid which has no advantages of value-objects and all the baggage of service-object.</li>
<li><strong>Mixing of Concerns</strong>: If summing up what the class does includes the word &#8220;and&#8221;, or class would be challenging for new team members to read and quickly &#8220;get it&#8221;, or class has fields that are only used in some methods, or class has static methods that only operate on parameters than you have a class which mixes concerns. These classes are hard to tests since there are multiple objects hiding inside of them and as a resulting you are testing all of the objects at once.</li>
</ol>
<p>So here is my top 10 list on testability, the trick is translating these abstract concepts into concrete decisions in your code.</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>How to Write 3v1L, Untestable Code</title>
		<link>http://misko.hevery.com/2008/07/24/how-to-write-3v1l-untestable-code/</link>
		<comments>http://misko.hevery.com/2008/07/24/how-to-write-3v1l-untestable-code/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 21:09:13 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Advice]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Testability]]></category>

		<guid isPermaLink="false">http://misko.hevery.com/?p=130</guid>
		<description><![CDATA[by Miško Hevery, Jonathan Wolter, Russ Ruffer, Brad Cross, and lots of other test infected Googlers
This guide lists principles that will help you write impossible to tests code. Or, avoiding these techniques will help you write code that can be tested.

 Make Your Own Dependencies &#8211; Instantiate objects using new in the middle of methods, [...]]]></description>
			<content:encoded><![CDATA[<p>by <a href="http://misko.hevery.com/about/">Miško Hevery</a>, <a href="http://jawspeak.com/">Jonathan Wolter</a>, Russ Ruffer, Brad Cross, and lots of other test infected Googlers</p>
<p>This guide lists principles that will help you write impossible to tests code. Or, avoiding these techniques will help you write code that can be tested.</p>
<ul>
<li> <strong>Make Your Own Dependencies</strong> &#8211; Instantiate objects using new in the middle of methods, don&#8217;t pass the object in. This is evil because whenever you new up an object inside a block of code and then use it, anyone that wants to test that code is also forced to use that concrete object you new&#8217;ed up. They can&#8217;t &#8220;inject&#8221; a dummy, fake, or other mock in to simplify the behavior or make assertions about what you do to it.</li>
<li> <strong>Heavy Duty Constructors</strong> &#8211; Make constructors that do lots of work in them. The more work you do in the constructor, the hard it is to create your object in a test fixture. And if your constructor can construct other things that are hard themselves to construct, that&#8217;s even better! You want the transitive dependencies of every constructor to be enormous. Enormous is hard to get under test.</li>
<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 or abstract class. Testing do-gooders might want to do this to get your code under a test harness &#8211; don&#8217;t let them!)</li>
<li> <strong>Conditional Slalom</strong> &#8211; Always, always, feel good when writing lengthy <code>if</code> branches and <code>switch</code> 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! When someone suggests to use polymorphism instead of conditionals, laugh at their thoughtfulness towards testing. Make the branching both deep and wide: if you&#8217;re not consistently at least 5 conditionals deep, you&#8217;re spoon feeding testable code to the TDD zealots.</li>
<li> <strong>Depend on Large Context Objects</strong> &#8211; Pass around ginormous context objects (or small ones with hard to construct contents). These will reduce the clarity of methods [myMethod(Context ctx) is less clear than myMethod(User user, Label label)]. For testing, the context objects will need to be created, populated, and passed around.</li>
<li> <strong>Use Statics</strong> &#8211; Statics, statics everywhere! They put a great big crunch in testability. They can&#8217;t be mocked, and are a smell that you&#8217;ve got a method without a home. OO zealots will say that a static method is a sign that one of the parameters should own the method. But you&#8217;re being 3v1L!</li>
<li> <strong>Use More Statics</strong> &#8211; Statics are a really powerful tool to bring TDD Infected engineers to their knees. Static methods can&#8217;t be overridden in a subclass (sometimes subclassing a class and overriding methods is a technique for testing). When you use static methods, they can&#8217;t be mocked using mocking libraries (nixing another trick up the pro-testing engineer&#8217;s sleeve).</li>
<li> <strong>Use Global Flags</strong> &#8211; Why call a method explicitly? Just like L Ron Hubbard, use &#8220;mind over matter&#8221; to set a flag in one part of your code, in order to cause an effect in a totally different part of your application (it&#8217;s even more fun when you do it concurrently in different threads!). 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.</li>
<li> <strong>Use Singletons Everywhere</strong> &#8211; Why pass in a dependency and make it obvious when you can use a singleton? It&#8217;s hard to set up a test that requires singletons, and the TDDers will be in for a world of hurt when all their tests depend on each other&#8217;s state.</li>
<li> <strong>Be Defensive &#8211; They&#8217;re out to Get Your Code!</strong> &#8211; Defensively assert about the state of parameters passed in methods, constructors, and mid-method. If someone can pass in a null, you&#8217;ve left your guard down. You see, there are testing freaks out there that like to instantiate your object, or call a method under test and pass in nulls! Be aggressive in preventing this: rule your code with an iron fist! (And remember: it&#8217;s not paranoia if <em>they really are out to get you</em>.)</li>
<li> <strong>Use Primitives Wherever Possible</strong> &#8211; Instead of using a &#8220;cookie object,&#8221; pass in primitives and do all the parsing you need, every time you need a value. Primitives make people work harder by having to parse and massage them to get the data out &#8212; where objects are mockable (gasp) and nullable, and encapsulate state (who&#8217;d want to do that?)</li>
<li> <strong>Look for Everything You Need</strong> &#8211; By Looking for things you are asserting your objects dominance as the object which knows where everything is. This will make the life of tester hard, since he will have to mimic the environment so that your code can get a hold of what it needs. And don&#8217;t be afraid of how many objects you need to reach out to to, the more the harder it will be for test to mock them all out in unisin. If you are an InvoiceTaxCalculator, feel free to do things like: invoiceTaxCalculator.getUser().getDbManager().getCaRateTables().getSalesTaxRate(). Cover your ears when some testing weenie tells you about <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/" target="_self">Dependency Injection</a>, <a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/" target="_self">Law of Demeter</a>, or not looking for things.</li>
<li> <strong>Use static initializes</strong> &#8211; Do as much work as possible when your class is loaded. Testing nuts will be so frustrated when they find out just loading your class causes nasty stuff like network or file access.</li>
<li> <strong>Couple functional code directly to the external systems it depends on</strong> If your product uses external systems such as a databases, file systems or a network, make sure your business logic is coded to reference as many low level implementation details of these systems as possible. This will prevent others from using your code in ways you don&#8217;t intend, (like small tests that run in 2 ms instead of 5 minutes).</li>
<li> <strong>Mix Object Lifecycles</strong> &#8211; Have long lived objects reference short lived objects. This confuses people as the long lived object references the short lived object still after it&#8217;s no longer valid or alive. This is especially insidious, both bad design, and evil, hard to test.<a name="Side_Effects_are_the_Way_to_Go"></a></li>
<li><strong>Side Effects are the Way to Go</strong> Your best bet is to perform a large number of side effect producing operations in your methods. This is especially true for setters. The more non-obvious the side effects better. Peculiar and seemingly irrational side effects are particularly helpful for unit testing. To add another layer of sweet creamy goodness on top, you want to make it possible to initialize your objects in an invalid state, with uninitialized member fields. Once you have achieved this, be sure to make calls on the methods of the uninitialized fields as side effects from your setters in order to cause SEGV&#8217;s or NPE&#8217;s, depending on your language&#8217;s vernacular. Why go to all this trouble? Clean, readable, and testable code that works, that&#8217;s why! Side effect free functions are for intellectual weaklings that think a function name should give some kind of an indication of what the function does.</li>
<li> <strong>Create Utility Classes and Functions/Methods</strong> &#8211; For instance, you have a String which is a URL you&#8217;re passing around (obeying &#8220;Use Primitives Wherever Possible&#8221;). Create another class with static methods such as isValidUrl(String url). Don&#8217;t let the OO police tell you to make that a method on a URL object. And if your static utility methods can call to external services as well, that&#8217;s even better!</li>
<li> <strong>Create Managers and Controllers</strong> &#8211; all over the place have these Managers and Controllers meddling in the responsibilities of other objects. Don&#8217;t bother trying to pull that responsibility into other individual objects. Look at a SomeObjectManager class and you have no idea what it&#8217;s going to do.</li>
<li> <strong>Do Complicated Creation Work in Objects</strong> &#8211; Whenever someone suggests you to use a Factory to instantiate things, know that you are smarter than them. You&#8217;re more intelligent than they must be, because your objects can have multiple responsibilities and be thousands of lines long.</li>
<li> <strong>Greenlight if-branches and switch statements</strong> &#8211; Go ahead, don&#8217;t feel dirty about nesting if-branches. It&#8217;s &#8220;more readable&#8221; that way. OO cowboys will want to have a whole polymorphic soup of collaborating objects. Say no to the OO-ist. When you nest and branch conditionals, all you need to do is read the code from top to bottom. Like a great novel, one simple linear prose of code. With the OO-overboard paradigm, it&#8217;s like a terrible choose-your-own-adventure kid&#8217;s book. You&#8217;re constantly flipping between classes and juggling patterns and so many more complex concepts. Just if-things out and you&#8217;ll be fine.</li>
<li> <strong>Utils, Utils, Utils!</strong> &#8211; Code smell? No way &#8211; code perfume! Litter about as many util and helper classes as you wish. These folks are helpful, and when you stick them off somewhere, someone else can use them too. That&#8217;s code reuse, and good for everyone, right? Be forewarned, the OO-police will say that functionality belongs in some object, as that object&#8217;s responsibility. Forget it, you&#8217;re way to pragmatic to break things down like they want. You&#8217;ve got a product to ship after all!</li>
<li> <strong>Use &#8220;Refactoring&#8221; whenever you need to get away with something</strong> &#8211; This is a word that Test-Driven and OO-goons like. So if you want to do something far reaching, involving new functionality, without tests, just tell them you&#8217;re &#8220;Refactoring.&#8221; It&#8217;ll trick them every time. No matter that they think you need to have tests around everything before you can refactor, and that it should never add new functionality. Ignore their hubbub, and do things your own way!</li>
</ul>
<h3>Java Specific</h3>
<ul>
<li> <strong>Final Methods</strong> &#8211; Use final classes and methods all the time. They can&#8217;t be overridden for testing (-; But don&#8217;t bother making fields final, or using value objects (without setters) &#8211; just let your objects&#8217; state be changed by anything and anyone. No sense in guaranteeing state, it&#8217;d make things too easy.</li>
<li> <strong>Handcuff your users to Specific Types</strong> &#8211; Use <code>instanceof</code> as much as possible. This will make Mocking a pain, and show people that you&#8217;re in control of the objects allowed.</li>
</ul>
<h3>C++ Specific</h3>
<ul>
<li> <strong>Use non-virtual methods</strong> &#8211; Unless you need to override the method in a deep and scary inheritance hierarchy, just make the method non-virtual. If you make it virtual, a TDD zealot may mock your class! An even nicer trick is to keep your destructor non-virtual &#8211; then when the testing freaks try to subclass, whooooaoaaaaaa&#8230;.</li>
<li> <strong>Never use pure abstract classes</strong> &#8211; Depending on pure abstract classes is a sure-fire way to let the TDD crazies inject stubs and mocks into your code, making it testable.</li>
<li> <strong>Macros are your friends</strong> &#8211; Always use <code>#ifdef PROD</code> and other compile-time switches to make sure the testies can&#8217;t get at your really important blocks of code and test them. In fact, this code won&#8217;t even run: until it gets to production!</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/07/24/how-to-write-3v1l-untestable-code/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Dynamic Languages are not Inherently More Testable</title>
		<link>http://misko.hevery.com/2008/07/13/dynamic-languages-are-not-more-testable/</link>
		<comments>http://misko.hevery.com/2008/07/13/dynamic-languages-are-not-more-testable/#comments</comments>
		<pubDate>Mon, 14 Jul 2008 03:32:36 +0000</pubDate>
		<dc:creator>misko</dc:creator>
				<category><![CDATA[Dynamic Languages]]></category>
		<category><![CDATA[Rant]]></category>

		<guid isPermaLink="false">http://s90424825.onlinehome.us/blog/?p=46</guid>
		<description><![CDATA[Lately a lot of people have been arguing that dynamic languages (JavaScript, Python, Ruby) are inherently more testable then static languages such as Java. (See Java is Naturally Untestable, Comments) But in my opinion it is a bad idea and a misdirected argument.

Mutable global state is bad
Replacing methods at runtime is mutating global state
It can [...]]]></description>
			<content:encoded><![CDATA[<p>Lately a lot of people have been arguing that dynamic languages (JavaScript, Python, Ruby) are inherently more testable then static languages such as Java. (See <a href="http://blog.thinkrelevance.com/2008/5/18/java-is-naturally-untestable">Java is Naturally Untestable</a>, <a href="https://www.blogger.com/comment.g?blogID=15045980&amp;postID=9081839922903151980">Comments</a>) But in my opinion it is a bad idea and a misdirected argument.</p>
<ul>
<li>Mutable global state is bad</li>
<li>Replacing methods at runtime is mutating global state</li>
<li>It can be done in Java, but I don&#8217;t recommend it, it is a bad idea and it misses the point.</li>
</ul>
<div style="margin: 5px 10px; display: inline; float: right;"><img src="http://spreadsheets.google.com/pub?key=p5f7FqS_WauJGv8wm5jkgOw&amp;oid=1&amp;output=image" alt="" /></div>
<p>First, let me just state that which I hope all readers already know. &#8220;Mutating Global State&#8221; is a bad idea. Still, not convinced that global state leads to hard to test, maintain and understand code base? Check <a href="http://en.wikipedia.org/wiki/Global_variables">Wikipedia</a> or search the web for &#8220;<a href="http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=lbS&amp;q=global+variables+good&amp;btnG=Search">Global Variables Good</a>&#8221; &amp; &#8220;<a href="http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=Cx7&amp;q=global+variables+bad&amp;btnG=Search">Global Variables Bad</a>&#8220;. Here is the breakdown of web page hits returned by Google.</p>
<p>Dynamic languages allow you to change method definition at runtime. On one side this makes testing really easy since now I have a lot more seams in my application where I can intercept the calls. At first glance it looks like that this is a good idea. The problem is that code is part of your global state. In static languages the code is not mutable hence it is a constant and therefore not part of global state. In dynamic languages distinction between code and data is blurred and therefore it can be changed. Since code can be mutated and it is globally accessible it is part of the global state.</p>
<p>Here is a list of problems which you encounter when trying to test an application which has a lot of global state. Notice how all of these issues apply to testing code in a dynamic language where we did monkey-patching in order to intercept method calls:</p>
<ul>
<li>The order of tests matter (test may communicate through global state)</li>
<li>Tests can not be run in parallel (global state interactions)</li>
<li>We need a teardown method for cleanup (code smell of global state)</li>
<li>New tests can break old tests (by changing global state)</li>
<li>Tests know too much about the implementation (refactoring code breaks our tests)</li>
</ul>
<p>So the argument goes like this. Dynamic languages are more testable because through mutable global state we have more seams than static languages. But this misses the point. Why is your code base written in such a bad way that you have to resort to such drastic measures like global state. Yes many design errors can be hacked through global state, but that does not make it a good idea!</p>
<p>In Java we too can replace method definitions at runtime. It is called a <tt>ClassLoader</tt>. You simply create a new <tt>ClassLoader</tt> and as you load your code you can replace a method call with another method call. There are even frameworks which make this easy known as Aspect Oriented Programming. But you don&#8217;t see anyone suggesting this in Java world as a good approach to testing.</p>
<p>Too me it sounds more like: Dynamic languages encourage bad application design since they provide so much rope that they make it impossible for you to hang yourself instead you drown in it.</p>
<p><strong>Disclaimer</strong>: I am actually a big fan of dynamic languages. And this blog by no means should be read as Java is better than &lt;<em>chose you favorite dynamic language</em>&gt;. Instead read this as people who claim that in dynamic languages there is no need for dependency injection and good OO design really don&#8217;t understand how to write well designed and testable code. Yes, you can fight static with static, but it does not make it a good idea, its still <a href="http://googletesting.blogspot.com/2008/06/defeat-static-cling.html">static cling</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://misko.hevery.com/2008/07/13/dynamic-languages-are-not-more-testable/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
