<?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>Google Data &#187; Misko</title>
	<atom:link href="/author/misko/feed/" rel="self" type="application/rss+xml" />
	<link>https://googledata.org</link>
	<description>Everything Google: News, Products, Services, Content, Culture</description>
	<lastBuildDate>Wed, 18 Mar 2015 21:09:38 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.7.5</generator>
	<item>
		<title>How to get Started with TDD</title>
		<link>https://googledata.org/google-testing/how-to-get-started-with-tdd/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-get-started-with-tdd</link>
		<comments>https://googledata.org/google-testing/how-to-get-started-with-tdd/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 09:51:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[By Miško HeveryBest way to learn TDD is to have someone show you while pairing with you. Short of that, I have set up an eclipse project for you where you can give it a try:hg clone https://bitbucket.org/misko/misko-hevery-blog/Open project blog/tdd/0...]]></description>
				<content:encoded><![CDATA[By <a href="http://misko.hevery.com/">Miško Hevery</a><br /><br />Best way to learn TDD is to have someone show you while pairing with you. Short of that, I have set up an eclipse project for you where you can give it a try:<br /><ol><br /><li><span style=" white-space: pre;font-family:monospace;">hg clone <a href="https://bitbucket.org/misko/misko-hevery-blog/">https://bitbucket.org/misko/misko-hevery-blog/</a></span></li><br /><li>Open project <span style="font-family:monospace, 'Times New Roman', 'Bitstream Charter', Times, serif;"><span style="white-space: pre;">blog/tdd/01_Calculator</span></span> in Eclipse.</li><br /><li>It should be set up to run all tests every time you modify a file.<br /><ul><br /><li>You may have to change the path to java if you are not an Mac OS.</li><br /><li>Project -&gt; Properties -&gt; Builders -&gt; Test -&gt; Edit</li><br /><li>Change location to your java</li><br /></ul><br /></li><br /><li>Right-click on Calculator.java -&gt; Run As -&gt; Java Application to run the calculator</li><br /></ol><br />Your mission is to make the calculator work using TDD. This is the simplest form of TDD where you don't have to mock classes or create complex interactions, so it should be a good start for beginners.<br /><br />TDD means:<br /><ol><br /> <li>write a simple test, and assert something interesting in it</li><br /> <li> implement just enough to make that tests green (nothing more, or you will get ahead of your tests)</li><br /> <li>then write another test, rinse, and repeat.</li><br /></ol><br />I have already done all of the work of separating the behavior from the UI, so that the code is testable and properly Dependency Injected, so you don't have to worry about running into testability issues.<br /><ul><br /><li>Calculator.java: This is the main method and it is where all of the wiring is happening.</li><br /><li>CalculatorView.java: This is a view and we don't usually bother unit testing it has cyclomatic complexity of one, hence there is no logic. It either works or does not. Views are usually good candidates for end-to-end testing, which is not part of this exercise.</li><br /><li>CalculatorModel.java: is just a PoJo which marshals data from the Controller to the View, not much to test here.</li><br /><li>CalculatorController.java: is where all of your if statements will reside, and we need good tests for it.</li><br /></ul><br />I have started you off with first 'testItShouldInitializeToZero' test. Here are some ideas for next tests you may want to write.<br /><ul><br /><li>testItShouldConcatinateNumberPresses</li><br /><li>testItShouldSupportDecimalPoint</li><br /><li>testItShouldIgnoreSecondDecimalPoint</li><br /><li>testItShouldAddTwoIntegers</li><br /></ul><br />I would love to see what you will come up with and what your thoughts are, after you get the whole calculator working. I would also encourage you to post interesting corner case tests here for others to incorporate. If you want to share your code with others, I would be happy to post your solutions.<br /><br />Good luck!<br /><br />PS: I know it is trivial example, but you need to start someplace.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-9018312402946084820?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/how-to-get-started-with-tdd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cost of Testing</title>
		<link>https://googledata.org/google-testing/cost-of-testing/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=cost-of-testing</link>
		<comments>https://googledata.org/google-testing/cost-of-testing/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 16:07:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[By Miško HeveryA lot of people have been asking me lately, what is the cost of testing, so I decided, that I will try to measure it, to dispel  the myth that testing takes twice as long.For the last two weeks I have been keeping track of the amount of...]]></description>
				<content:encoded><![CDATA[By <a href="http://misko.hevery.com/">Miško Hevery</a><br /><br />A lot of people have been asking me lately, what is the cost of testing, so I decided, that I will try to measure it, to dispel  the myth that testing takes twice as long.<br /><br />For the last two weeks I have been keeping track of the amount of time I spent writing tests versus the time writing production code. The number surprised even me, but after I thought about it, it makes a lot of sense. The magic number is about 10% of time spent on writing tests. Now before, you think I am nuts, let me back it up with some real numbers from a personal project I have been working on.<br /><br /><table border="0"><tbody></tbody><tbody><tr><th></th><th>Total</th><th>Production</th><th>Test</th><th>Ratio</th></tr><tr><th>Commits</th><td>1,347</td><td>1,347</td><td>1,347</td><td></td></tr><tr><th>LOC</th><td>14,709</td><td>8,711</td><td>5,988</td><td>40.78%</td></tr><tr><th>JavaScript LOC</th><td>10,077</td><td>6,819</td><td>3,258</td><td>32.33%</td></tr><tr><th>Ruby LOC</th><td>4,632</td><td>1,892</td><td>2,740</td><td>59.15%</td></tr><tr><th>Lines/Commit</th><td>10.92</td><td>6.47</td><td>4.45</td><td>40.78%</td></tr><tr><th>Hours(estimate)</th><td>1,200</td><td>1,080</td><td>120</td><td>10.00%</td></tr><tr><th>Hours/Commit</th><td>0.89</td><td>0.80</td><td>0.09</td><td></td></tr><tr><th>Mins/Commit</th><td>53</td><td>48</td><td>5</td><td></td></tr></tbody></table><br />Commits refers to the number of commits I have made to the repository. LOC is lines of code which is broken down by language. The ratio shows the typical breakdown between the production and test code when you test drive and it is about half, give or take a language. It is interesting to note that on average I commit about 11 lines out of which 6.5 are production and 4.5 are test. Now, keep in mind this is average, a lot of commits are large where you add a lot of code, but then there are a lot of commits where you are tweaking stuff, so the average is quite low.<br /><br />The number of hours spent on the project is my best estimate, as I have not kept track of these numbers. Also, the 10% breakdown comes from keeping track of my coding habits for the last two weeks of coding. But, these are my best guesses.<br /><br />Now when I test drive, I start with writing a test which usually takes me few minutes (about 5 minutes) to write. The test represents my scenario. I then start implementing the code to make the scenario pass, and the implementation usually takes me a lot longer (about 50 minutes). The ratio is highly asymmetrical! Why does it take me so much less time to write the scenario than it does to write the implementation given that they are about the same length? Well look at a typical test and implementation:<br /><br />Here is a typical test for a feature:<br /><pre>ArrayTest.prototype.testFilter = function() {<br /> var items = ["MIsKO", {name:"john"}, ["mary"], 1234];<br /> assertEquals(4, items.filter("").length);<br /> assertEquals(4, items.filter(undefined).length);<br /><br /> assertEquals(1, items.filter('iSk').length);<br /> assertEquals("MIsKO", items.filter('isk')[0]);<br /><br /> assertEquals(1, items.filter('ohn').length);<br /> assertEquals(items[1], items.filter('ohn')[0]);<br /><br /> assertEquals(1, items.filter('ar').length);<br /> assertEquals(items[2], items.filter('ar')[0]);<br /><br /> assertEquals(1, items.filter('34').length);<br /> assertEquals(1234, items.filter('34')[0]);<br /><br /> assertEquals(0, items.filter("I don't exist").length);<br />};<br /><br />ArrayTest.prototype.testShouldNotFilterOnSystemData = function() {<br /> assertEquals("", "".charAt(0)); // assumption<br /> var items = [{$name:"misko"}];<br /> assertEquals(0, items.filter("misko").length);<br />};<br /><br />ArrayTest.prototype.testFilterOnSpecificProperty = function() {<br /> var items = [{ignore:"a", name:"a"}, {ignore:"a", name:"abc"}];<br /> assertEquals(2, items.filter({}).length);<br /><br /> assertEquals(2, items.filter({name:'a'}).length);<br /><br /> assertEquals(1, items.filter({name:'b'}).length);<br /> assertEquals("abc", items.filter({name:'b'})[0].name);<br />};<br /><br />ArrayTest.prototype.testFilterOnFunction = function() {<br /> var items = [{name:"a"}, {name:"abc", done:true}];<br /> assertEquals(1, items.filter(function(i){return i.done;}).length);<br />};<br /><br />ArrayTest.prototype.testFilterIsAndFunction = function() {<br /> var items = [{first:"misko", last:"hevery"},<br />              {first:"mike", last:"smith"}];<br /><br /> assertEquals(2, items.filter({first:'', last:''}).length);<br /> assertEquals(1, items.filter({first:'', last:'hevery'}).length);<br /> assertEquals(0, items.filter({first:'mike', last:'hevery'}).length);<br /> assertEquals(1, items.filter({first:'misko', last:'hevery'}).length);<br /> assertEquals(items[0], items.filter({first:'misko', last:'hevery'})[0]);<br />};<br /><br />ArrayTest.prototype.testFilterNot = function() {<br /> var items = ["misko", "mike"];<br /><br /> assertEquals(1, items.filter('!isk').length);<br /> assertEquals(items[1], items.filter('!isk')[0]);<br />};</pre><br />Now here is code which implements this scenario tests above:<br /><pre>Array.prototype.filter = function(expression) {<br /> var predicates = [];<br /> predicates.check = function(value) {<br />   for (var j = 0; j &lt; predicates.length; j++) {<br />      if(!predicates[j](value)) {<br />        return false;<br />      }<br />    }<br />    return true;<br />  };<br />  var getter = Scope.getter;<br />  var search = function(obj, text){<br />    if (text.charAt(0) === '!') {<br />      return !search(obj, text.substr(1));<br />    }<br />    switch (typeof obj) {<br />    case "bolean":<br />    case "number":<br />    case "string":<br />      return ('' + obj).toLowerCase().indexOf(text) &gt; -1;<br />   case "object":<br />     for ( var objKey in obj) {<br />       if (objKey.charAt(0) !== '$' &amp;&amp; search(obj[objKey], text)) {<br />         return true;<br />       }<br />     }<br />     return false;<br />   case "array":<br />     for ( var i = 0; i &lt; obj.length; i++) {<br />       if (search(obj[i], text)) {<br />         return true;<br />       }<br />     }<br />     return false;<br />   default:<br />     return false;<br />   }<br /> };<br /> switch (typeof expression) {<br />   case "bolean":<br />   case "number":<br />   case "string":<br />     expression = {$:expression};<br />   case "object":<br />     for (var key in expression) {<br />       if (key == '$') {<br />         (function(){<br />           var text = (''+expression[key]).toLowerCase();<br />           if (!text) return;<br />           predicates.push(function(value) {<br />             return search(value, text);<br />           });<br />         })();<br />       } else {<br />         (function(){<br />           var path = key;<br />           var text = (''+expression[key]).toLowerCase();<br />           if (!text) return;<br />           predicates.push(function(value) {<br />             return search(getter(value, path), text);<br />           });<br />         })();<br />       }<br />     }<br />     break;<br />   case "function":<br />     predicates.push(expression);<br />     break;<br />   default:<br />     return this;<br /> }<br /> var filtered = [];<br /> for ( var j = 0; j &lt; this.length; j++) {<br />   var value = this[j];<br />   if (predicates.check(value)) {<br />     filtered.push(value);<br />   }<br /> }<br /> return filtered;<br />};</pre><br />Now, I think that if you look at these two chunks of code, it is easy to see that even though they are about the same length, one is much harder to write. The reason, why tests take so little time to write is that they are linear in nature. No loops, ifs or interdependencies with other tests. Production code is a different story, I have to create complex ifs, loops and have to make sure that the implementation works not just for one test, but all test. This is why it takes you so much longer to write production than test code. In this particular case, I remember rewriting this function three times, before I got it to work as expected. :-)<br /><br />So a naive answer is that writing test carries a 10% tax. But, we pay taxes in order to get something in return. Here is what I get for 10% which pays me back:<br /><ul><br /> <li>When I implement a feature I don't have to start up the whole application and click several pages until I get to page to verify that a feature works. In this case it means that I don't have to refreshing the browser, waiting for it to load a dataset and then typing some test data and manually asserting that I got what I expected. This is immediate payback in time saved!</li><br /> <li>Regression is almost nil.  Whenever you are adding new feature you are running the risk of breaking something other then what you are working on immediately (since you are not working on it you are not actively testing it). At least once a day I have a what the @#$% moment when a change suddenly breaks a test at the opposite end of the codebase which I did not expect, and I count my lucky stars. This is worth a lot of time spent when you discover that a feature you thought was working no longer is, and by this time you have forgotten how the feature is implemented.</li><br /> <li>Cognitive load is greatly reduced since I don't have to keep all of the assumptions about the software in my head, this makes it really easy to switch tasks or to come back to a task after a meeting, good night sleep or a weekend.</li><br /> <li>I can refactor the code at will, keeping it from becoming stagnant, and hard to understand. This is a huge problem on large projects, where the code works, but it is really ugly and everyone is afraid to touch it. This is worth money tomorrow to keep you going.</li><br /></ul><br />These benefits translate to real value today as well as tomorrow. I write tests, because the additional benefits I get more than offset the additional cost of 10%.  Even if I don't include the long term benefits, the value I get from test today are well worth it. I am faster in developing code with test. How much, well that depends on the complexity of the code. The more complex the thing you are trying to build is (more ifs/loops/dependencies) the greater the benefit of tests are.<br /><br />So now you understand my puzzled look when people ask me how much slower/costlier the development with tests is.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-1974718471053623145?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/cost-of-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Checked exceptions I love you, but you have to go</title>
		<link>https://googledata.org/google-testing/checked-exceptions-i-love-you-but-you-have-to-go/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=checked-exceptions-i-love-you-but-you-have-to-go</link>
		<comments>https://googledata.org/google-testing/checked-exceptions-i-love-you-but-you-have-to-go/#comments</comments>
		<pubDate>Wed, 16 Sep 2009 18:01:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[By Miško HeveryOnce upon a time Java created an experiment called checked-exceptions, you know, you have to declare exceptions or catch them. Since that time, no other language (I know of) has decided to copy this idea, but somehow the Java developers...]]></description>
				<content:encoded><![CDATA[<div>By <a href="http://misko.hevery.com">Miško Hevery</a></div><div><br /></div>Once upon a time Java created an experiment called checked-exceptions, you know, you have to declare exceptions or catch them. Since that time, no other language (I know of) has decided to copy this idea, but somehow the Java developers are in love with checked exceptions. Here, I am going to "try" to convince you that checked-exceptions, even though look like a good idea at first glance, are actually not a good idea at all:<br /><br /><strong>Empirical Evidence</strong><br /><br />Let's start with an observation of your code base. Look through your code and tell me what percentage of catch blocks do rethrow or print error? My guess is that it is in high 90s. I would go as far as 98% of catch blocks are meaningless, since they just print an error or rethrow the exception which will later be printed as an error. The reason for this is very simple. Most exceptions such as FileNotFoundException, IOException, and so on are sign that we as developers have missed a corner case. The exceptions are used as away of informing us that we, as developers, have messed up. So if we did not have checked exceptions, the exception would be throw and the main method would print it and we would be done with it (optionally we would catch all exceptions in the main log them if we are a server).<br /><br />Checked exceptions force me to write catch blocks which are meaningless: more code, harder to read, and higher chance that I will mess up the rethrow logic and eat the exception.<br /><br /><strong>Lost in Noise</strong><br /><br />Now lets look at the 2-5% of the catch blocks which are not rethrow and real interesting logic happens there. Those interesting bits of useful and important information is lost in the noise, since my eye has been trained to skim over the catch blocks. I would much rather have code where a catch would indicate: "pay, attention! here, something interesting is happening!", rather than, "it is just a rethrow." Now, if we did not have checked exceptions, you would write your code without catch blocks, test your code (you do test right?) and realize that under some circumstances an exception is throw and deal with it by writing the catch block. In such a case forgetting to write a catch block is no different than forgetting to write an else block of the if statement. We don't have checked ifs and yet no one misses them, so why do we need to tell developers that FileNotFound can happen. What if the developer knows for a fact that it can not happen since he has just placed the file there, and so such an exception would mean that your filesystem has just disappeared! (and your application is not place to handle that.)<br /><br />Checked exception make me skim the catch blocks as most are just rethrows, making it likely that you will miss something important.<br /><br /><strong>Unreachable Code</strong><br /><br />I love to write tests first and implement as a consequence of tests. In such a situation you should always have 100% coverage since you are only writing what the tests are asking for. But you don't! It is less than 100% because checked exceptions force you to write catch blocks which are impossible to execute. Check this code out:<br /><pre>bytesToString(byte[] bytes) {<br /> ByteArrayOutputStream out = new ByteArrayOutputStream();<br /> try {<br />   out.write(bytes);<br />   out.close()<br />   return out.toSring();<br /> } catch (IOException e) {<br />   // This can never happen!<br />   // Should I rethrow? Eat it? Print Error?<br /> }<br />}</pre><br />ByteArrayOutputStream will never throw IOException! You can look through its implementation and see that it is true! So why are you making me catch a phantom exception which can never happen and which I can not write a test for? As a result I cannot claim 100% coverage because of things outside my control.<br /><br />Checked exceptions create dead code which will never  execute.<br /><br /><strong>Closures Don't Like You</strong><br /><br />Java does not have closures but it has visitor pattern. Let me explain with concrete example. I was creating a custom class loader and need to override load() method on MyClassLoader which throws ClassNotFoundException under some circumstances. I use ASM library which allows me to inspect Java bytecodes. The way ASM works is that it is a visitor pattern, I write visitors and as ASM parses the bytecodes it calls specific methods on my visitor implementation. One of my visitors, as it is examining bytecodes, decides that things are not right and needs to throw a ClassNotFondException which the class loader contract says it should throw. But now we have a problem. What we have on a stack is MyClassLoader -&gt; ASMLibrary -&gt; MyVisitor. MyVisitor wants to throw an exception which MyClassLoader expects but it can not since ClassNotFoundException is checked and ASMLibrary does not declare it (nor should it). So I have to throw RuntimeClassNotFoundException from MyVisitor which can pass through ASMLibrary which MyClassLoader can then catch and rethrow as ClassNotFoundException.<br /><br />Checked exception get in the way of functional programing.<br /><br /><strong>Lost Fidelity</strong><br /><br />Suppose java.sql package would be implemented with useful exception such as SqlDuplicateKeyExceptions and SqlForeignKeyViolationException and so on (we can wish) and suppose these exceptions are checked (which they are). We say that the SQL package has high fidelity of exception since each exception is to a very specific problem. Now lets say we have the same set up as before where there is some other layer between us and the SQL package, that layer can either redeclare all of the exceptions, or more likely throw its own. Let's look at an example, Hibernate is object-relational-database-mapper, which means it converts your SQL rows into java objects. So on the stack you have MyApplication -&gt; Hibernate -&gt; SQL. Here Hibernate is trying hard to hide the fact that you are talking to SQL so it throws HibernateExceptions instead of SQLExceptions. And here lies the problem. Your code knows that there is SQL under Hibernate and so it could have handled SqlDuplicateKeyException in some useful way, such as showing an error to the user, but Hibernate was forced to catch the exception and rethrow it as generic HibernateException. We have gone from high fidelitySqlDuplicateKeyException to low fidelity HibernateException. An so MyApplication can not do anything. Now Hibernate could have throw HibernateDuplicateKeyException but that means that Hibernate now has the same exception hierarchy as SQL and we are duplicating effort and repeating ourselves.<br /><br />Rethrowing checked exceptions causes you to lose fidelity and hence makes it less likely that you could do something useful with the exception later on.<br /><br /><strong>You can't do Anything Anyway</strong><br /><br />In most cases when exception is throw there is no recovery. We show a generic error to the user and log an exception so that we con file a bug and make sure that that exception will not happen again. Since 90+% of the exception are bugs in our code and all we do is log, why are we forced to rethrow it over and over again.<br /><br />It is rare that anything useful can be done when checked exception happens, in most case we die with error! Therefor I want that to be the default behavior of my code with no additional typing.<br /><br /><strong>How I deal with the code</strong><br /><br />Here is my strategy to deal with checked exceptions in java:<br /><ul><br /> <li>Always catch all checked exceptions at source and rethrow them as LogRuntimeException.<br /><ul><br /> <li>LogRuntimeException is my runtime un-checked exception which says I don't care just log it.</li><br /> <li>Here I have lost Exception fidelity.</li><br /></ul><br /></li><br /> <li>All of my methods do not declare any exceptions</li><br /> <li>As I discover that I need to deal with a specific exception I go back to the source where LogRuntimeException was thrown and I change it to &lt;Specific&gt;RuntimeException (This is rarer than you think)<br /><ul><br /> <li>I am restoring the exception fidelity only where needed.</li><br /></ul><br /></li><br /> <li>Net effect is that when you come across a try-catch clause you better pay attention as interesting things are happening there.<br /><ul><br /> <li>Very few try-catch calluses, code is much easier to read.</li><br /> <li>Very close to 100% test coverage as there is no dead code in my catch blocks.</li><br /></ul><br /></li><br /></ul><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4509944480391294720?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/checked-exceptions-i-love-you-but-you-have-to-go/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>It is not about writing tests, its about writing stories</title>
		<link>https://googledata.org/google-testing/it-is-not-about-writing-tests-its-about-writing-stories/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=it-is-not-about-writing-tests-its-about-writing-stories</link>
		<comments>https://googledata.org/google-testing/it-is-not-about-writing-tests-its-about-writing-stories/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 15:52:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryI would like to make an analogy between building software and building a car. I know it is imperfect one, as one is about design and the other is about manufacturing, but indulge me, the lessons are very similar.A piece of software is l...]]></description>
				<content:encoded><![CDATA[<div>by <a href="http://misko.hevery.com">Miško Hevery</a></div><div><br /></div>I would like to make an analogy between building software and building a car. I know it is imperfect one, as one is about design and the other is about manufacturing, but indulge me, the lessons are very similar.<br /><br />A piece of software is like a car. Lets say you would like to test a car, which you are in the process of designing, would you test is by driving it around and making modifications to it, or would you prove your design by testing each component separately? I think that testing all of the corner cases by driving the car around is very difficult, yes if the car drives you know that a lot of things must work (engine, transmission, electronics, etc), but if it does not work you have no idea where to look. However, there are some things which you will have very hard time reproducing in this end-to-end test. For example, it will be very hard for you to see if the car will be able to start in the extreme cold of the north pole, or if the engine will not overheat going full throttle up a sand dune in Sahara. I propose we take the engine out and simulate the load on it in a laboratory.<br /><br />We call driving car around an end-to-end test and testing the engine in isolation a unit-test. With unit tests it is much easier to simulate failures and corner cases in a much more controlled environment. We need both tests, but I feel that most developers can only imagine the end-to-end tests.<br /><br />But lets see how we could use the tests to design a transmission. But first, little terminology change, lets not call them test, but instead call them stories. They are stories because that is what they tell you about your design. My first story is that:<br /><ul><br /> <li>the transmission should allow the output shaft to be locked, move in same direction (D) as the input shaft, move in opposite (R) or move independently (N)</li><br /></ul><br />Given such a story I could easily create a test which would prove that the above story is true for any design submitted to me. What I would most likely get is a transmission which would only have a single gear in each direction. So lets write another story<br /><ul><br /> <li>the transmission should allow the ratio between input and output shaft to be [-1, 0, 1, 2, 3, 4]</li><br /></ul><br />Again I can write a test for such a transmission but i have not specified how the forward gear should be chosen, so such a transmission would most likely be permanently stuck in 1st gear and limit my speed, it will also over-rev the engine.<br /><ul><br /> <li>the transmission should start in 1st and than switch to higher gear before the engine reaches maximum revolutions.</li><br /></ul><br />This is better, but my transmission would most likely rev the engine to maximum before it would switch, and once it would switch to higher gear and I would slow down, it would not down-shift.<br /><ul><br /> <li>the transmission should down shift whenever the engine RPM fall bellow 1000 RPMs</li><br /></ul><br />OK, now it is starting to drive like a car, but still the limits for shifting really are 1000-6000 RPMs which is not very fuel efficient way to drive your car.<br /><ul><br /> <li>the transmission should up-shift whenever the estimated fuel consumption at a higher gear ration is better than the current one.</li><br /></ul><br />So now our engine will not rev any more but it will be a lazy car since once the transmission is in the fuel efficient mode it will not want to down-shift<br /><ul><br /> <li>the transmission should down-shift whenever the gas pedal is depressed more than 50% and the RPM is lower than the engine's peak output RPM.</li><br /></ul><br />I am not a transmission designer, but I think this is a decent start.<br /><br />Notice how I focused on the end result of the transmission rather than on testing specific internals of it. The transmission designer would have a lot of levy in choosing how it worked internally, Once we would have something and we would test it in the real world we could augment these list of stories with additional stories as we discovered additional properties which we would like the transmission to posses.<br /><br />If we would decide to change the internal design of the transmission for whatever reason we would have these stories as guides to make sure that we did not forget about anything. The stories represent assumptions which need to be true at all times. Over the lifetime of the component we can collect hundreds of stories which represent equal number of assumption which is built into the system.<br /><br />Now imagine that a new designer comes on board and makes a design change which he believes will improve the responsiveness of the transmission, he can do so because the existing stories are not restrictive in how, only it what the outcome should be. The stories save the designer from breaking an existing assumption which was already designed into the transmission.<br /><br />Now lets contrast this with how we would test the transmission if it would already be build.<br /><ul><br /> <li>test to make sure all of the gears work</li><br /> <li>test to make sure that the engine is not allowed to over-rev</li><br /></ul><br />It is hard now to think about what other tests to write, since we are not using the tests to drive the design. Now, lets say that someone now insist that we get 100% coverage, we open the transmission up and we see all kinds of logic, and rules and we don't know why since we were not part of the design so we write a test<br /><ul><br /> <li>at 3000 RPM input shaft, apply 100% throttle and assert that the transmission goes to 2nd gear.</li><br /></ul><br />Tests like that are not very useful when you want to change the design, since you are likely to break the test, without fully understanding why the test was testing that specific conditions, it is hard to know if anything was broken if the tests is red.. That is because the tests does not tell a story any more, it only asserts the current design. It is likely that such a test will be in the way when you will try to do design changes. The point I am trying to make is that there is huge difference between writing tests before or after. When we write tests before we are:<br /><ul><br /> <li>creating a story which is forcing a particular design decision.</li><br /> <li>tests are a collection of assumptions which needs to be true at all times.</li><br /></ul><br />when we write tests after the fact we:<br /><ul><br /> <li>miss a lot of reasons why things are done in particular way even if we have 100% coverage</li><br /> <li>test are often brittle because they are tied to particulars of the current implementation</li><br /> <li>tests are just snapshots and don't tell a story of why the component does something, only that it does.</li><br /></ul><br />For this reason there are huge differences in quality when writing assumptions as stories before (which force design to emerge) or writing tests after which take a snapshot of a given design.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-3776965704329854742?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/it-is-not-about-writing-tests-its-about-writing-stories/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Super Fast JS Testing</title>
		<link>https://googledata.org/google-testing/super-fast-js-testing/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=super-fast-js-testing</link>
		<comments>https://googledata.org/google-testing/super-fast-js-testing/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 18:20:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Shyam SeshadriBefore I jump into how exactly you can perform super fast and easy JS testing, let me give you some background on the problem.Javascript is a finicky language (Some people even hesitate to call it a language). And it can easily grow an...]]></description>
				<content:encoded><![CDATA[<div><br /><br />by <a href="http://theshyam.com/">Shyam Seshadri</a><br /><br />Before I jump into how exactly you can perform super fast and easy JS testing, let me give you some background on the problem.<br /><br />Javascript is a finicky language (Some people even hesitate to call it a language). And it can easily grow and become a horrible and complicated beast, incapable of being tamed once let loose. And testing it is a nightmare. Once you have decided on a framework (of which there are a dime a dozen), you then have to set it up to run just right. You need to set it up to actually run your tests. Then you have to figure out how to run it in a continuous integration environment. Maybe even run it in headless mode. And everyone solves it in their own ways.<br /><br />But the biggest problem I have with most of these frameworks is that executing the tests usually requires a context switch. By that, I mean to run a JSUnit test, you end up usually having to open the browser, browse to a particular url or html page which then runs the test. Then you have to look at the results there, and then come back to your editor to either proceed further or fix your tests. Works, but really slows down development.<br /><br />In java, all it takes is to click the run button in your IDE to run your tests. You get instant feedback, a green / red bar and details on which tests passed and failed and at what line. No context switch, you can get it to run at every save, and proceed on your merry way. Till now, this was not possible with Javascript.<br /><br />But now, we have <a onclick="javascript:pageTracker._trackPageview('/outbound/article/code.google.com');" href="http://code.google.com/p/js-test-driver/" >JS Test Driver</a>. My colleagues Jeremie and <a onclick="javascript:pageTracker._trackPageview('/outbound/article/misko.hevery.com');" href="http://misko.hevery.com" >Misko</a> ended up running into some of the issues I outlined above, and decided that going along with the flow was simply unacceptable. So they created a JS Testing framework which solves these very things. You can capture any browser on any machine, and when you tell it to run tests, it will go ahead and execute them on all these browsers and return you the results in your client. And its blazing fast. I am talking milliseconds to run 100 odd tests. And you can tell it to rerun your tests at each save. All within the comforts of your IDE. And over the last three weeks, I have been working on the eclipse plugin for JS Test Driver, and its now at the point where its in a decent working condition.<br /><div id="attachment_165" style="width: 438px;"><a href="http://theshyam.com/wp-content/uploads/2009/08/JS-Test-Driver-Plugin.png"><img title="JS Test Driver Plugin" src="http://theshyam.com/wp-content/uploads/2009/08/JS-Test-Driver-Plugin.png" alt="The plugin in action" width="428" height="478" /></a>The plugin in action</div><br />The plugin allows you to, from within Eclipse, start the JS Test Driver server, capture some browsers, and then run your tests. You get pretty icons telling you what browsers were captured, the state of the server, the state of the tests. It allows you to filter and show only failures, rerun your last launch configuration, even setup the paths to your browsers so you can launch it all from the safety of eclipse. And as you can see, its super fast. <strong><em>Some 100 odd tests in less than 10 ms</em></strong>. If thats not fast, I don’t know what is.<br /><br />For more details on JS Test Driver, visit its <a onclick="javascript:pageTracker._trackPageview('/outbound/article/code.google.com');" href="http://code.google.com/p/js-test-driver/" >Google Code</a> website and see how you can use it in your next project and even integrate it into a continuous integration. Misko talks a little bit more about the motivations behind writing it on his <a onclick="javascript:pageTracker._trackPageview('/outbound/article/misko.hevery.com');" href="http://misko.hevery.com/2009/05/22/yet-another-javascript-testing-framework/" >Yet Another JS Testing Framework</a> post. To try out the plugin for yourselves, go add the following update site to eclipse:<br /><br /><strong>http://js-test-driver.googlecode.com/svn/update/</strong><br /><br /><strong> </strong>For all you IntelliJ fanatics, there is something similar in the works.</div><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4811369746547225829?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/super-fast-js-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to think about OO</title>
		<link>https://googledata.org/google-testing/how-to-think-about-oo/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-think-about-oo</link>
		<comments>https://googledata.org/google-testing/how-to-think-about-oo/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 18:58:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryEveryone seems to think that they are writing OO after all they are using OO languages such as Java, Python or Ruby. But if you exam the code it is often procedural in nature.Static MethodsStatic methods are procedural in nature and the...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />Everyone seems to think that they are writing OO after all they are using OO languages such as Java, Python or Ruby. But if you exam the code it is often procedural in nature.<br /><br /><strong>Static Methods</strong><br /><br />Static methods are procedural in nature and they have no place in OO world. I can already hear the screams, so let me explain why, but first we need to agree that <a href="http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/">global variables and state is evil</a>. If you agree with previous statement than for a static method to do something interesting it needs to have some arguments, otherwise it will always return a constant. Call to a staticMethod() must always return the same thing, if there is no global state. (Time and random, has global state, so that does not count and object instantiation may have different instance but the object graph will be wired the same way.)<br /><br />This means that for a static method to do something interesting it needs to have arguments. But in that case I will argue that the method simply belongs on one of its arguments. Example: Math.abs(-3) should really be -3.abs(). Now that does not imply that -3 needs to be object, only that the compiler needs to do the magic on my behalf, which BTW, Ruby got right. If you have multiple arguments you should choose the argument with which method interacts the most.<br /><br />But most justifications for static methods argue that they are "utility methods". Let's say that you want to have toCamelCase() method to convert string "my_workspace" to "myWorkspace". Most developers will solve this as StringUtil.toCamelCase("my_workspace"). But, again, I am going to argue that the method simply belongs to the String class and should be "my_workspace".toCamelCase(). But we can't extend the String class in Java, so we are stuck, but in many other OO languages you can add methods to existing classes.<br /><br />In the end I am sometimes (handful of times per year) forced to write static methods <strong>due to limitation of the language</strong>. But that is a rare event since <a href="http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/">static methods are death to testability</a>. What I do find, is that in most projects static methods are rampant.<br /><br /><strong>Instance Methods</strong><br /><br />So you got rid of all of your static methods but your codes still is procedural. OO says that code and data live together. So when one looks at code one can judge how OO it is without understanding what the code does, simply by looking at the relationship of data and code.<br /><pre>class Database {<br /> // some fields declared here<br /> boolean isDirty(Cache cache, Object obj) {<br />   for (Object cachedObj : cache.getObjects) {<br />     if (cachedObj.equals(obj))<br />       return false;<br />   }<br />   return true;<br /> }<br />}</pre><br />The problem here is the method may as well be static! It is in the wrong place, and you can tell this because it does not interact with any of the data in the Database, instead it interacts with the data in cache which it fetches by calling the getObjects() method. My guess is that this method belongs to one of its arguments most likely Cache. If you move it to Cache you well notice that the Cache will no longer need the getObjects() method since the for loop can access the internal state of the Cache directly. Hey, we simplified the code (moved one method, deleted one method) and we have made <a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">Demeter happy</a>.<br /><br />The funny thing about the getter methods is that it usually means that the code where the data is processed is outside of the class which has the data. In other words the code and data are not together.<br /><pre>class Authenticator {<br /> Ldap ldap;<br /> Cookie login(User user) {<br />   if (user.isSuperUser()) {<br />     if ( ldap.auth(user.getUser(),<br />            user.getPassword()) )<br />       return new Cookie(user.getActingAsUser());<br />   } else (user.isAgent) {<br />       return new Cookie(user.getActingAsUser());<br />   } else {<br />     if ( ldap.auth(user.getUser(),<br />            user.getPassword()) )<br />       return new Cookie(user.getUser());<br />   }<br />   return null;<br /> }<br />}</pre><br />Now I don't know if this code is well written or not, but I do know that the login() method has a very high affinity to user. It interacts with the user a lot more than it interacts with its own state. Except it does not interact with user, it uses it as a dumb storage for data. Again, code lives with data is being violated. I believe that the method should be on the object with which it interacts the most, in this case on User. So lets have a look:<br /><pre>class User {<br /> String user;<br /> String password;<br /> boolean isAgent;<br /> boolean isSuperUser;<br /> String actingAsUser;<br /><br /> Cookie login(Ldap ldap) {<br />   if (isSuperUser) {<br />     if ( ldap.auth(user, password) )<br />       return new Cookie(actingAsUser);<br />   } else (user.isAgent) {<br />       return new Cookie(actingAsUser);<br />   } else {<br />     if ( ldap.auth(user, password) )<br />       return new Cookie(user);<br />   }<br />   return null;<br /> }<br />}</pre><br />Ok we are making progress, notice how the need for all of the getters has disappeared, (and in this simplified example the need for the Authenticator class disappears) but there is still something wrong. The ifs branch on internal state of the object. My guess is that this code-base is riddled with if (user.isSuperUser()). The issue is that if you add a new flag you have to remember to change all of the ifs which are dispersed all over the code-base. Whenever I see If or switch on a flag I can almost always know that polymorphism is in order.<br /><pre>class User {<br /> String user;<br /> String password;<br /><br /> Cookie login(Ldap ldap) {<br />   if ( ldap.auth(user, password) )<br />     return new Cookie(user);<br />   return null;<br /> }<br />}<br /><br />class SuperUser extends User {<br /> String actingAsUser;<br /><br /> Cookie login(Ldap ldap) {<br />   if ( ldap.auth(user, password) )<br />     return new Cookie(actingAsUser);<br />   return null;<br /> }<br />}<br /><br />class AgentUser extends User {<br /> String actingAsUser;<br /><br /> Cookie login(Ldap ldap) {<br />   return new Cookie(actingAsUser);<br /> }<br />}</pre><br />Now that we took advantage of polymorphism, each different kind of user knows how to log in and we can easily add new kind of user type to the system. Also notice how the user no longer has all of the flag fields which were controlling the ifs to give the user different behavior. The <a href="http://misko.hevery.com/2008/08/14/procedural-language-eliminated-gotos-oo-eliminated-ifs/">ifs and flags have disappeared</a>.<br /><br />Now this begs the question: should the User know about the Ldap? There are actually two questions in there. 1) should User have a field reference to Ldap? and 2) should User have compile time dependency on Ldap?<br /><br />Should User have a field reference to Ldap? The answer is no, because you may want to serialize the user to database but you don't want to serialize the Ldap. See <a href="http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/">here</a>.<br /><br />Should User have compile time dependency on Ldap? This is more complicated, but in general the answer depends on weather or not you are planning on reusing the User on a different project, since compile time dependencies are transitive in strongly typed languages. My experience is that everyone always writes code that one day they will reuse it, but that day never comes, and when it does, usually the code is entangled in other ways anyway, so code reuse after the fact just does not happen. (developing a library is different since code reuse is an explicit goal.) My point is that a lot of people pay the price of "what if" but never get any benefit out of it. Therefore don't worry abut it and make the User depend on Ldap.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4127025554572568925?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/how-to-think-about-oo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Advantages of Unit Testing Early</title>
		<link>https://googledata.org/google-testing/the-advantages-of-unit-testing-early/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-advantages-of-unit-testing-early</link>
		<comments>https://googledata.org/google-testing/the-advantages-of-unit-testing-early/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 03:33:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Shyam SeshadriNowadays, when I talk with (read: rant at) anyone about why they should do test driven development or write unit tests, my spiel has gotten extremely similar and redundant to the point that I don't have to think about it anymore. But e...]]></description>
				<content:encoded><![CDATA[by <a href="http://theshyam.com/">Shyam Seshadri</a><br /><br />Nowadays, when I talk with (read: rant at) anyone about why they should do test driven development or write unit tests, my spiel has gotten extremely similar and redundant to the point that I don't have to think about it anymore. But even when I do pairing with skeptics, even as I cajole and coax testable code or some specific refactorings out of them, I wonder, why is it that I have to convince you of the worth of testing ? Shouldn't it be obvious ?<br /><br />And sadly, it isn't. Not to many people. To many people, I come advocating the rise of the devil itself. To others, it is this redundant, totally useless thing that is covered by the manual testers anyway. The general opinion seems to be, "I'm a software engineer. It is my job to write software. Nowhere in the job description does it say that I have to write these unit tests." Well, to be fair, I haven't heard that too many times, but they might as well be thinking it, given their investment in writing unit tests. And last time I checked, an engineer's role is to deliver a working software. How do you even prove that your software works without having some unit tests to back you up ? Do you pull it up and go through it step by step, and start cursing when it breaks ? Because without unit tests, the odds are that it will.<br /><br />But writing unit tests as you develop isn't just to prove that your code works (though that is a great portion of it). There are so many more benefits to writing unit tests. Lets talk in depth about a few of these below.<br /><br /><b>Instantaneous Gratification</b><br /><br />The biggest and most obvious reason for writing unit tests (either as you go along, or before you even write code) is instantaneous gratification. When I write code (write, not spike. That is a whole different ball game that I won't get into now), I love to know that it works and does what it should do. If you are writing a smaller component of a bigger app (especially one that isn't complete yet), how are you even supposed to know if what you just painstakingly wrote even works or not ? Even the best engineers make mistakes.<br /><br />Whereas with unit tests, I can write my code. Then just hit my shortcut keys to run my tests, and voila, within a second or two, I have the results, telling me that everything passed (in the ideal case) or what failed and at which line, so I know exactly what I need to work on. It just gives you a safety net to fall back on, so you don't have to remember all the ways it is supposed to work in. Something tells you if it is or not.<br /><br />Also, doing Test Driven Development when developing is one of the best ways to keep track of what you are working on. I have times when I am churning out code and tests, one after the other, before I need to take a break. The concept of TDD is that I write a failing test, and then I write just enough code to pass that test. So when I take a break, I make it a point to leave at a failing test, so that when I come back, I can jump right back into writing the code to get it to pass. I don't have to spend 15 - 20 minutes reading through the code to figure out where I left off. My asserts usually tell me exactly what I need to do.<br /><br /><b>Imposing Modularity / Reusability</b><br /><br />The very first rule of reusable code is that you have to be able to instantiate an instance of the class before you can use it. And guess what ? With unit tests, you almost always have to instantiate an instance of the class under test. Therefore, writing a unit test is always a first great step in making code reusable. And the minute you start writing unit tests, most likely, you will start running into the common pain points of not having injectable dependencies (Unless of course, you are one of the converts, in which case, good for you!).<br /><br />Which brings me to the next point. Once you start having to jump through fiery hoops to set up your class just right to test it, you will start to realize when a class is getting bloated, or when a certain component belongs in its own class. For instance, why test the House when what you really want to test is the Kitchen it contains. So if the Kitchen class was initially part of the House, when you start writing unit tests, it becomes obvious enough that it belongs separately. Before long, you have modular classes which are small and self contained and can be tested independently without effort. And it definitely helps keep the code base cleaner and more comprehensible.<br /><br /><b>Refactoring Safety Net</b><br /><br />Any project, no matter what you do, usually ends up at a juncture where the requirements change on you. And you are left with the option of refactoring your codebase to add / change it, or rewrite from scratch. One, never rewrite from scratch, always refactor. Its always faster when you refactor, no matter what you may think. Two, what do you do when you have to refactor and you don't have unit tests ? How do you know you haven't horribly broken something in that refactor ? Granted, IDE's such as Eclipse and IntelliJ have made refactoring much more convenient, but adding new functionality or editing existing features is never simple.<br /><br />More often than not, we end up changing some undocumented way the existing code behaved, and blow up 10 different things (it takes skill to blow up more, believe me, I have tried). And its often something as simple as changing the way a variable is set or unset. In those cases, having unittests (remember those things you were supposed to have written?) to confirm that your refactoring broke nothing is godsend. I can't tell you the amount of times I have had to refactor a legacy code base without this safety net. The only way to ensure I did it correct was to write these large integration tests (because again, no unit tests usually tends to increase the coupling and reduce modularity, even in the most well designed code bases) which verified things at a higher level and pray fervently that I broke nothing. Then I would spend a few minutes bringing up the app everytime, and clicking on random things to make sure nothing blew up. A complete waste of my time when I could have known the same thing by just running my unit tests.<br /><br /><b>Documentation</b><br /><br />Finally, one of my favorite advantages to doing TDD or writing unit tests as I code. I have a short memory for code I have written. I could look back at the code I wrote two days ago, and have no clue what I was thinking. In those cases, all I have to do is go look at the test for a particular method, and that almost always will tell me what that method takes in as parameters, and what all it should be doing. A well constructed set of tests tell you about valid and invalid inputs, state that it should modify and output that it may return.<br /><br />Now this is useful for people like me with short memory spans. But it is also useful, say, when you have a new person joining the team. We had this cushion the last time someone joined our team for a short period of time, and when we asked him to add a particular check to a method, we just pointed him to the tests for that method, which basically told him what the method does. He was able to understand the requirements, and go ahead and add the check with minimal handholding. And the tests give a safety net so he doesn't break anything else while he was at it.<br /><br />Also useful is the fact that later, when someone comes marching through your door, demanding you fix this bug, you can always make sure whether it was a a bug (in which case, you are obviously missing a test case) or if it was a feature that they have now changed the requirements on (in which case you already have a test which proves it was your intent to do it, and thus not a bug).<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-8596966213546342619?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/the-advantages-of-unit-testing-early/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Software Testing Categorization</title>
		<link>https://googledata.org/google-testing/software-testing-categorization/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=software-testing-categorization</link>
		<comments>https://googledata.org/google-testing/software-testing-categorization/#comments</comments>
		<pubDate>Tue, 14 Jul 2009 19:29:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryYou hear people talking about small/medium/large/unit/integration/functional/scenario tests but do most of us really know what is meant by that? Here is how I think about tests.Unit/SmallLets start with unit test. The best definition I ...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško</a><a href="http://misko.hevery.com/about/"> </a><a href="http://misko.hevery.com/about/">Hevery</a><br /><br /><br />You hear people talking about small/medium/large/unit/integration/functional/scenario tests but do most of us really know what is meant by that? Here is how I think about tests.<br /><br /><strong>Unit/Small</strong><br /><br />Lets start with unit test. The best definition I can find is that it is a test which runs super-fast (under 1 ms) and when it fails you don't need debugger to figure out what is wrong. Now this has some <span style="font-size:+0;"><span id="SPELLING_ERROR_2">implications. Under 1 ms means that your test cannot do any I/O. The reason this is important is that you want to run ALL (thousands) of your unit-tests every time you modify anything, <a href="http://misko.hevery.com/2009/05/07/configure-your-ide-to-run-your-tests-automatically/">preferably on each save</a>. My patience is two seconds max. In two seconds I want to make sure that all of my unit tests ran and nothing broke. This is a great world to be in, since if tests go red you just hit Ctrl-Z few times to undo what you have done and try again. The immediate feedback is addictive. Not needing a debugger implies that the test is localized (hence the word unit, as in single class).</span></span><br /><br />The purpose of the unit-test is to check the conditional logic in your code, your 'ifs' and 'loops'. This is where the majority of your bugs come from (see <a href="http://misko.hevery.com/2008/11/17/unified-theory-of-bugs/">theory of bugs</a>). Which is why if you do no other testing, unit tests are the best bang for your buck! Unit tests, also make sure that you have testable code. If you have unit-testable code than all other testing levels will be testable as well.<br /><br />A <a href="http://code.google.com/p/testability-explorer/source/browse/trunk/core/src/test/java/com/google/test/metric/collection/KeyedMultiStackTest.java">KeyedMultiStackTest.java</a> is what I would consider great unit test example from <a href="http://code.google.com/p/testability-explorer">Testability Explorer</a>. Notice how each test tells a story. It is not testMethodA, testMethodB, etc, rather each test is a scenario. Notice how at the beginning the test are normal operations you would expect but as you get to the bottom of the file the test become little stranger. It is because those are weird corner cases which I have discovered later. Now the funny thing about <a href="http://code.google.com/p/testability-explorer/source/browse/trunk/core/src/main/java/com/google/test/metric/collection/KeyedMultiStack.java">KeyedMultiStack.java</a> is that I had to rewrite this class three times. Since I could not get it to work under all of the test cases. One of the test was always failing, until I realized that my algorithm was <span style="font-size:+0;"><span id="SPELLING_ERROR_8">fundamentally flawed. By this time I had most of the project working and this is a key class for byte-code analysis process. How would you feel about ripping out something so fundamental out of your system and rewriting it from scratch? It took me two days to rewrite it until all of my test passed again. After the rewrite the overall application still worked. This is where you have an AHa! moment, when you realize just how amazing unit-tests are.</span></span><br /><br />Does each class need a unit test? A qualified no. Many classes get tested indirectly when testing something else. Usually simple value objects do not have tests of their own. But don't confuse not having tests and not having test coverage. All classes/methods should have test coverage. If you TDD, than this is automatic.<br /><br /><strong>Medium/Functional</strong><br /><br />So you proved that each class works <span style="font-size:+0;"><span id="SPELLING_ERROR_10">individually, but how do you know that they work together? For this we need to wire related classes together just as they would be in production and exercise some basic execution paths through it. The question here we are trying to answer is not if the 'ifs' and 'loops' work, (we have already answered that,) but whether the interfaces between classes abide by their contracts. Great example of functional test is <a href="http://code.google.com/p/testability-explorer/source/browse/trunk/core/src/test/java/com/google/test/metric/MetricComputerTest.java">MetricComputerTest.java</a>. Notice how the input of each test is an inner class in the test file and the output is ClassCost.java. To get the output <span style="font-size:+0;">several</span> classes have to collaborate together to: parse byte-codes, analyze code paths, and compute costs until the final cost numbers are asserted.</span></span><br /><br />Many of the classes are tested twice. Once directly throughout unit-test as described above, and once indirectly through the functional-tests. If you would remove the unit tests I would still have high confidence that the functional tests would catch most changes which would break things, but I would have no idea where to go to look for a fix, since the mistake can be in any class involved in the execution path. The no debugger needed rule is broken here. When a functional test fails, (and there are no unit tests failing) I am forced to take out my debugger. When I find the problem, I add a unit test <span style="font-size:+0;"><span id="SPELLING_ERROR_13">retroactively to my unit test to 1) prove to myself that I understand the bug and 2) prevent this bug from happening again. The retroactive unit test is the reason why the unit tests at the end of <a href="http://code.google.com/p/testability-explorer/source/browse/trunk/core/src/test/java/com/google/test/metric/collection/KeyedMultiStackTest.java">KeyedMultiStackTest.java</a> file are "strange" for a lack of a better world. They are things which I did not think of when i wrote the unit-test, but discovered when I wrote functional tests, and through lot of hours behind debugger track down to <a href="http://code.google.com/p/testability-explorer/source/browse/trunk/core/src/main/java/com/google/test/metric/collection/KeyedMultiStack.java">KeyedMultiStack.java</a> class as the culprit.</span></span><br /><br />Now computing metrics is just a small part of what testability explorer does, (it also does reports, and suggestions) but those are not tested in this functional test (there are other functional tests for that). You can think of functional-tests as a set of related classes which form a cohesive functional unit for the overall application. Here are some of the functional areas in testability explorer: java byte-code parsing, java source parsing, c++ parsing, cost analysis, 3 different kinds of reports, and suggestion engine. All of these have unique set of related classes which work together and need to be tested together, but for the most part are independent.<br /><br /><strong>Large/End-to-End/Scenario</strong><br /><br />We have proved that: 'ifs' and 'loops' work; and that the contracts are compatible, what else can we test? There is still one class of mistake we can make. You can wire the whole thing wrong. For example, passing in null instead of report, not configuring the location of the jar file for parsing, and so on. These are not logical bugs, but wiring bugs. Luckily, wiring bugs have this nice property that they fail consistently and usually spectacularly with an exception. Here is an example of end-to-end test: <a href="http://code.google.com/p/testability-explorer/source/browse/trunk/core/src/test/java/com/google/test/metric/TestabilityRunnerTest.java">TestabilityRunnerTest.java</a>. Notice how these tests exercises the whole application, and do not assert much. What is there to assert? We have already proven that everything works, we just want to make sure that it is wired properly.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-141461068372288356?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/software-testing-categorization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why are we embarrassed to admit that we don&#8217;t know how to write tests?</title>
		<link>https://googledata.org/google-testing/why-are-we-embarrassed-to-admit-that-we-dont-know-how-to-write-tests/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-are-we-embarrassed-to-admit-that-we-dont-know-how-to-write-tests</link>
		<comments>https://googledata.org/google-testing/why-are-we-embarrassed-to-admit-that-we-dont-know-how-to-write-tests/#comments</comments>
		<pubDate>Wed, 08 Jul 2009 16:49:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Take your average developer and ask "do you know language/technology X?" None of us will feel any shame in admitting that we do not know X. After all there are so many languages, frameworks and technologies, how could you know them all? But what if X i...]]></description>
				<content:encoded><![CDATA[<span class="Apple-style-span"   style="font-family:Times;font-size:medium;"><div style="PADDING-RIGHT: 0.6em; PADDING-LEFT: 0.6em; PADDING-BOTTOM: 0.6em; MARGIN: 0px; FONT: 13px/19px Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; PADDING-TOP: 0.6em; BACKGROUND-COLOR: rgb(255,255,255); -webkit-background-clip: initial; -webkit-background-origin: initial"><p>Take your average developer and ask "do you know language/technology X?" None of us will feel any shame in admitting that we do not know X. After all there are so many languages, frameworks and technologies, how could you know them all? But what if X is writing testable code? Somehow we have trouble answering the question "do you know how to write tests?" Everyone says yes, whether or not we actually know it. It is as if there is some shame in admitting that you don't know how to write tests.</p><p>Now I am not suggesting that people knowingly lie here, it is just that they think there is nothing to it. We think: I know how to write code, I think my code is pretty good, therefore my code is testable!</p><p>I personally think that we would do a lot better if we would recognize testability as a skill in its own right. And as such skills are not innate and take years of practice to develop. We could than treat it as any other skill and freely admit that we don't know it. We could than do something about it. We could offer classes, or other materials to grow our developers, but instead we treat it like breathing. We think that any developer can write testable code.</p><p>It took me two years of writing tests first, where I had as much tests as production code, before I started to understand what is the difference between testable and hard to test code. Ask yourself, how long have you been writing tests? What percentage of the code you write is tests?</p><p>Here is a question which you can ask to prove my point: "How do you write hard to test code?" I like to ask this question in interviews and most of the time I get silence. Sometimes I get people to say, make things private. Well if visibility is your only problem, I have a RegExp for you which will solve all of your problems. The truth is a lot more complicated, the code is hard to test doe to its structure, not doe to its naming conventions or visibility. <a href="http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/" mce_href="http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/">Do you know the answer?</a></p><p>We all start at the same place. When I first heard about testing I immediately thought about writing a framework which will pretend to be a user so that I can put the app through its paces. It is only natural to thing this way. This kind of tests are called end-to-end-tests (or scenario or large tests), and they should be the last kind of tests which you write not the first thing you think of. End-to-end-tests are great for locating <a href="http://misko.hevery.com/2008/11/17/unified-theory-of-bugs/" mce_href="http://misko.hevery.com/2008/11/17/unified-theory-of-bugs/">wiring bugs</a> but are pretty bad at locating <a href="http://misko.hevery.com/2008/11/17/unified-theory-of-bugs/" mce_href="http://misko.hevery.com/2008/11/17/unified-theory-of-bugs/">logical bugs</a>. And most of your mistakes are in logical bugs, those are the hard ones to find. I find it a bit amusing that to fight buggy code we write even more complex framework which will pretends to be the user, so now we have even more code to test.</p><p>Everyone is in search of some magic test framework, technology, the know-how, which will solve the testing woes. Well I have news for you: there is no such thing. <span class="Apple-style-span" style="FONT-WEIGHT: bold" mce_style="font-weight: bold;" mce_name="strong">The secret in tests is in writing testable code</span>, not in knowing some magic on testing side. And it certainly is not in some company which will sell you some test automation framework. Let me make this super clear: <span class="Apple-style-span" style="FONT-WEIGHT: bold" mce_style="font-weight: bold;" mce_name="strong">The secret in testing is in writing testable-code</span>! You need to go after your developers not your test-organization.</p><p>Now lets think about this. Most organizations have developers which write code and than a test organization to test it. So let me make sure I understand. There is a group of people which write untestable code and a group which desperately tries to put tests around the untestable code. (Oh and test-group is not allowed to change the production code.) The developers are where the mistakes are made, and testers are the ones who feel the pain. Do you think that the developers have any incentive to change their behavior if they don't feel the pain of their mistakes? Can the test-organization be effective if they can't change the production code?</p><p>It is so easy to hide behind a "framework" which needs to be built/bought and things will be better. But the root cause is the untestable code, and until we learn to admit that we don't know how to write testable code, nothing is going to change...</p></div></span><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-3592174159500685132?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/why-are-we-embarrassed-to-admit-that-we-dont-know-how-to-write-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Separation anxiety?</title>
		<link>https://googledata.org/google-testing/separation-anxiety/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=separation-anxiety</link>
		<comments>https://googledata.org/google-testing/separation-anxiety/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 22:00:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Shyam SeshadriWe all have separation anxiety. Its a human tendency. We love inertia, and we don’t like change. But why should your code have separation anxiety ? Its not human (even though it might try and grow a brain of its own at times)!I bring...]]></description>
				<content:encoded><![CDATA[by <a href="http://assertionfailed.wordpress.com/about/">Shyam Seshadri</a><br /><br /><p>We all have separation anxiety. Its a human tendency. We love inertia, and we don’t like change. But why should your code have separation anxiety ? Its not human (even though it might try and grow a brain of its own at times)!</p><br /><p>I bring this up because I got the chance to work with someone who had some questions on how to test UI code. Fairly innocuous question, and in most cases, my response would have been, keep the UI code simple and free of any logic, and don’t worry too much about it. Or you could write some nice end to end / integration tests / browser based tests. So with that response set in mind, I set off into the unknown. Little was I to know was that was the least of my concerns. As I sat down to look at the code, I saw that there were already tests for the code. I was optimistic now, I mean, how bad could things be if there are already tests for it ?</p><br /><p>Well, I should remember next time to actually look at the tests first. But anyways, there were tests, so I was curious what kinds of tests they wanted to write and what kind of help I could provide, if any. So it turns out, the class was some sort of GUI Component, which basically had some fields, and depending on whether they were set of not, displayed them as widgets inside of it. So there were, say, 5 fields, and differing combinations of what was set would produce different output. The nice thing was that the rendered data was returned as a nice Java object, so you could easily assert on what was set, and get a handle on the widgets inside of it, etc. So the method was something along the following lines :</p><br /><pre><span style="color: rgb(51, 51, 51);">public RenderedWidgetGroup render() {<br /></span><span style="color: rgb(51, 51, 51);">    </span><span style="color: rgb(51, 51, 51);">RenderedWidgetGroup group =<br />       createWidgetGroup(this.componentId,<br />                         this.parent);</span><br /><span style="color: rgb(51, 51, 51);">    if (this.name = null) {</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">        return group;</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">    } </span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">    group.addWidget(new TextWidget(this.name));</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">    group.addWidget(<br />       new DateWidget(<br />           this.updatedTimestamp == null ?<br />                this.createdTimestamp : this.updatedTimestamp));<br /></span><span style="color: rgb(51, 51, 51);">    </span><span style="color: rgb(51, 51, 51);">return group;</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">}</span></pre><br /><p>So far, so good, right ? Nice, clean, should be easy to test if we can set up this component with the right fields. After that, it should just be a few tests based on the different code paths defined by the conditionals. Yeah, thats what I thought too. So, me, being the naive guy that I was, said, yeah, that  looks nice, should be easy to test. I don’t see the problem.</p><br /><p>Well, then I was taken to the tests. The first thing I see is a huge test. Or atleast thats what I think it is. Then I read it more closely, and see its a private method. It seems to take in a bunch of fields (Fields with names that I distinctly remembered from just a while ago) and churn out a POJO (Plain Old Java Object). Except this POJO was not the GUI Component object I expected. So obviously, I was curious (and my testing sensors were starting to tingle).  So I followed through to where it was called (which wasn’t very hard, it was a private method) and lo and behold, my worst fears confirmed.</p><br /><p>The POJO object generated by the private method was passed in to the constructor of the GUI component, which (on following it further down the rabbit hole) in its constructor did something like the following :</p><br /><pre><span style="color: rgb(51, 51, 51);">public MyGUIComponent(ComponentId id,<br />                     Component parent,<br />                     MyDataContainingPOJO pojo) {<br />   super(id, parent);<br />   readData(pojo);<br />} </span></pre><br /><p>And of course, <strong>readData</strong>, as you would expect, is a :</p><br /><ul><br /><li>Private method</li><br /><li>Looks through the POJO</li><br /><li>If it finds a field which is not null then it sets it in the Gui Component</li><br /></ul><br /><p>And of course, without writing the exact opposite of this method in the unit test, it just wasn’t possible to write unit tests. And sudddenly, it became clear why they were having trouble unit testing their Gui Components. Because if they wanted to test render (Which was really their aim), they would have to set up this POJO with the correct fields (which of course, to make things more interesting / miserable, had sub POJOs with sub POJOs of their own. Yay!) to be exercised in their test.</p><br /><p>The problem with this approach is two fold :</p><br /><ol><br /><li>I need tests to ensure that the parsing and reading from the POJO logic is sound, and that it correctly sets up the GUI Component.</li><br /><li>Every time I want to test the render logic, I end up testing (unintentionally, and definitely unwantedly) the parsing logic.</li><br /></ol><br /><p>This also adds, as I saw, obviously complicated pre test setup logic which should not be required to test something completely different. This is a HUGE <strong>code smell</strong>. Unit testing a class should not be an arduous, painful task. It should be easy as setting up a POJO and testing a method. The minute you have to perform complicated setup to Unit test a class (Note, the keyword is unit test. You can have integration tests which need some non trivial setup.), stop! There is something wrong.</p><br /><p>The problem here is that there is a mixing of concerns in the MyGuiComponent class. As it turns out, MyGuiComponent breaks a few fundamental rules of testability. One, it does <strong>work in the constructor</strong>. Two, it violates the <strong>law of demeter</strong>, which states that the class should ask for what it needs, not what it doesn’t need to get what it needs (Does that even make sense ?). Thirdly, it is <strong>mixing concerns</strong>. That is, it does too much. It knows both how to create itself as well as do the rendering logic. Let me break this down further :</p><br /><h3>Work in the constructor</h3><br /><p>If you scroll back up and look at the constructor for MyGuiComponent, you will see it calling <strong><em><span style="color: rgb(128, 128, 128);">readData(pojo)</span></em></strong>. Now, the basic concept to test any class is that you have to create an instance of the class under test (unless it has static methods. Don’t get me started on that…). So now, every time you create an instance of MyGuiComponent, guess what ? <strong><em><span style="color: rgb(128, 128, 128);">readData(pojo)</span></em></strong> is going to get called. <strong>Every. Single. Time</strong> ! And it cannot be mocked out. Its a private method. And god forbid if you really didn’t care about the pojo and passed in a null. Guess what ? It most probably will blow up with a NullPointerException. So suddenly, that innocuous method in the constructor comes back to haunt you when you write yours tests (You are, aren’t you ?).</p><br /><h3>Law of Demeter</h3><br /><p>Furthermore, if you look at what <strong><em><span style="color: rgb(128, 128, 128);">readData(pojo)</span></em></strong> does, you would be even more concerned. At its base, MyGuiComponent only cares about 6 fields which it needs to render. Depending on the state of each of these fields, it adds widget. So why does the constructor ask for something totally unrelated ? This is a fundamental violation of the Law of Demeter. The Law of Demeter can be summed up as “Ask for what you need. If you need to go through one object to get what you need, you are breaking it.”. A much more fancier definition can be found on the web if you care, but the minute you see something like A.B().C() or something along those lines, there is a potential violation.</p><br /><p>In this case, MyGuiComponent doesn’t really care about the POJO. It only cares about some fields in the POJO, which it then assigns to its own fields. But the constructor still asks for the POJO instead of directly asking for the fields. What this means is that instead of just creating an instance of MyGuiComponent with the required fields in my test, I now have to create the POJO with the required fields and pass that in instead of just setting it directly. Convoluted, anyone ?</p><br /><h3>Mixing Concerns</h3><br /><p>Finally, what could be considered an extension of the previous one, but deserves a rant of its own. What the fundamental problem with the above class is that it is mixing concerns. It knows both how to create itself as well as how to render itself once it has been created. And the way it has been coded enforces that the creation codepath is executed every single time. To provide an analogy for how ridiculous this is, it is like a a Car asking for an Engine Number and then using that number to create its own engine. Why the heck should a car have to know how to create its engine ? Or even a car itself ? Similarly, why should <strong>MyGuiComponent</strong> know how to create itself ? Which is exactly what is happening here.</p><br /><h3>Solution</h3><br /><p>Now that we had arrived at the root of the problem, we immediately went about trying to fix it. My immediate instinct was to pull out MyGuiComponent into the two classes that I was seeing. So we pulled out a MyGuiComponentFactory, which took up the responsibility of taking in the POJO and creating a GuiComponent out of it. Now this was independently testable. We also added a builder pattern to the MyGuiComponent, which the factory leveraged.</p><br /><pre><span style="color: rgb(51, 51, 51);">class MyGuiComponentFactory {</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(136, 136, 136);"><span style="color: rgb(51, 51, 51);">    MyGuiComponent createFromPojo(ComponentId id,<br />                                 Component parent,<br />                                 MyDataContainingPOJO pojo) {<br />     // Actual logic of converting from pojo to<br />     // MyGuiComponent using the builder pattern<br />    }<br />}</span></span><br /><span style="color: rgb(51, 51, 51);">class MyGuiComponent {</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">    public MyGuiComponent(ComponentId id,<br />                         Component parent) {<br />       super(id, parent);<br />   }</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">    public MyGuiComponent setName(String name) {<br />       this.name = name;<br />       return this;<br />   }</span><span style="color: rgb(51, 51, 51);"><br /></span><span style="color: rgb(51, 51, 51);">} </span></pre><br /><p>And now, suddenly (and expectedly, I would like to add), the constructor for MyGuiComponent becomse simple. There is no work in the constructor. The fields are set up through setters and the builder pattern. So now, we started writing the unit tests for the render methods. It took about a single line of setup to instantiate MyGuiComponent, and we could test the render method in isolation now. Hallelujah!!</p><br /><p>Disclaimer :<br /><br />No code was harmed / abused in the course of the above blog post. There were no separation issues whatsoever in the end, it was a clean mutual break!</p><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-1183337849722593346?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/separation-anxiety/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Yet Another JavaScript Testing Framework</title>
		<link>https://googledata.org/google-testing/yet-another-javascript-testing-framework/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=yet-another-javascript-testing-framework</link>
		<comments>https://googledata.org/google-testing/yet-another-javascript-testing-framework/#comments</comments>
		<pubDate>Fri, 22 May 2009 22:36:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško Hevery &#38; Jeremie Lenfant-engelmannDid you notice that there are a lot of JavaScript testing frameworks out there? Why has the JavaScript community not consolidated on a single JavaScript framework the way Java has on JUnit. My feeling is ...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a> &amp; Jeremie Lenfant-engelmann<br /><br />Did you notice that there are a lot of JavaScript testing frameworks out there? Why has the JavaScript community not consolidated on a single JavaScript framework the way Java has on JUnit. My feeling is that all of these frameworks are good at something but none solve the complete package. Here is what I want out of JavaScript unit-test framework:<br /><blockquote><em>I want to edit my JavaScript code in my favorite IDE, and when I hit Ctrl-S, I want all of the tests to execute across all browsers and return the results immediately.</em></blockquote><br />I don't know of any JavaScript framework out there which will let me do what I want. In order to achieve my goal I need a JavaScript framework with these three features:<br /><br /><strong>Command Line Control</strong><br /><br />Most JavaScript test runners consist of JavaScript application which runs completely in the browser. What this means in practice is that I have to go to the browser and <em>refresh</em> the page to get my results. But browsers need an HTML file to display, which means that I have to write HTML file which loads all of my production code and my tests before I can run my tests. Now since browsers are sandboxes, the JavaScript tests runner can only report the result of the test run inside the browser window for human consumption only. This implies that 1) I cannot trigger running of the tests by hitting Ctrl-S in my IDE, I have to Alt-tab to Browser, hit refresh and Alt-tab back to the IDE and 2) I cannot display my test result in my IDE, the results are in the browser in human readable form only.<br /><br />On my continuous build machine I need to be able to run the same tests and somehow get the failures out of the browser and on to the status page. Most JavaScript test runners have a very poor story here, which makes integrating them into a continuous build very difficult.<br /><br />What we need, is the ability to control test execution from command line so that I can trigger it from my IDE, or my continuous build machine. And I need test failures to be reported on the command line (not inside the browser where they are unreachable) so that I can display them in IDE or in continuous build status page.<br /><br /><strong>Parallel Execution</strong><br /><br />Since most JavaScript test runners run fully in the browser I can only run my test on one browser at a time during my development process. In practice this means that you don't find out about failures in other browser until you have checked in the code to your continuous build machine (if you were able to set it up) and your code executes on all browsers. By that point you have completely forgotten about what you have written and debugging becomes a pain. When I run my test I want to run them on all browser platforms in parallel.<br /><br /><strong>Instant Feedback in IDE</strong><br /><br />After I hit Ctrl-S on my IDE, my patience for test results is about two seconds before I start to get annoyed. What this means in practice is that you can not wait until the browser launches and runs the tests. The browser needs to be already running. Hitting refresh on your browser manually is very expensive since the browser needs to reload all of the JavaScript code an re-parse it. If you have one HTML file for each TestCase and you have hundred of these TestCases, The browser may be busy for several minutes until it reloads and re-parses the same exact production code once for each TestCase. There is no way you can fit that into the patience of average developer after hitting Ctrl-S.<br /><br /><strong>Introducing <a href="http://code.google.com/p/js-test-driver/">JsTestDriver</a></strong><br /><br />Jeremie Lenfant-engelmann and I have set out to build a JavaScript test runner which solves exactly these issues so that Ctrl-S causes all of my JavaScript tests to execute in under a second on all browsers. Here is how Jeremie has made this seemingly impossible dream a reality. On startup <a href="http://code.google.com/p/js-test-driver/">JsTestDriver</a> captures any number of browsers from any number of platforms and turns them into slaves. As slave the browser has your production code loaded along with all of your test code. As you edit your code and hit Ctrl-S the <a href="http://code.google.com/p/js-test-driver/">JsTestDriver</a> reloads only the files which you have modified into the captured browsers slaves, this greatly reduces the amount of network traffic and amount of JavaScript re-parsing which the browser has to do and therefore greatly improves the test execution time. The <a href="http://code.google.com/p/js-test-driver/">JsTestDriver</a> than runs all of your test in parallel on all captured browsers. Because JavaScript APIs are non-blocking it is almost impossible for your tests to run slow, since there is nothing to block on, no network traffic and no re-parsing of the JavaScript code. As a result JsTestDriver can easily run hundreds of TestCases per second. Once the tests execute the results are sent over the network to the command which executed the tests either on the command line ready to be show in you IDE or in your continuous build.<br /><br /><strong>Demo</strong><br /><object type="application/x-shockwave-flash" height="505" width="640" data="http://www.youtube.com/v/V4wYrR6t5gE&amp;hl=" fs="1"></object><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-8134342768172481822?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/yet-another-javascript-testing-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Constructor Injection vs. Setter Injection</title>
		<link>https://googledata.org/google-testing/constructor-injection-vs-setter-injection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=constructor-injection-vs-setter-injection</link>
		<comments>https://googledata.org/google-testing/constructor-injection-vs-setter-injection/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 18:22:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryThere seems to be two camps in dependency-injection: (1) The constructor-injection camp and (2) the setter-injection camp. Historically the setter-injection camp come from spring, whereas constructor-injection camp are from pico-contain...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />There seems to be two camps in dependency-injection: (1) The constructor-injection camp and (2) the setter-injection camp. Historically the setter-injection camp come from spring, whereas constructor-injection camp are from pico-container and GUICE. But lets leave the history behind and explore the differences in the strategies.<br /><br /><strong>Setter-Injection</strong><br /><br />The basic-ideas is that you have a no argument-constructor which creates the object with "reasonable-defaults" . The user of the object can then call setters on the object to override the collaborators of the object in order to wire the object graph together or to replace the key collaborators with test-doubles.<br /><br /><strong>Constructor-Injection</strong><br /><br />The basic idea with constructor-injection is that the object has no defaults and instead you have a single constructor where all of the collaborators and values need to be supplied before you can instantiate the object.<br /><br />At first it may seem that setter injection is preferred since you have no argument constructors which will make it easy for you to create the object in production and test. However, there is one non-obvious benefit with constructor injection, which in my opinion makes it a winner. Constructor-injection enforces the order of initialization and prevents <a href="http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/">circular dependencies</a>. With setter-injection it is not clear in which order things need to be instantiated and when the wiring is done. In a typical application there may be hundreds of collaborators with at least as many setter calls to wire them together. It is easy to miss a few setter calls when wiring the application together. On the other hand constructor-injection automatically enforces the order and completeness of the instantiated. Furthermore, when the last object is instantiated the wiring phase of your application is completed. This further allows me to set the collaborators as final which makes the code easier to comprehend if you know a given field will not change during the lifetime of the application.<br /><br />Let's look at an example as to how we would instantiate a CreditCardProcessor.<br /><pre>CreditCardProcessor processor = new CreditCardProcessor();</pre><br />Great I have instantiated CreditCardProcessor, but is that enough? No, I somehow need to know to call, setOfflineQueue(). This information is not necessarily obvious.<br /><pre>OfflineQueue queue = new OfflineQueue();<br />CreditCardProcessor processor = new CreditCardProcessor();<br />processor.setOfflineQueue(queue);</pre><br />Ok I have instantiated the OfflineQueue and remember to set the queue as a collaborator of the processor, but am I done? No, you need to set the database to both the queue and the processor.<br /><pre>Database db = new Database();<br />OfflineQueue queue = new OfflineQueue();<br />queue.setDatabase(db);<br />CreditCardProcessor processor = new CreditCardProcessor();<br />processor.setOfflineQueue(queue);<br />processor.setDatabase(db);</pre><br />But wait, you are not done you need to set the Username, password and the URL on the database.<br /><pre>Database db = new Database();<br />db.setUsername("username");<br />db.setPassword("password");<br />db.setUrl("jdbc:....");<br />OfflineQueue queue = new OfflineQueue();<br />queue.setDatabase(db);<br />CreditCardProcessor processor = new CreditCardProcessor();<br />processor.setOfflineQueue(queue);<br />processor.setDatabase(db);</pre><br />Ok, am I done now? I think so, but how do I know for sure? I know a framework will take care of it, but what if I am in a language where there is no framework, then what?<br /><br />Ok, now let's see how much easier this will be in the constructor-injection. Lets instantiate CreditCardPrecossor.<br /><pre>CreditCardProcessor processor = new CreditCardProcessor(?queue?, ?db?);</pre><br />Notice we are not done yet since CreditCardProcessor needs a queue and a database, so lets make those.<br /><pre>Database db = new Database("username", "password", "jdbc:....");<br />OfflineQueue queue = new OfflineQueue(db);<br />CreditCardProcessor processor = new CreditCardProcessor(queue, db);</pre><br />Ok, every constructor parameter is accounted for, therefore we are done. No framework needed, to tell us that we are done. As an added bonus the code will not even compile if all of the constructor arguments are not satisfied. It is also not possible to instantiate things in the wrong order. You must instantiate Database before the OfflineQueue, since otherwise you could not make the compiler happy. I personally find the constructor-injection much easier to use and the code is much easier to read and understand.<br /><br />Recently, I was building a Flex application and using the <a href="http://misko.hevery.com/2008/07/05/testing-ui-part1/">Model-View-Controller</a>. Flex XML markup requires that components must have no argument constructors, therefore I was left with setter-injection as the only way to do dependency injection. After several views I was having hard time to keep all of the pieces wired together properly, I was constantly forgetting to wire things together. This made the debugging hard since the application appeared to be wired together (as there are reasonable defaults for your collaborators) but the collaborators were of wrong instances and therefor the application was not behaving just right. To solve the issue, I was forced to abandon the Flex XML as a way to instantiate the application so that I can start using the constructor-injection and these issues went away.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-2673227152205185572?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/constructor-injection-vs-setter-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>To Assert or Not To Assert</title>
		<link>https://googledata.org/google-testing/to-assert-or-not-to-assert/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=to-assert-or-not-to-assert</link>
		<comments>https://googledata.org/google-testing/to-assert-or-not-to-assert/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 18:22:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeverySome of the strongest objections I get from people is on my stance on what I call "defensive programming". You know all those asserts you sprinkle your code with. I have a special hate relationship against null checking. But let me expl...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/2008/09/30/about/">Miško Hevery</a><br /><br />Some of the strongest objections I get from people is on my stance on what I call "defensive programming". You know all those asserts you sprinkle your code with. I have a special hate relationship against null checking. But let me explain.<br /><br />At first, people wrote code, and spend a lot of time debugging. Than someone came up with the idea of asserting that some set of things should never happen. Now there are two kinds of assertions, the ones where you assert that an object will never get into on inconsistent state and the ones where you assert that objects never gets passed a incorrect value. The most common of which is the null check.<br /><br />Than some time later people started doing automated unit-testing, and a weird thing happened, those assertions are actually in the way of good unit testing, especially the null check on the arguments. Let me demonstrate with on example.<br /><pre>class House {<br />  Door door;<br />  Window window;<br />  Roof roof;<br />  Kitchen kitchen;<br />  LivingRoom livingRoom;<br />  BedRoom bedRoom;<br /><br />  House(Door door, Window window,<br />            Roof roof, Kitchen kitchen,<br />            LivingRoom livingRoom,<br />            BedRoom bedRoom){<br />    this.door = Assert.notNull(door);<br />    this.window = Assert.notNull(window);<br />    this.roof = Assert.notNull(roof);<br />    this.kitchen = Assert.notNull(kitchen);<br />    this.livingRoom = Assert.notNull(livingRoom);<br />    this.bedRoom = Assert.notNull(bedRoom);<br />  }<br /><br />  void secure() {<br />    door.lock();<br />    window.close();<br />  }<br />}</pre><br />Now let's say that i want to test the secure() method. The secure method needs door and window. Therefore my ideal would look like this.<br /><pre>testSecureHouse() {<br />  Door door = new Door();<br />  Window window = new Window();<br />  House house = new House(door, window,<br />             null, null, null, null);<br /><br />  house.secure();<br /><br />  assertTrue(door.isLocked());<br />  assertTrue(window.isClosed());<br />}</pre><br />Since the secure() method only needs to operate on door, and window, those are the only objects which I should have to create. For the rest of them I should be able to pass in null. null is a great way to tell the reader, "these are not the objects you are looking for". Compare the readability with this:<br /><pre>testSecureHouse() {<br />  Door door = new Door();<br />  Window window = new Window();<br />  House house = new House(door, window,<br />    new Roof(),<br />    new Kitchen(),<br />    new LivingRoom(),<br />    new BedRoom());<br /><br />  house.secure();<br /><br />  assertTrue(door.isLocked());<br />  assertTrue(window.isClosed());<br />}</pre><br />If the test fails here you are now sure where to look for the problem since so many objects are involved. It is not clear from the test that that many of the collaborators are not needed.<br /><br />However this test assumes that all of the collaborators have no argument constructors, which is most likely not the case. So if the Kitchen class needs dependencies in its constructor, we can only assume that the same person who put the asserts in the House also placed them in the Kitchen, LivingRoom, and BedRoom constructor as well. This means that we have to create instances of those to pass the null check, so our real test will look like this:<br /><pre>testSecureHouse() {<br />  Door door = new Door();<br />  Window window = new Window();<br />  House house = new House(door, window,<br />    new Roof(),<br />    new Kitchen(new Sink(new Pipes()),<br />           new Refrigerator()),<br />    new LivingRoom(new Table(), new TV(), new Sofa()),<br />    new BedRoom(new Bed(), new Closet()));<br /><br />  house.secure();<br /><br />  assertTrue(door.isLocked());<br />  assertTrue(window.isClosed());<br />}</pre><br />Your asserts are forcing you to create so many objects which have nothing to do with the test and only confuse the reader and make the tests hard to write. Now I know that a house with a <span style="font-family:mceinline;">null</span> roof, livingRoom, kitchen and bedRoom is an inconsistent object which would be an error in production, but I can write another test of my HouseFactory class which will assert that it will never happen.<br /><br />Now there is a difference if the API is meant for my internal consumption or is part of an external API. For external API I will often times write tests to assert that appropriate error conditions are handled, but for the internal APIs my tests are sufficient.<br /><br />I am not against asserts, I often use them in my code as well, but most of my asserts check the internal state of an object not wether or not I am passing in a null value. Checking for nulls usually goes against testability, and given a choice between well tested code and untested code with asserts, there is no debate for me which one I chose.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4748379615359190799?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/to-assert-or-not-to-assert/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When to use Dependency Injection</title>
		<link>https://googledata.org/google-testing/when-to-use-dependency-injection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=when-to-use-dependency-injection</link>
		<comments>https://googledata.org/google-testing/when-to-use-dependency-injection/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 00:14:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryA great question from the reader...The only thing that does not fully convince me in your articles is usage of Guice. I'm currently unable to see clearly its advantages over plain factories, crafted by hand. Do you recommend using of Gu...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about">Miško Hevery</a><br /><br />A great question from the reader...<br /><blockquote>The only thing that does not fully convince me in your articles is usage of Guice. I'm currently unable to see clearly its advantages over plain factories, crafted by hand. Do you recommend using of Guice in every single case? I strongly suspect, there are cases, where hand-crafted factories make a better fit than Guice. Could you comment on that (possibly at your website)?</blockquote><br />I think this is multi-part question:<br /><ol><br /><li>Should I be using dependency-injection?</li><br /><li>Should I be using manual dependency-injection or automatic dependency-injection framework?</li><br /><li>Which automatic dependency-injection framework should I use?</li><br /></ol><br /><strong>Should I be using dependency-injection?</strong><br /><br />The answer to this question should be a resounding <strong>yes</strong>! We covered this many times <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">how to think about the new-operator</a>, <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">singletons are liars</a>, and of course the talk on <a href="http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/">dependency-injection</a>.<br /><br />Dependency injection is simply a good idea and it helps with: testability; maintenance; and bringing new people up to speed on new code-base. Dependency-injection helps you with writing good software whether it is a small project of one or large project with a team of collaborators.<br /><br /><strong>Should I be using manual dependency-injection or automatic dependency-injection framework?</strong><br /><br />Whether or not to use a framework for dependency injection depends a lot on your preferences and the size of your project. You don't get any additional magical powers by using a framework. I personally like to use frameworks on medium to large projects but stick to manual DI with small projects. Here are some arguments both ways to help you make a decision.<br /><br /><em>In favor of manual DI:</em><br /><ul><br /><li>Simple: Nothing to learn, no dependencies.</li><br /><li>No reflection magic: In IDE it is easy to find out who calls the constructors.</li><br /><li>Even developers who do not understand DI can follow and contribute to projects.</li><br /></ul><br /><em>In favor of automatic DI framework:</em><br /><ul><br /><li>Consistency: On a large team a lot can be said in doing things in consistent manner. Frameworks help a lot here.</li><br /><li>Declarative: The wiring, scopes and rules of instantiation are declarative. This makes it easier to understand how the application is wired together and easier to change.</li><br /><li>Less typing: No need to create the factory classes by hand.</li><br /><li>Helps with end-to-end tests: For end-to-end tests we often need to replace key components of the application with fake implementations, an automated framework can be of great help.</li><br /></ul><br /><strong>Which automatic dependency-injection framework should I use?</strong><br /><br />There are three main DI frameworks which I am aware off: <a href="http://code.google.com/p/google-guice/">GUICE</a>, <a href="http://www.picocontainer.org/">Pico Container</a> and <a href="http://www.springsource.org/">Spring</a>.<br /><br />I work for Google, I have used GUICE extensively therefor my default recommendation will be GUICE. :-) However I am going to attempt to be objective about the differences. Keep in mind that I have not actually used the other ones on real projects.<br /><br />Spring was first. As a result it goes far beyond DI and has everything and kitchen sink integrated into it which is very impressive. The DI part of Spring has some differences worth pointing out. Unlike GUICE or Pico, Spring uses XML files for configuration. Both are declarative but GUICE is compiled and as a result GUICE can take advantage of compiler type safety and generics, which I think is a great plus for GUICE.<br /><br />Historically, Spring started with setter injection. Pico introduced constructor injection. Today, all frameworks can do both setter and constructor injection, but the developers using these frameworks still have their preferences. GUICE and Pico strongly prefer constructor injection while Spring is in the setter injection camp. I prefer constructor injection but the reasons are better left for another post.<br /><br />Personally, I think all of the three have been around for a while and have proven themselves extensively, so no matter which one you chose you will benefit greatly from your decision. All three frameworks have been heavily influenced by each other and on a macro level are very similar.<br /><br /><em>Your milage may very.</em><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-34081476831591347?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/when-to-use-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interfacing with hard-to-test third-party code</title>
		<link>https://googledata.org/google-testing/interfacing-with-hard-to-test-third-party-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=interfacing-with-hard-to-test-third-party-code</link>
		<comments>https://googledata.org/google-testing/interfacing-with-hard-to-test-third-party-code/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 21:19:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryShahar asks an excellent question about how to deal with frameworks which we use in our projects, but which were not written with testability in mind.Hi Misko, First I would like to thank you for the “Guide to Writing Testable Code”...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />Shahar asks an excellent question about how to deal with frameworks which we use in our projects, but which were not written with testability in mind.<br /><blockquote>Hi Misko, First I would like to thank you for the “<a href="http://misko.hevery.com/code-reviewers-guide/">Guide to Writing Testable Code</a>”, which really helped me to think about better ways to organize my code and architecture. Trying to apply the guide to the code I’m working on, I came up with some difficulties. Our code is based on external frameworks and libraries. Being dependent on external frameworks makes it harder to write tests, since test setup is much more complex. It’s not just a single class we’re using, but rather a whole bunch of classes, base classes, definitions and configuration files. Can you provide some tips about using external libraries or frameworks, in a manner that will allow easy testing of the code?<br /><p style="text-align: right;">-- Thanks, Shahar</p></blockquote><p style="text-align: left;">There are two different kind of situations you can get yourself into:</p><ol><br /> <li> Either your code calls a third-party library (such as you calling into LDAP authentication, or JDBC driver)</li><br /> <li>Or a third party library calls you and forces you to implement an interface or extend a base class (such as when using servlets).</li><br /></ol><br />Unless these APIs are written with testability in mind, they will hamper your ability to write tests.<br /><br /><strong>Calling Third-Party Libraries</strong><br /><br />I always try to separate myself from third party library with a Facade and an Adapter. Facade is an interface which has a simplified view of the third-party API. Let me give you an example. Have a look at <span style="font-family:courier new,courier;">javax.naming.ldap</span>. It is a collection of several interfaces and classes, with a complex way in which you have to call them. If your code depends on this interface you will drown in mocking hell. Now I don't know why the API is so complex, but I do know that my application only needs a fraction of these calls. I also know that many of these calls are configuration specific and outside of bootstrapping code these APIs are cluttering what I have to mock out.<br /><br />I start from the other end. I ask myself this question. 'What would an ideal API look like for my application?' The key here is 'my application' An application which only needs to authenticate will have a very different 'ideal API' than an application which needs to manage the LDAP. Because we are focusing on our application the resulting API is significantly simplified. It is very possible that for most applications the ideal interface may be something along these lines.<br /><pre>interface Authenticator {<br /> boolean authenticate(String username,<br />                      String password);<br />}</pre><br />As you can see this interface is a lot simpler to mock and work with than the original one as a result it is a lot more testable. In essence the ideal interfaces are what separates the testable world from the legacy world.<br /><br />Once we have an ideal interface all we have to do is implement the adapter which bridges our ideal interface with the actual one. This adapter may be a pain to test, but at least the pain is in a single location.<br /><br />The benefit of this is that:<br /><ul><br /> <li>We can easily implement an <span style="font-family:courier new,courier;">InMemoryAuthenticator</span> for running our application in the QA environment.</li><br /> <li>If the third-party APIs change than those changes only affect our adapter code.</li><br /> <li>If we now have to authenticate against a Kerberos or Windows registry the implementation is straight forward.</li><br /> <li>We are less likely to introduce a usage bug since calling the ideal API is simpler than calling the original API.</li><br /></ul><br /><strong>Plugging into an Existing Framework</strong><br /><br />Let's take servlets as an example of hard to test framework. Why are servlets hard to test?<br /><ul><br /> <li>Servlets require a no argument constructor which prevents us from using dependency injection. 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>.</li><br /> <li>Servlets pass around <span style="font-family:courier new,courier;">HttpServletRequest</span> and <span style="font-family:courier new,courier;">HttpServletResponse</span> which are very hard to instantiate or mock.</li><br /></ul><br />At a high level I use the same strategy of separating myself from the servlet APIs. I implement my actions in a separate class<br /><pre>class LoginPage {<br /> Authenticator authenticator;<br /> boolean success;<br /> String errorMessage;<br /> LoginPage(Authenticator authenticator) {<br />   this.authenticator = authenticator;<br /> }<br /><br /> String execute(Map&lt;String, String&gt; parameters,<br />                String cookie) {<br />   // do some work<br />   success = ...;<br />   errorMessage = ...;<br /> }<br /><br /> String render(Writer writer) {<br />   if (success)<br />     return "redirect URL";<br />   else<br />     writer.write(...);<br /> }<br />}</pre><br />The code above is easy to test because:<br /><ul><br /> <li>It does not inherit from any base class.</li><br /> <li>Dependency injection allows us to inject mock authenticator (Unlike the no argument constructor in servlets).</li><br /> <li>The work phase is separated from the rendering phase. It is really hard to assert anything useful on the Writer but we can assert on the state of the <span style="font-family:courier new,courier;">LoginPage</span>, such as <span style="font-family:courier new,courier;">success</span> and <span style="font-family:courier new,courier;">errorMessage</span>.</li><br /> <li>The input parameters to the <span style="font-family:courier new,courier;">LoginPage</span> are very easy to instantiate. (<span style="font-family:courier new,courier;">Map&lt;String, String&gt;</span>, <span style="font-family:courier new,courier;">String</span> for cookie, or a <span style="font-family:courier new,courier;">StringWriter</span> for the writer).</li><br /></ul><br />What we have achieved is that all of our application logic is in the <span style="font-family:courier new,courier;">LoginPage</span> and all of the untestable mess is in the <span style="font-family:courier new,courier;">LoginServlet</span> which acts like an adapter. We can than test the <span style="font-family:courier new,courier;">LoginPage</span> in depth. The <span style="font-family:courier new,courier;">LoginSevlet</span> is not so simple, and in most cases I just don't bother testing it since there can only be <a href="http://misko.hevery.com/2008/11/17/unified-theory-of-bugs/">wiring bug</a> in that code. There should be no application logic in the <span style="font-family:courier new,courier;">LoginServlet</span> since we have moved all of the application logic to <span style="font-family:courier new,courier;">LoginPage</span>.<br /><br />Let's look at the adapter class:<br /><pre>class LoginServlet extends HttpServlet {<br /> Provider&lt;LoginPage&gt; loginPageProvider;<br /><br /> // no arg constructor required by<br /> // Servlet Framework<br /> LoginServlet() {<br />   this(Global.injector<br />          .getProvider(LoginPage.class));<br /> }<br /><br /> // Dependency injected constructor used for testing<br /> LoginServlet(Provider&lt;LoginPage&gt; loginPageProvider) {<br />   this.loginPageProvider = loginPageProvider;<br /> }<br /><br /> service(HttpServletRequest req,<br />         HttpServletResponse resp) {<br />   LoginPage page = loginPageProvider.get();<br />   page.execute(req.getParameterMap(),<br />        req.getCookies());<br />   String redirect = page.render(resp.getWriter())<br />   if (redirect != null)<br />     resp.sendRedirect(redirect);<br /> }<br />}</pre><br />Notice the use of two constructors. One fully dependency injected and the other no argument. If I write a test I will use the dependency injected constructor which will than allow me to mock out all of my dependencies.<br /><br />Also notice that the no argument constructor is forcing me to use <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">global state</a>, which is very bad, but in the case of servlets I have no choice.  However, I make sure that only servlets access the global state and the rest of my application is unaware of this global variable and uses proper dependency injection techniques.<br /><br />BTW there are many frameworks out there which sit on top of servlets and which provide you a very testable APIs. They all achieve this by separating you from the servlet implementation and from <span style="font-family:courier new,courier;">HttpServletRequest</span> and <span style="font-family:courier new,courier;">HttpServletResponse</span>. For example <a href="http://waffle.codehaus.org/">Waffle</a> and <a href="http://www.opensymphony.com/webwork/">WebWork</a><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-6950962881670313433?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/interfacing-with-hard-to-test-third-party-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Static Methods are Death to Testability</title>
		<link>https://googledata.org/google-testing/static-methods-are-death-to-testability/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=static-methods-are-death-to-testability</link>
		<comments>https://googledata.org/google-testing/static-methods-are-death-to-testability/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 17:26:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryRecently 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 me...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />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>)<br /><br />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 "wire"</strong> since there are no objects, the code and data are separate.<br /><br />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.<br /><br />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. <br /><br />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'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.<br /><br />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.<br /><br />"So leaf methods are ok to be static but other methods should not be?" 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.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4723265772272993255?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/static-methods-are-death-to-testability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clean Code Talks &#8211; Inheritance, Polymorphism, &amp; Testing</title>
		<link>https://googledata.org/google-testing/clean-code-talks-inheritance-polymorphism-testing/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=clean-code-talks-inheritance-polymorphism-testing</link>
		<comments>https://googledata.org/google-testing/clean-code-talks-inheritance-polymorphism-testing/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 18:52:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryGoogle Tech TalksNovember 20, 2008ABSTRACTIs your code full of if statements? Switch statements? Do you have the same switch statement in various places? When you make changes do you find yourself making the same change to the same if/s...]]></description>
				<content:encoded><![CDATA[<div><br /><br />by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />Google Tech Talks<br />November 20, 2008<br /><br />ABSTRACT<br /><br />Is your code full of if statements? Switch statements? Do you have the same switch statement in various places? When you make changes do you find yourself making the same change to the same if/switch in several places? Did you ever forget one?<br /><br />This talk will discuss approaches to using Object Oriented techniques to remove many of those conditionals. The result is cleaner, tighter, better designed code that's easier to test, understand and maintain.<br /><br /><a href="http://www.youtube.com/watch?v=4F72VULWFvc">Video</a><br /><br /><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/4F72VULWFvc&amp;hl=en&amp;fs=1"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed src="http://www.youtube.com/v/4F72VULWFvc&amp;hl=en&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object><br /><br /><a href="http://docs.google.com/Present?docid=d449gch_62ckrb4zgj">Slides</a></div><br /><iframe src="http://docs.google.com/EmbedSlideshow?docid=d449gch_62ckrb4zgj" frameborder="0" width="410" height="342"></iframe><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-2327486247114822215?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/clean-code-talks-inheritance-polymorphism-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Guide to Writing Testable Code</title>
		<link>https://googledata.org/google-testing/guide-to-writing-testable-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=guide-to-writing-testable-code</link>
		<comments>https://googledata.org/google-testing/guide-to-writing-testable-code/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 16:47:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[It is with great pleasure that I have been able to finally open-source the Guide to Writing Testable Code.I am including the first page here for you, but do come and check it out in detail.To keep our code at Google in the best possible shape we provid...]]></description>
				<content:encoded><![CDATA[It is with great pleasure that I have been able to finally open-source the <a href="http://misko.hevery.com/code-reviewers-guide/">Guide to Writing Testable Code</a>.<br /><br />I am including the first page here for you, but do come and check it out in detail.<br /><br /><hr /><br /><p style="margin: 0.14in 0in 0in; background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" align="left">To keep our code at Google in the best possible shape we provided our software engineers with these constant reminders. Now, we are happy to share them with the world.</p><br /><p style="margin: 0.14in 0in 0in; background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" align="left"></p><br /><p style="margin: 0.14in 0in 0in; background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" align="left">Many thanks to these folks for inspiration and hours of hard work getting this guide done:</p><ul><li><a href="http://jawspeak.com/">Jonathan Wolter </a></li> <li>Russ Ruffer</li> <li><a href="http://misko.hevery.com/about/">Miško Hevery</a></li></ul><br /><p style="margin: 0.14in 0in 0in; background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" align="left"><a href="http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/">Flaw #1: Constructor does Real Work</a></p><p style="margin-left: 0.06in; margin-top: 0in; margin-bottom: 0in; font-style: normal;" align="left"><strong>Warning Signs</strong></p><ul><li><span style="font-family:Courier New,monospace;">new</span> keyword in a constructor or at field declaration</li> <li> Static method calls in a constructor or at  field declaration</li> <li> Anything more than field assignment in  constructors</li> <li> Object not fully initialized after the  constructor finishes (watch out for <span style="font-family:Courier New,monospace;">initialize</span> methods)</li> <li> Control flow (conditional or looping logic)  in a constructor</li> <li> Code does complex object graph construction  inside a constructor rather than using a factory or builder</li> <li> Adding or using an initialization block</li></ul><br /><p style="margin: 0.14in 0in 0in; background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" align="left"><a href="http://misko.hevery.com/code-reviewers-guide/flaw-digging-into-collaborators/">Flaw #2: Digging into Collaborators</a></p><p style="margin-left: 0.06in; margin-top: 0in; margin-bottom: 0in; font-style: normal;" align="left"><strong>Warning Signs</strong></p><ul><li>Objects are passed in but never used directly  (only used to get access to other objects)</li> <li>Law of Demeter violation: method call chain  walks an object graph with more than one dot (<span style="font-family:Courier New,monospace;">.</span>)</li> <li>Suspicious names: <span style="font-family:Courier New,monospace;">context</span>,  <span style="font-family:Courier New,monospace;">environment</span>, <span style="font-family:Courier New,monospace;">principal</span>,  <span style="font-family:Courier New,monospace;">container</span>, or manager</li></ul><br /><p style="margin: 0.14in 0in 0in; background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" align="left"><a href="http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/">Flaw #3: Brittle Global State &amp; Singletons</a></p><p style="margin-left: 0.06in; margin-top: 0in; margin-bottom: 0in; font-style: normal;" align="left"><strong>Warning Signs</strong></p><ul><li>Adding or using singletons</li> <li>Adding or using static fields or static  methods</li> <li>Adding or using static initialization blocks</li> <li>Adding or using registries</li> <li>Adding or using service locators</li></ul><br /><p style="margin: 0.14in 0in 0in; background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" align="left"><a href="http://misko.hevery.com/code-reviewers-guide/flaw-class-does-too-much/">Flaw #4: Class Does Too Much</a></p><p style="margin-left: 0.06in; margin-top: 0in; margin-bottom: 0in; font-style: normal;" align="left"><strong>Warning Signs</strong></p><ul><li>Summing up what the class does includes the  word “and”</li> <li>Class would be challenging for new team  members to read and quickly “get it”</li> <li>Class has fields that are only used in some  methods</li> <li>Class has static methods that only operate on  parameters</li></ul><br /><strong></strong><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4074110201034282851?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/guide-to-writing-testable-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clean Code Talks &#8211; Global State and Singletons</title>
		<link>https://googledata.org/google-testing/clean-code-talks-global-state-and-singletons/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=clean-code-talks-global-state-and-singletons</link>
		<comments>https://googledata.org/google-testing/clean-code-talks-global-state-and-singletons/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 19:15:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryGoogle Tech TalksNovember 13, 2008ABSTRACTClean Code Talk SeriesTopic: Global State and SingletonsSpeaker: Miško HeveryVideoSlides]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />Google Tech Talks<br />November 13, 2008<br /><br />ABSTRACT<br /><br />Clean Code Talk Series<br />Topic: Global State and Singletons<br /><br />Speaker: Miško Hevery<br /><br /><strong><a href="http://www.youtube.com/watch?v=-FRm3VPhseI">Video</a></strong><br /><br /><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/-FRm3VPhseI&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/-FRm3VPhseI&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object><br /><br /><br /><strong><a href="http://docs.google.com/Presentation?id=d449gch_61gm36h6c4">Slides</a></strong><br /><iframe src='http://docs.google.com/EmbedSlideshow?docid=d449gch_61gm36h6c4' frameborder='0' width='410' height='342'></iframe><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-5747702132046943224?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/clean-code-talks-global-state-and-singletons/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My Unified Theory of Bugs</title>
		<link>https://googledata.org/google-testing/my-unified-theory-of-bugs/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=my-unified-theory-of-bugs</link>
		<comments>https://googledata.org/google-testing/my-unified-theory-of-bugs/#comments</comments>
		<pubDate>Tue, 18 Nov 2008 18:29:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryI think of bugs as being classified into three fundamental kinds of bugs.Logical: Logical bug is the most common and classical "bug." This is your "if"s, "loop"s, and other logic in your code. It is by far the most common kind of bug in...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />I think of bugs as being classified into three fundamental kinds of bugs.<br /><ul><br /><li><strong>Logical</strong>: Logical bug is the most common and classical "bug." This is your "if"s, "loop"s, and other logic in your code. It is by far the most common kind of bug in an application. (<em>Think</em>: it does the wrong thing)</li><br /><li><strong>Wiring</strong>: Wiring bug is when two different objects are miswired. For example wiring the first-name to the last-name field. It could also mean that the output of one object is not what the input of the next object expects. (<em>Think</em>: Data gets clobbered in process to where it is needed.)</li><br /><li><strong>Rendering</strong>: Rendering bug is when the output (typical some UI or a report) does not look right. The key here is that it takes a human to determine what "right" is. (<em>Think</em>: it "looks" wrong)</li><br /></ul><br /><em>NOTE</em>: A word of caution. Some developers think that since they are building UI everything is a rendering bug! A rendering bug would be that the button text overlaps with the button border. If you click the button and the wrong thing happens than it is either because you wired it wrong (wiring problem) or your logic is wrong (a logical bug). Rendering bugs are rare.<br /><br /><strong>Typical Application Distribution (without Testability in Mind)</strong><br /><br />The first thing to notice about these three bug types is that the probability is not evenly distributed. Not only is the probability not even, but the cost of finding and fixing them is different. (I am sure you know this from experience). My experience from building web-apps tells me that the Logical bugs are by far the most common, followed by wiring and finally rendering bugs.<br /><p style="text-align: center;"><img class="aligncenter" title="Bug Type Distribution" src="http://spreadsheets.google.com/pub?key=p5f7FqS_WauJGv8wm5jkgOw&amp;oid=2&amp;output=image" alt="" height="193" width="350" /></p><br /><br /><strong>Cost of Finding the Bug</strong><br /><br />Logical bugs are notoriously hard to find. This is because they only show up when the right set of input conditions are present and finding that magical set of inputs or reproducing it tends to be hard. On the other hand wiring bugs are much easier to spot since the wiring of the application is mostly fixed. So if you made a wiring error, it will show up every time you execute that code, for the most part independent of input conditions. Finally, the rendering bugs are the easiest. You simply look at the page and quickly spot that something "looks" off.<br /><br /><strong>Cost of Fixing the Bug</strong><br /><br />Our experience also tells us how hard it is to fix things. A logical bug is hard to fix, since you need to understand all of the code paths before you know what is wrong and can create a solution. Once the solution is created, it is really hard to be sure that we did not break the existing functionality. Wiring problems are much simpler, since they either manifest themselves with an exception or data in wrong location. Finally rendering bugs are easy since you "look" at the page and immediately know what went wrong and how to fix it. The reason it is easy to fix is that we design our application knowing that rendering will be something which will be constantly changing.<br /><p style="text-align: center;"></p><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><table border="0" cellpadding="2"><tbody></tbody><tbody><tr><td><br /></td><td><strong>Logical</strong></td><td><strong>Wiring</strong></td><td><strong>Rendering</strong></td></tr><tr><td><strong>Probability of Occurrence</strong></td><td>High</td><td>Medium</td><td>Low</td></tr><tr><td><strong>Difficulty of Discovering</strong></td><td>Difficult</td><td>Easy</td><td>Trivial</td></tr><tr><td><strong>Cost of Fixing</strong></td><td>High Cost</td><td>Medium</td><td>Low</td></tr></tbody></table><br /><strong>How does testability change the distribution?</strong><br /><br />It turns out that testable code has effect on the distribution of the bugs. Testable code needs:<br /><p></p><ul><br /><li>Clear separation between classes (<a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">Testable Seams</a>) --&gt; clear separation between classes makes it less likely that a wiring problem is introduced. Also, less code per class lowers the probability of logical bug.</li><br /><li>Dependency Injection --&gt; makes wiring explicit (unlike <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">singletons</a>, <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">globals</a> or <a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">service locators</a>).</li><br /><li><a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">Clear separation of Logic from Wiring</a> --&gt; by having wiring in a single place it is easier to verify.</li><br /></ul><br />The result of all of this is that the number of wiring bugs are significantly reduced. (So as a percentage we gain Logical Bugs. However total number of bugs is decreased.)<br /><p style="text-align: center;"><img class="aligncenter" title="Testable Bug Distribution" src="http://spreadsheets.google.com/pub?key=p5f7FqS_WauJGv8wm5jkgOw&amp;oid=3&amp;output=image" alt="" height="195" width="348" /></p><br /><br />The interesting thing to notice is that you can get benefit from testable code without writing any tests. Testable code is better code! (When I hear people say that they sacrificed "good" code for testability, I know that they don't really understand testable-code.)<br /><br /><strong>We Like Writing Unit-Tests</strong><br /><br />Unit-tests give you greatest bang for the buck. A unit test focuses on the most common bugs, hardest to track down and hardest to fix. And a unit-test forces you to write testable code which indirectly helps with wiring bugs. As a result when writing automated tests for your application we want to overwhelmingly focus on unit test. Unit-tests are tests which focus on the logic and focus on one class/method at a time.<br /><ul><br /><li>Unit-tests focus on the logical bugs. Unit tests focus on your "if"s and "loop"s, a Focused unit-test does not directly check the wiring. (and certainly not rendering)</li><br /><li>Unit-test are focused on a single CUT (class-under-test). This is important, since you want to make sure that unit-tests will not get in the way of future refactoring. Unit-tests should HELP refactoring not PREVENT refactorings. (Again, when I hear people say that tests prevent refactorings, I know that they have not understood what unit-tests are)</li><br /><li>Unit-tests do not directly prove that wiring is OK. They do so only indirectly by forcing you to write more testable code.</li><br /><li>Functional tests verify wiring, however there is a trade-off. You "may" have hard time refactoring if you have too many functional test OR, if you mix functional and logical tests.</li><br /></ul><br /><strong>Managing Your Bugs</strong><br /><br />I like to think of tests as bug management. (with the goal of bug free) Not all types of errors are equally likley, therefore I pick my battles of which tests I focus on. I find that I love unit-tests. But they need to be focused! Once a test starts testing a lot of classes in a single pass I may enjoy high coverage, but it is really hard to figure out what is going on when the test is red. It also may hinder refactorings. I tend to go very easy on Functional tests. A single test to prove that things are wired together is good enough to me.<br /><br />I find that a lot of people claim that they write unit-tests, but upon closer inspection it is a mix of functional (wiring) and unit (logic) test.  This happens becuase people wirte tests after code, and therefore the code is not testable. Hard to test code tends to create mockeries. (A mockery is a test which has lots of mocks, and mocks returning other mocks in order to execute the desired code) The result of a mockery is that you prove little. Your test is too high level to assert anything of interest on method level. These tests are too intimate with implementation ( the intimace comes from too many mocked interactions) making any refactorings very painful.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-9131045812688558188?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/my-unified-theory-of-bugs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clean Code Talks &#8211; Dependency Injection</title>
		<link>https://googledata.org/google-testing/clean-code-talks-dependency-injection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=clean-code-talks-dependency-injection</link>
		<comments>https://googledata.org/google-testing/clean-code-talks-dependency-injection/#comments</comments>
		<pubDate>Tue, 11 Nov 2008 23:12:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryGoogle Tech TalksNovember 6, 2008ABSTRACTClean Code Talk SeriesTopic: Don't Look For Things!Speaker: Miško Hevery VideoSlides]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />Google Tech Talks<br />November 6, 2008<br /><br />ABSTRACT<br /><br />Clean Code Talk Series<br />Topic: Don't Look For Things!<br /><br />Speaker: Miško Hevery <br /><br /><strong><a href="http://www.youtube.com/watch?v=RlfLCWKxHJ0">Video</a></strong><br /><br /><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/RlfLCWKxHJ0&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/RlfLCWKxHJ0&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object><br /><br /><strong><a href="http://docs.google.com/Presentation?id=d449gch_60cx9xhchn">Slides</a></strong><br /><iframe src='http://docs.google.com/EmbedSlideshow?docid=d449gch_60cx9xhchn' frameborder='0' width='410' height='342'></iframe><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4647311401931740614?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/clean-code-talks-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clean Code Talks &#8211; Unit Testing</title>
		<link>https://googledata.org/google-testing/clean-code-talks-unit-testing/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=clean-code-talks-unit-testing</link>
		<comments>https://googledata.org/google-testing/clean-code-talks-unit-testing/#comments</comments>
		<pubDate>Wed, 05 Nov 2008 17:19:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryGoogle Tech Talks October, 30 2008 ABSTRACT Clean Code Talks - Unit Testing Speaker: Misko HeveryVideoSlides]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />Google Tech Talks October, 30 2008 ABSTRACT Clean Code Talks - Unit Testing Speaker: Misko Hevery<br /><br /><strong><a href="http://www.youtube.com/watch?v=wEhu57pih5w">Video</a></strong><br /><br /><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="344" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/wEhu57pih5w&amp;hl=en&amp;fs=1" /><embed type="application/x-shockwave-flash" width="425" height="344" src="http://www.youtube.com/v/wEhu57pih5w&amp;hl=en&amp;fs=1" allowscriptaccess="always" allowfullscreen="true"></embed></object><br /><br /><strong><a href="http://docs.google.com/Presentation?id=d449gch_58dtrzqtgv">Slides</a></strong><br /><iframe src='http://docs.google.com/EmbedSlideshow?docid=d449gch_58dtrzqtgv' frameborder='0' width='410' height='342'></iframe><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-3796964993937453523?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/clean-code-talks-unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testability Explorer: Measuring Testability</title>
		<link>https://googledata.org/google-testing/testability-explorer-measuring-testability/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=testability-explorer-measuring-testability</link>
		<comments>https://googledata.org/google-testing/testability-explorer-measuring-testability/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 19:22:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Testability Explorer: Using Byte-Code Analysis to Engineer Lasting Social Changes in an Organization’s Software Development Process. (Or How to Get Developers to Write Testable Code) Presented at 2008 OOPSLA by Miško Hevery a Best Practices Coach @ ...]]></description>
				<content:encoded><![CDATA[<p><strong>Testability Explorer: Using Byte-Code Analysis to Engineer Lasting Social Changes in an Organization’s Software Development Process. (Or How to Get Developers to Write Testable Code)</strong></p> <p><em>Presented at 2008 OOPSLA by <a href="http://misko.hevery.com/about/">Miško Hevery</a> a Best Practices Coach @ Google</em></p> <p><strong>Abstract</strong></p> <p>Testability Explorer is an open-source tool that identifies hard-to-test Java code. Testability Explorer provides a repeatable objective metric of “testability.” This metric becomes a key component of engineering a social change within an organization of developers. The Testability Explorer report provides actionable information to developers which can be used as (1) measure of progress towards a goal and (2) a guide to refactoring towards a more testable code-base.<br /><strong>Keywords:</strong> unit-testing; testability; refactoring; byte-code analysis; social engineering.</p> <p><strong>1. Testability Explorer Overview</strong></p> <p>In order to unit-test a class, it is important that the class can be instantiated in isolation as part of a unit-test. The most common pitfalls of testing are (1) mixing object-graph instantiation with application-logic and (2) relying on global state. The Testability Explorer can point out both of these pitfalls.</p> <p><strong>1.1 Non-Mockable Cyclomatic Complexity</strong></p> <p>Cyclomatic complexity is a count of all possible paths through code-base. For example: a main method will have a large cyclomatic complexity since it is a sum of all of the conditionals in the application. To limit the size of the cyclomatic complexity in a test, a common practice is to replace the collaborators of class-under-test with mocks, stubs, or other test doubles.</p> <p>Let’s define “non-mockable cyclomatic complexity” as what is left when the class-under-test has all of its accessible collaborators replaced with mocks. A code-base where the responsibility of object-creation and application-logic is separated (using Dependency Injection) will have high degree of accessible collaborators; as a result most of its collaborators will easily be replaceable with mocks, leaving only the cyclomatic complexity of the class-under-test behind.</p> <p>In applications, where the class-under-test is responsible for instantiating its own collaborators, these collaborators will not be accessible to the test and as a result will not be replaceable for mocks. (There is no place to inject test doubles.) In such classes the cyclomatic complexity will be the sum of the class-under-test and its non-mockable collaborators.</p> <p>The higher the non-mockable cyclomatic complexity the harder it will be to write a unit-test. Each non-mockable conditional translates to a single unit of cost on the Testability Explorer report. The cost of static class initialization and class construction is automatically included for each method, since a class needs to be instantiated before it can be exercised in a test.</p> <p><strong>1.2 Transitive Global-State</strong></p> <p>Good unit-tests can be run in parallel and in any order. To achieve this, the tests need to be well isolated. This implies that only the stimulus from the test has an effect on the code execution, in other words, there is no global-state.</p> <p>Global-state has a transitive property. If a global variable refers to a class than all of the references of that class (and all of its references) are globally accessible as well. Each globally accessible variable, that is not final, results in a cost of ten units on the Testability Explorer.</p> <p><strong>2. Testability Explorer Report</strong></p> <p>A chain is only as strong as its weakest link. Therefore the cost of testing a class is equal to the cost of the class’ costliest method. In the same spirit the application’s overall testability is de-fined in terms of a few un-testable classes rather than a large number of testable ones. For this reason when computing the overall score of a project the un-testable classes are weighted heavier than the testable ones.</p> <p><a href="http://misko.hevery.com/wp-content/uploads/2008/10/testabilityexplorerreport.png"><img class="alignnone size-medium wp-image-259" title="testabilityexplorerreport" src="http://misko.hevery.com/wp-content/uploads/2008/10/testabilityexplorerreport.png" alt="" height="206" width="240" /></a></p> <p><strong>3. How to Interpret the Report</strong></p> <p>By default the classes are categorized into three categories: “Excellent” (green) for classes whose cost is below 50; “Good” (yellow) for classes whose cost is below 100; and “Needs work” (red) for all other classes. For convenience the data is presented as both a pie chart and histogram distribution and overall (weighted average) cost shown on a dial.</p> <pre>[-]ClassRepository [ 323 ]<br /> [-]ClassInfo getClass(String) [ 323 ]<br />   line 51:<br />     ClassInfo parseClass(InputStream) [318]<br />     InputStream inputStreamForClass(String) [2]<br /> [-]ClassInfo parseClass(InputStream) [318]<br />   line 77: void accept(ClassVisitor, int) [302]<br />   line 75: ClassReader(InputStream) [15]</pre> <p>Clicking on the class ClassRepository allows one to drill down into the classes to get more information. For example the above report shows that ClassRepository has a high cost of 318 due to the parseClass(InputStream) method. Looking in closer we see that the cost comes from line 77 and an invocation of the accept() method.</p> <pre>73:ClassInfo parseClass(InputStream is) {<br />74:  try {<br />75:    ClassReader reader = new ClassReader(is);<br />76:    ClassBuilder v = new ClassBuilder (this);<br />77:    reader.accept(v, 0);<br />78:    return visitor.getClassInfo();<br />79:  } catch (IOException e) {<br />80:    throw new RuntimeException(e);<br />81:  }<br />82:}</pre> <p>As you can see from the code the ClassReader can never be replaced for a mock and as a result the cyclomatic complexity of the accept method can not be avoided in a test — resulting in a high testability cost. (Injecting the ClassReader would solve this problem and make the class more test-able.)</p> <p><strong>4. Social Engineering</strong></p> <p>In order to produce a lasting change in the behavior of developers it helps to have a measurable number to answer where the project is and where it should be. Such information can provide in-sight into whether or not the project is getting closer or farther from its testability goal.</p> <p>People respond to what is measured. Integrating the Testability Explorer with the project’s continuous build and publishing the report together with build artifacts communicate the importance of testability to the team. Publishing a graph of overall score over time allows the team to see changes on per check-in basis.</p> <p>If Testability Explorer is used to identify the areas of code that need to be refactored, than compute the rate of improvement and project expected date of refactoring completion and create a sense of competition among the team members.</p> <p>It is even possible to set up a unit test for Testability Explorer that will only allow the class whose testability cost is better than some predetermined cost.</p><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-5506675188755198233?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/testability-explorer-measuring-testability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency Injection Myth: Reference Passing</title>
		<link>https://googledata.org/google-testing/dependency-injection-myth-reference-passing/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dependency-injection-myth-reference-passing</link>
		<comments>https://googledata.org/google-testing/dependency-injection-myth-reference-passing/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 14:56:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško Hevery After reading the article on Singletons (the design anti-pattern) and how they are really global variables and dependency injection suggestion to simply pass in the reference to the singleton in a constructor (instead of looking them u...]]></description>
				<content:encoded><![CDATA[<p>by <a href="http://misko.hevery.com/about/" mce_href="http://googletesting.blogspot.com/2008/about/">Miško Hevery</a></p> <p>After reading the article on <a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/" mce_href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">Singletons</a> (the design anti-pattern) and how they are really <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/" mce_href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">global variables</a> and dependency injection <a href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/" mce_href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/">suggestion</a> to simply pass in the reference to the singleton in a constructor (instead of looking them up in <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/" mce_href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">global state</a>), many people incorrectly concluded that now they will have to pass the singleton all over the place. Let me demonstrate the myth with the following example.</p> <p>Let's say that you have a LoginPage which uses the UserRepository for authentication. The UserRepository in turn uses Database Singleton to get a hold of the global reference to the database connection, like this:</p> <pre>class UserRepository {<br /> private static final BY_USERNAME_SQL = "Select ...";<br /><br /> User loadUser(String user) {<br />   <b>Database db = Database.getInstance();</b><br />   return db.query(BY_USERNAME_SQL, user);<br /> }<br />}<br /><br />class LoginPage {<br /> UserRepository repo = new UserRepository();<br /><br /> login(String user, String pwd) {<br />   User user = repo.loadUser(user);<br />   if (user == null || user.checkPassword(pwd)) {<br />     throw new IllegalLoginException();<br />   }<br /> }<br />}</pre> <p>The first thought is that if you follow the advice of dependency injection you will have to pass in the Database into the LoginPage just so you can pass it to the UserRepository. The argument goes that this kind of coding will make the code hard to maintain, and understand. Let's see what it would look like after we get rid of the global variable Singleton Database look up.</p> <p>First, lets have a look at the UserRepository.</p> <pre>class UserRepository {<br /> private static final BY_USERNAME_SQL = "Select ...";<br /> private final Database db;<br /><br /><b>  UserRepository(Database db) {<br />   this.db = db;<br /> }<br /></b><br /> User loadUser(String user) {<br />   return db.query(BY_USERNAME_SQL, user);<br /> }<br />}</pre> <p>Notice how the removal of Singleton global look up has cleaned up the code. This code is now easy to test since in a test we can instantiate a new UserRepository and pass in a fake database connection into the constructor. This improves testability. Before, we had no way to intercept the calls to the Database and hence could never test against a Database fake. Not only did we have no way of intercepting the calls to Database, we did not even know by looking at the API that Database is involved. (see <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/" mce_href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">Singletons are Pathological Lairs</a>) I hope everyone would agree that this change of explicitly passing in a Database reference greatly improves the code.</p> <p>Now lets look what happens to the LoginPage...</p> <pre>class LoginPage {<br /> UserRepository repo;<br /><br /><b>  LoginPage(Database db) {<br />   repo = new UserRepository(db);<br /> }<br /></b><br /> login(String user, String pwd) {<br />   User user = repo.loadUser(user);<br />   if (user == null || user.checkPassword(pwd)) {<br />     throw new IllegalLoginException();<br />   }<br /> }<br />}</pre> <p>Since UserRepository can no longer do a global look-up to get a hold of the Database it musk ask for it in the constructor. Since LoginPage is doing the construction it now needs to ask for the Databse so that it can pass it to the constructor of the UserRepository. The myth we are describing here says that this makes code hard to understand and maintain. <b>Guess what?! The myth is correct! The code as it stands now is hard to maintain and understand.</b> Does that mean that dependency injection is wrong? NO! it means that you only did half of the work! In <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/" mce_href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">how to think about the new operator</a> we go into the details why it is important to separate your business logic from the new operators. Notice how the LoginPage violates this. It calls a new on UserRepository. The issue here is that LoginPage is <a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/" mce_href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">breaking a the Law of Demeter</a>. LoginPage is asking for the Database even though it itself has no need for the Database (This greatly hinders testability as explained <a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/" mce_href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">here</a>). You can tell since LoginPage does not invoke any method on the Database. <b>This code, like the myth suggest, is bad!</b> So how do we fix that?</p> <p>We fix it by doing <b>more</b> Dependency Injection.</p> <pre>class LoginPage {<br /> UserRepository repo;<br /><br /><b>  LoginPage(UserRepository repo) {<br />   this.repo = repo;<br /> }<br /></b><br /> login(String user, String pwd) {<br />   User user = repo.loadUser(user);<br />   if (user == null || user.checkPassword(pwd)) {<br />     throw new IllegalLoginException();<br />   }<br /> }<br />}</pre> <p>LoginPage needs UserRepository. So instead of trying to construct the UserRepository itself, it should simply ask for the UserRepository in the constructor. The fact that UserRepository needs a reference to Database is not a concern of the LoginPage. Neither is it a concern of LoginPage how to construct a UserRepository. Notice how this LoginPage is now cleaner and easier to test. To test we can simply instantiate a LoginPage and pass in a fake UserRepository with which we can emulate what happens on successful login as well as on unsuccessful login and or exceptions. It also nicely takes care of the concern of this myth. <b>Notice that every object simply knows about the objects it directly interacts with. There is no passing of objects reference just to get them into the right location where they are needed.</b> If you get yourself into this myth then all it means is that you have not fully applied dependency injection.</p> <p>So here are the two rules of Dependency Injection:</p> <ul><li>Always ask for a reference! (don't create, or look-up a reference in global space aka Singleton design anti-pattern)</li><li>If you are asking for something which you are not directly using, than you are violating a <a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/" mce_href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">Law of Demeter</a>. Which really means that you are either trying to create the object yourself or the parameter should be passed in through the constructor instead of through a method call. (We can go more into this in another blog post)</li></ul> <p>So <a href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/" mce_href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/">where have all the new operators gone</a> you ask? Well we have already answered that question <a href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/" mce_href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/">here</a>. And with that I hope we have put the myth to rest!</p> <p>BTW, for those of you which are wondering why this is a common misconception the reason is that people incorrectly assume that the constructor dependency graph and the call graph are inherently identical (see <a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/" mce_href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">this post</a>). If you construct your objects in-line (as most developers do, <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/" mce_href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">see thinking about the new operator</a>) then yes the two graphs are very similar. However, if you separate the object graph instantiation from the its execution, than the two graphs are independent. This independence is what allows us to inject the dependencies directly where they are needed without passing the reference through the intermediary collaborators.</p><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-4764874536707462592?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/dependency-injection-myth-reference-passing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>To &quot;new&quot; or not to &quot;new&quot;&#8230;</title>
		<link>https://googledata.org/google-testing/to-new-or-not-to-new/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=to-new-or-not-to-new</link>
		<comments>https://googledata.org/google-testing/to-new-or-not-to-new/#comments</comments>
		<pubDate>Fri, 03 Oct 2008 17:39:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško Hevery Dependency injection asks us to separate the new operators from the application logic. This separation forces your code to have factories which are responsible for wiring your application together. However, better than writing factorie...]]></description>
				<content:encoded><![CDATA[<p>by <a href="http://misko.hevery.com/about/" mce_href="http://googletesting.blogspot.com/2008/about/">Miško Hevery</a></p> <p>Dependency injection asks us to <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/" mce_href="http://googletesting.blogspot.com/2008/2008/07/08/how-to-think-about-the-new-operator/">separate the new operators from the application logic</a>. This separation forces your code to have <a href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/" mce_href="http://googletesting.blogspot.com/2008/2008/09/10/where-have-all-the-new-operators-gone/">factories which are responsible for wiring your application</a> together. However, better than writing factories,  we want to use <a href="http://misko.hevery.com/2008/09/24/application-wiring-on-auto-pilot/" mce_href="http://misko.hevery.com/2008/09/24/application-wiring-on-auto-pilot/">automatic dependency injection</a> such as GUICE to do the wiring for us. But can DI really save us from all of the new operators?</p> <p>Lets look at two extremes. Say you have a class MusicPlayer which needs to get a hold of AudioDevice. Here we want to use DI and ask for the AudioDevice in the constructor of the MusicPlayer. This will allow us to inject a test friendly AudioDevice which we can use to assert that correct sound is coming out of our MusicPlayer. If we were to use the new operator to instantiate the BuiltInSpeakerAudioDevice we would have hard time testing. So lets call objects such as AudioDevice or MusicPlayer "Injectables." Injectables are objects which you will ask for in the constructors and expect the DI framework to supply.</p> <p>Now, lets look at the other extreme. Suppose you have primitive "int" but you want to auto-box it into an "Integer" the simplest thing is to call new Integer(5) and we are done. But if DI is the new "new" why are we calling the new in-line? Will this hurt our testing? Turns out that DI frameworks can't really give you the Integer you are looking for since it does not know which Integer you are referring to. This is a bit of a toy example so lets look at something more complex.</p> <p>Lets say the user entered the email address into the log-in box and you need to call new Email("a@b.com"). Is that OK, or should we ask for the Email in our constructor. Again, the DI framework has no way of supplying you with the Email since it first needs to get a hold of a String where the email is. And there are a lot of Strings to chose from. As you can see there are a lot of objects out there which DI framework will never be able to supply. Lets call these "Newables" since you will be forced to call new on them manually.</p> <p>First, lets lay down some ground rules. An Injectable class can ask for other Injectables in its constructor. (Sometimes I refer to Injectables as Service Objects, but that term is overloaded.) Injectables tend to have interfaces since chances are we may have to replace them with an implementation friendly to testing. However, Injectable can never ask for a non-Injectable (Newable) in its constructor. This is because DI framework does not know how to produce a Newable. Here are some examples of classes I would expect to get from my DI framework: CreditCardProcessor, MusicPlayer, MailSender, OfflineQueue. Similarly Newables can ask for other Newables in their constructor, but not for Injectables (Sometimes I refer to Newables as Value Object, but again, the term is overloaded). Some examples of Newables are: Email, MailMessage, User, CreditCard, Song. If you keep this distinctions your code will be easy to test and work with. If you break this rule your code will be hard to test.</p> <p>Lets look at an example of a MusicPlayer and a Song</p> <pre>class Song {<br /> Song(String name, byte[] content);<br />}<br />class MusicPlayer {<br /> @Injectable<br /> MusicPlayer(AudioDevice device);<br /> play(Song song);<br />}</pre> <p>Notice that Song only asks for objects which are Newables. This makes it very easy to construct a Song in a test. Music player is fully Injectable, and so is its argument the AudioDevice, therefore, it can be gotten from DI framework.</p> <p>Now lets see what happens if the MusicPlayer breaks the rule and asks for Newable in its constructor.</p> <pre>class Song {<br /> String name;<br /> byte[] content;<br /> Song(String name, byte[] content);<br />}<br />class MusicPlayer {<br /> AudioDevice device;<br /> Song song;<br /> @Injectable<br /> MusicPlayer(AudioDevice device, Song song);<br /> play();<br />}</pre> <p>Here the Song is still Newable and it is easy to construct in your test or in your code. The MusicPlayer is the problem. If you ask DI framework for MusicPlayer it will fail, since the DI framework will not know which Song you are referring to. Most people new to DI frameworks rarely make this mistake since it is so easy to see: your code will not run.</p> <p>Now lets see what happens if the Song breaks the rule and ask for Injectable in its constructor.</p> <pre>class MusicPlayer {<br /> AudioDevice device;<br /> @Injectable<br /> MusicPlayer(AudioDevice device);<br />}<br />class Song {<br /> String name;<br /> byte[] content;<br /> MusicPlayer palyer;<br /> Song(String name, byte[] content, MusicPlayer player);<br /> play();<br />}<br />class SongReader {<br /> MusicPlayer player<br /> @Injectable<br /> SongReader(MusicPlayer player) {<br />   this.player = player;<br /> }<br /> Song read(File file) {<br />   return new Song(file.getName(),<br />                   readBytes(file),<br />                   player);<br /> }<br />}</pre> <p>At first the world looks OK. But think about how the Songs will get created. Presumably the songs are stored on a disk and so we will need a SongReader. The SongReader will have to ask for MusicPlayer so that when it calls the new on a Song it can satisfy the dependencies of Song on MusicPlayer. See anything wrong here? Why in the world does SongReader need to know about the MusicPlayer. This is a <a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/" mce_href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">violation of Law of Demeter</a>. The SongReader does not need to know about MusicPlayer. You can tell since SongReader does not call any method on the MusicPlayer. It only knows about the MusicPlayer because the Song has violated the Newable/Injectable separation. The SongReader pays the price for a mistake in Song. Since the place where the mistake is made and where the pain is felt are not the same this mistake is very subtle and hard to diagnose. It also means that a lot of people make this mistake.</p> <p>Now from the testing point of view this is a real pain. Suppose you have a SongWriter and you want to verify that it correctly serializes the Song to disk. Why do you have to create a MockMusicPlayer so that you can pass it into a Song so that you can pass it into the SongWritter. Why is MusicPlayer in the picture? Lets look at it from a different angle. Song is something you may want to serialize, and simplest way to do that is to use Java serialization. This will serialize not only the Song but also the MusicPlayer and the AudioDevice. Neither MusicPlayer nor the AudioDevice need to be serialized. As you can see a subtle change makes a whole lot of difference in the easy of testability.</p> <p>As you can see the code is easiest to work with if we keep these two kinds objects distinct. If you mix them your code will be hard to test.  Newables are objects which are at the end of your application object graph. Newables may depend on other Newables as in CreditCard may depend on Address which may depend on a City but these things are leafs of the application graph. Since they are leafs, and they don't talk to any external services (external services are Injectables) there is no need to mock them. Nothing behaves more like a String like than a String. Why would I mock User if I can just new User, Why mock any of these: Email, MailMessage, User, CreditCard, Song? Just call new and be done with it.</p> <p>Now here is something very subtle. It is OK for Newable to know about Injectable. What is not OK is for the Newable to have a field reference to Injectable. In other words it is OK for Song to know about MusicPlayer. For example it is OK for an Injectable MusicPlayer to be passed in through the stack to a Newable Song. This is because the stack passing is independent of DI framework. As in this example:</p> <pre>class Song {<br /> Song(String name, byte[] content);<br /> boolean isPlayable(MusicPlayer player);<br />}</pre> <p>The problem becomes when the Song has a field reference to MusicPlayer. Field references are set through the constructor which will force a <a href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/" mce_href="http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/">Law of Demeter violation</a> for the caller and we will have hard time to test.</p><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-2907065510802987377?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/to-new-or-not-to-new/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Testing Blog 2008-09-26 16:49:00</title>
		<link>https://googledata.org/google-testing/google-testing-blog-2008-09-26-164900/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=google-testing-blog-2008-09-26-164900</link>
		<comments>https://googledata.org/google-testing/google-testing-blog-2008-09-26-164900/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 20:49:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
    by Miško Hevery

    We talked about how it is important to separate the new operators from the application logic. This separation forces your code to have factories which are responsible for wiring your application together. By separating these ...]]></description>
				<content:encoded><![CDATA[<p>
<br />    by <a href="http://misko.hevery.com/about/">Miško Hevery</a>
<br /></p><p>
<br />    We talked about how it is important to <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">separate the new operators from the application logic</a>. This separation forces your code to have <a href="http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/">factories which are responsible for wiring your application</a> together. By separating these responsibilities the tests can always wire together a subset of an application with key components replaced for friendlies making testing easier and more focused.
<br /></p><p>Let's look at a sample factory
<br /></p>    <pre>class CarFactory {
<br />Car create() {
<br />  return new Car(
<br />        new EngineCompartment(
<br />              new Engine(),
<br /><span style="font-family:Times;"><pre>                new Door(new PowerWindow()),
<br />              new Door(new PowerWindow()),
<br />              new PowerSeat(), new PowerSeat()</pre></span>                new ManualTransmission(),
<br />              new PowerSteering(),
<br />              new Battery()
<br />           ),
<br />        new Cabin(
<br />              new Door(new PowerWindow()),
<br />              new Door(new PowerWindow()),
<br />              new PowerSeat(), new PowerSeat()
<br />          ),
<br />       Arrays.asList(
<br />            new Wheel(new Tire(), new Rim()),
<br />            new Wheel(new Tire(), new Rim()),
<br />            new Wheel(new Tire(), new Rim()),
<br />            new Wheel(new Tire(), new Rim())
<br />          )
<br />     );
<br />}
<br />}</pre>    This factory builds a car. The first thing to notice is that all of the <span style="font-family:Courier New;">new</span> operators are here (If you were to look inside each of the classes it would be devoid of "new"s). The second thing to notice is a complete lack of logic (no loops or conditions). And thirdly, your application behavior is controlled by the way the classes are wired together. If I wanted a automatic-transmission car, all I would have to do is to wire the classes differently. The wiring responsibility is in the factory class not with the application logic.
<br />
<br />But why do we need to tell the JVM how to wire these Classes together? Is it not self obvious? Just look at the constructors of these classes:
<br /><pre>Car(EngineCompartment ec, Cabin c, List<wheel> ws);
<br />EngineCompartment(Engine e, Transmission t,
<br />            Steering s, Battery b);
<br />Cabin(Door driverDoor, Door passengerDoor,
<br />            Seat driverSeat, Seat passengerSeat);
<br />Engine(float dissplacement, int pistonCount);
<br />Battery(float voltage);
<br />Door(Window window);
<br /><span style="font-family:Times;"><pre>                new Door(new PowerWindow()),
<br />              new Door(new PowerWindow()),
<br />              new PowerSeat(), new PowerSeat()</pre></span>PowerWindow() implements Window;
<br />PowerSeat() implements Seat;
<br />Wheel(Tire tire, Rim rim);
<br />...</wheel></pre><p>      Imagine you could just ask for things. Lets start simple and look at the Wheel. The constructor of Wheel needs a Tire and Rim. So when we ask for a Wheel it should be obvious that we want <span style="font-family:Courier New;">new Wheel(new Tire(), new Rim())</span>. Why do we need to make this explicit in our factory? Lets build a framework from which we can ask for a class and it returns an instance of that class. So in our case if we ask for <span style="font-family:Courier New;">getInstance(Wheel.class)</span> it returns a <span style="font-family:Courier New;">new Wheel(new Tire(), new Rim())</span>. Now a framework like this is easy to build since all we need to do is look at the constructor and recursively try to instantiate the objects until all recursive constructors are satisfied.
<br /></p><p>But things are a bit more complicated than that. What if we ask for Cabin, as in <span style="font-family:Courier New;">getInstance(Cabin.class)</span>? Well Cabin needs two Doors and two Seats, but Seat is an interface so we have to make a decision: What subclass of Seat should we instantiate? To help our framework make that decision, somewhere we will add a bind method such as <span style="font-family:Courier New;">bind(Seat.class, PowerSeat.class)</span>. Great! Now when we call <span style="font-family:Courier New;">getInstance(Seat.class)</span> the framework returns <span style="font-family:Courier New;">new PowerSeat()</span>. Similarly, we will have to call <span style="font-family:Courier New;">bind(Window.class, PowerWindow.class)</span>. Now we can call <span style="font-family:Courier New;">getInstance(Cabin.class)</span> and the framework will return <span style="font-family:Courier New;">new Cabin(new Door(new PowerWindow()), new Door(new PowerWindow()), new PowerSeat(), new PowerSeat())</span>.
<br /></p><p>Notice that closer a class you ask for is to the root (Car in this case), the more work will the framework do for us. So ideally we just want to ask for the root object, Car. Calling getInstance(Car.class) will cause the framework to do all of the work originally in our factory.
<br /></p><p>As you can see a framework which will call the new operators on your behalf is very useful. This is because you only have to ask for the root object (in our case the Car) and the framework will build the whole object graph on your behalf. This kinds of frameworks are called Automatic Dependency Injection frameworks and there are few of them our there. Namely <a href="http://code.google.com/p/google-guice/">GUICE</a>, <a href="http://www.picocontainer.org/">PicoContainer</a>, and <a href="http://www.springframework.org/">Spring</a>.
<br /></p><p>Since I know most about <a href="http://code.google.com/p/google-guice/">GUICE</a>, The above example can be rewritten in GUICE like this:
<br /></p>    <pre>class CarModule extends AbstractModule() {
<br />public void bind() {
<br />  bind(Seat.class, PowerSeat.class);
<br />  bind(Seat.class, PowerSeat.class);
<br />  bind(Transmission.class, ManualTransmission.class);
<br />  // maybe use a provider method?(jwolter)
<br />  // maybe explain the need for different wheels, so use a Provider<wheel>;
<br />  bind(new TypeLiteral<list><wheel>>(){})
<br />    .toProvider(new Provider<list><wheel>>(){
<br />      @Inject Provider<wheel> wp;
<br />      List<wheel> get() {
<br />        return Array.asList(wp.get(), wp.get(),
<br />                            wp.get(), wp.get());
<br />      }
<br />    });
<br />}
<br />
<br />// or, what I think is simpler and clearer
<br />@Provides
<br />List<wheel> provideWheels(Provider<wheel> wp) {
<br />  return Array.asList(wp.get(), wp.get()
<br />                      wp.get(), wp.get());
<br />}
<br />}
<br />// Then somewhere create your application, using the injector only
<br />//   once, for the root object.
<br />Injector injector = Guice.createInjector(new CarModule());
<br />Car car = injector.getInstance(Car.class);</wheel></wheel></wheel></wheel></wheel></list></wheel></list></wheel></pre>As you can see Automatic Dependency Injection frameworks can do a lot of things for you. Namely, that you don't have to worry about writing the factories. You simply declare dependencies, and write your application logic. As needed, you ask for your dependencies in a constructor and let the framework resolve all of them for you. You move the responsibility of calling the new operator to the framework. The DI-framework is your new "new". Now DI-frameworks can do lot of other things, which are beyond the scope of this article, such as manage object lifetimes, enforce singletons (in a good way, see: <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">Root Cause of Singletons</a> and <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">Singletons are Pathological Liars</a>) and manage different configurations of your application such as production vs development server.
<br />
<br />For a more real life example of a Guice Module see: <a href="http://code.google.com/p/unit-test-teaching-examples/source/browse/trunk/src/di/webserver/CalculatorServerModule.java?r=6">CalculatorServerModule.java</a>
<br />
<br />Also, the curious may wonder why a Provider<wheel> is injected into the provider method for List&lt;Wheel&gt;. This is because our 4 wheeled car needs to have different wheels. If we injected a single wheel, it would be assigned as the same wheel on all 4 positions. Providers, when used without any explicit scopes will return a new instance every time get() is called on them.
<br />
<br /></wheel><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-992663051743495204?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/google-testing-blog-2008-09-26-164900/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where Have all the &quot;new&quot; Operators Gone?</title>
		<link>https://googledata.org/google-testing/where-have-all-the-new-operators-gone/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=where-have-all-the-new-operators-gone</link>
		<comments>https://googledata.org/google-testing/where-have-all-the-new-operators-gone/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 22:23:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[By Miško Hevery(the other title: Your Application has a Wiring Problem)In My main() Method Is Better Than Yours we looked into what a main() method should look like. There we introduced a clear separation between (1) the responsibility of constructing...]]></description>
				<content:encoded><![CDATA[By <a href="http://www.testabilityexplorer.org/about">Miško Hevery</a><br /><em>(the other title: Your Application has a Wiring Problem)</em><br /><br />In <a href="http://misko.hevery.com/2008/08/29/my-main-method-is-better-than-yours/">My main() Method Is Better Than Yours</a> we looked into what a main() method should look like. There we introduced a clear separation between (1) the responsibility of constructing the object graph and (2) the responsibility of running the application. The reason that this separation is important was outlined in <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">How to Think About the “new” Operator</a>. So let us look at where have all of the new operators gone...<br /><br />Before we go further I want you to visualize your application in your mind. Think of the components of your application as physical boxes which need to be wired together to work. The wires are the references one component has to another. In an ideal application you can change the behavior of the application just by wiring the components differently. For example instead of instantiating LDAPAuthenticator you instantiate KerberosAuthenticator and you wire the KerberosAuthenticator to appropriate components which need to know about Authenticator. That is the basic idea. By <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">removing the new operators from the application logic</a> you have separated the responsibility of wiring the components from the application logic, and this is highly desirable. So now the problem becomes, where have all the new operators gone?<br /><br />First lets look at a manual wiring process. In the <a href="http://misko.hevery.com/2008/08/29/my-main-method-is-better-than-yours/">main() method</a> we asked the ServerFactory to build us a Server (in our case a <a href="http://www.mortbay.org/jetty/">Jetty</a> Web Server) Now, server needs to be wired together with servlets. The servlets, in turn, need to be wired with their services and so on. Notice that the factory bellow is full of "new" operators. We are new-ing the components and we are passing the references of one component to another to create the wiring. This is the instantiation and wiring activity I asked you to visualize above. (Full <a href="http://code.google.com/p/unit-test-teaching-examples/source/browse/trunk/src/di/webserver/ServerBuilder.java?r=6">source</a>):<br /><pre>  public Server buildServer() {<br />  Server server = new Server();<br /><br />  SocketConnector socketConnector<br />       = new SocketConnector();<br />  socketConnector.setPort(8080);<br />  server.addConnector(socketConnector);<br /><br />  new ServletBuilder(server)<br />    .addServlet("/calc", new CalculatorServlet(<br />                         new Calculator()))<br />    .addServlet("/time", new TimeServlet(<br />                         new Provider() {<br />      public Date get() {<br />        return new Date();<br />      }<br />    }));<br /><br />  return server;<br />}</pre><br />When I first suggest to people that application logic should not instantiate its own dependencies, I get two common objections which are myths:<br /><ol><br /><li><em>"So now each class needs a factory, therefore I have twice as many classes!</em>" Heavens No! Notice how our ServerFactory acted as a factory for many different classes. Looking at it I counted 7 or so classes which we instantiated in order to wire up our application. So it is not true that we have one to one correspondence. In theory you only need one Factory per object lifetime. You need one factory for all long-lived objects (your singletons) and one for all request-lifetime objects and so on. Now in practice we further split those by related concepts. (But that is a discussion for a separate blog article.) The important thing to realize is that: yes, you will have few more classes, but it will be no where close to doubling your load.</li><br /><li><em>"If each object asks for its dependencies, than I will have to pass those dependencies through all of the callers. This will make it really hard to add new dependencies to the classes."</em> The myth here is that call-graph and instantiation-graph are one and the same. We looked into this myth in <a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">Where have all the Singletons Gone</a>. Notice that the Jetty server calls the TimeServlet which calls the Date. If the constructor of Date or TimeServlet all of a sudden needed a new argument it would not effect any of the callers. The only code which would have to change is factory class above. This is because we have isolated the instantiation/wiring problem into this factory class. So in reality this makes it easier to add dependencies not harder.</li><br /></ol><br />Now there are few important things to remember. Factories should have no logic! Just instantiation/wiring (so you will probably not have any conditionals or loops). I should be able to call the factory to create a server in a unit test without any access to the file-system, threads or any other expensive CPU or I/O operations. Factory creates the server, but does not run it. The other thing you want to keep in mind is that the wiring process is often controlled by the command line arguments. This makes is so that your application can behave differently depending what you pass in on a command line. The difference in behavior is not conditionals sprinkled throughout your code-base but rather a different way of wiring your application up.<br /><br />Finally, here are few thoughts on my love/hate of Singletons (mentioned <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">here</a> and <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">here</a>) First a little review of singletons. A singleton with a lower case 's' is a good singleton and simply means a single instance of some class. A Singleton with an upper case 'S' is a design pattern which is a singleton (one instance of some class) with a global "instance" variable which makes it accessible from anywhere. It is the global instance variable which makes it globally accessible , which turns a singleton into a Singleton. So singleton is acceptable, and sometimes very helpful for a design, but Singleton relies on mutable global state, which inhibits testability and makes a brittle, hard to test design. Now notice that our factory created a whole bunch of singletons as in a single instance of something . Also notice how those singletons got explicitly passed into the services that needed them. So if you need a singleton you simply create a single instance of it in the factory and than pass that instance into all of the components which need them. There is no need for the global variable.<br /><br />For example a common use of Singleton is for a DB connection pool. In our example you would simply instantiate a new DBConnectionPool class in the top-most factory (above) which is responsible for creating the long-lived objects. Now lets say that both CalculatorServlet and TimeServlet would need a connection pool. In that case we would simply pass the same instance of the DBConnectionPool into each of the places where it is needed. Notice we have a singleton (DBConnectionPool) but we don't have any global variables associated with that singleton.<br /><pre>  public Server buildServer() {<br />  Server server = new Server();<br /><br />  SocketConnector socketConnector<br />       = new SocketConnector();<br />  socketConnector.setPort(8080);<br />  server.addConnector(socketConnector);<br /><br />  <strong>DBConnectionPool pool = new DBConnectionPool();</strong><br />  new ServletBuilder(server)<br />    .addServlet("/calc", new CalculatorServlet(<br />                         <strong>pool</strong>,<br />                         new Calculator()))<br />    .addServlet("/time", new TimeServlet(<br />                         <strong>pool</strong>,<br />                         new Provider() {<br />      public Date get() {<br />        return new Date();<br />      }<br />    }));<br /><br />  return server;<br />}</pre><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-5787849677995901679?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/where-have-all-the-new-operators-gone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My main() Method Is Better Than Yours</title>
		<link>https://googledata.org/google-testing/my-main-method-is-better-than-yours/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=my-main-method-is-better-than-yours</link>
		<comments>https://googledata.org/google-testing/my-main-method-is-better-than-yours/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 17:52:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[By Miško HeveryPeople 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 co...]]></description>
				<content:encoded><![CDATA[By <a href="http://www.testabilityexplorer.org/about">Miško Hevery</a><br /><br />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't fit all of that into a single blog post ... So lets get started at the beginning...<br /><br />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>)<br /><pre>public static void main(String[] args)<br />  throws Exception {<br />    // Creation Phase<br />    Injector injector = Guice.createInjector(<br />             new CalculatorServerModule(args));<br />    Server server = injector.getInstance(Server.class);<br />    // Run Phase<br />    server.start();<br />}</pre><br />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>)<br /><pre>public static void main(String[] args)<br />  throws Exception {<br />    // Creation Phase<br />    Server server = new ServerFactory(args)<br />                               .createServer();<br />    // Run Phase<br />    server.start();<br />}</pre><br />The truth is I don'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'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.<br /><br />But the method is so short that I don't bother testing it since it has some really cool properties:<br /><ol><br /> <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><br /> <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><br /></ol><br />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!<br /><br />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'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't know how to test the main method. Main method is static and hence procedural. I don't know how to test procedural code since there is nothing to wire differently. I can't wire the call graph different in procedural world to prevent things from executing, the call graph is determined at compile time.<br /><br />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... 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...<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-3359446571524205832?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/my-main-method-is-better-than-yours/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Root Cause of Singletons</title>
		<link>https://googledata.org/google-testing/root-cause-of-singletons/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=root-cause-of-singletons</link>
		<comments>https://googledata.org/google-testing/root-cause-of-singletons/#comments</comments>
		<pubDate>Wed, 27 Aug 2008 16:37:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeverySince 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 pat...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />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.<br /><br />Lets get the definition right. There is Singleton the design pattern (Notice the capital "S" as in name of something) and there is a singleton as in one of something (notice the lower case "s"). 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.<br /><br />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 "Singletons are global state in sheep's clothing." Most developers agree that global state is bad, but they love their Singletons.<br /><br />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't have a Singleton design pattern and at the same time not have the global state.<br /><br />Someone pointed out that any design pattern can be abused. I agree, but with Singleton design pattern, I don'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'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.<br /><br />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't put state into your enumeration you are OK, so please don't.)<br /><br />The other kind of Singletons, which are semi-acceptable are those which don't effect the execution of your code, They have no "side effects". 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.<br /><br />So the root cause is "GLOBAL STATE!" 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 "the right way." 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.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-7342620331444175526?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/root-cause-of-singletons/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where Have All the Singletons Gone?</title>
		<link>https://googledata.org/google-testing/where-have-all-the-singletons-gone/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=where-have-all-the-singletons-gone</link>
		<comments>https://googledata.org/google-testing/where-have-all-the-singletons-gone/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 18:51:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryIn Singletons are Pathological Liars we discussed the problems of having singletons in your code. Let's build on that and answer the question "If I don't have singletons how do I ensure there is only one instance of X and how do I get X...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />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's build on that and answer the question "If I don'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?"<br /><br />An OO application is a graph of objects. There are three different kinds of graphs I think of when I design an application<br /><ol><br /> <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's fields)</li><br /> <li><strong>Construction Graph</strong>: This graph shows which object created which other ones.</li><br /> <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><br /></ol><br />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.<br /><br /><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 "instance" variable as in Singleton.getInstance().<br /><br />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.<br /><br />Now, in order to have a testable codebase we have to make sure that we don'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.<br /><br />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's a non-starter.)<br /><br />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" /><br /><br />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.)<br /><br />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.<br /><br />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.<br /><br />Important things to notice:<br /><ul><br /> <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><br /> <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><br /> <li>All of the new operators end up in the factories; application logic is devoid of new operators.</li><br /> <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><br /> <li>The problem of "how do I ensure that I only have one of something" 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><br /></ul><br /><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't actually have to write the factories.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-1337316089516682857?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/where-have-all-the-singletons-gone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singletons are Pathological Liars</title>
		<link>https://googledata.org/google-testing/singletons-are-pathological-liars/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=singletons-are-pathological-liars</link>
		<comments>https://googledata.org/google-testing/singletons-are-pathological-liars/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 17:44:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></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 explora...]]></description>
				<content:encoded><![CDATA[<p>by <a href="http://misko.hevery.com/2008/08/14/about/" mce_href="http://googletesting.blogspot.com/2008/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 "What happens if I execute this method" tests. You start by writing this:</p> <pre>testCreditCardCharge() {<br />CreditCard c =  new CreditCard(<br />  "1234 5678 9012 3456", 5, 2008);<br />c.charge(100);<br />}</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'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 "Spooky action at a distance!"</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() {<br />CreditCardProcessor.init();<br />CreditCard c =  new CreditCard(<br />  "1234 5678 9012 3456", 5, 2008);<br />c.charge(100);<br />}</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() {<br />OfflineQueue.init();<br />CreditCardProcessor.init();<br />CreditCard c =  new CreditCard(<br />  "1234 5678 9012 3456", 5, 2008);<br />c.charge(100);<br />}</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() {<br />Database.init();<br />OfflineQueue.init();<br />CreditCardProcessor.init();<br />CreditCard c =  new CreditCard(<br />  "1234 5678 9012 3456", 5, 2008);<br />c.charge(100);<br />}</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 "if not initialized then initialize" 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() {<br />CreditCardProcessor.init();<br />OfflineQueue.init();<br />CreditCard c =  new CreditCard(<br />  "1234 5678 9012 3456", 5, 2008);<br />c.charge(100);<br />Database.init();<br />}</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() {<br />Database db = Database();<br />OfflineQueue q = OfflineQueue(db);<br />CreditCardProcessor ccp = new CreditCardProcessor(q);<br />CreditCard c =  new CreditCard(<br />  "1234 5678 9012 3456", 5, 2008);<br />c.charge(ccp, 100);<br />}</pre> <p>Since the CreditCard charge method declares that it needs a CreditCardProcessor, I don'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'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><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-6689795822919924618?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/singletons-are-pathological-liars/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Testable Code</title>
		<link>https://googledata.org/google-testing/writing-testable-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=writing-testable-code</link>
		<comments>https://googledata.org/google-testing/writing-testable-code/#comments</comments>
		<pubDate>Wed, 06 Aug 2008 15:39:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeverySo you decided to finally give this testing thing a try. But somehow you just can'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...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />So you decided to finally give this testing thing a try. But somehow you just can'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, "I understand how to write tests for your code, but my code is different <em><insert></insert></em>". 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)<br /><ol><br /><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 "new" 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 "new" operators and are responsible for building the object graph of your application, but don't do anything. And the application logic classes which are devoid of the "new" 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 "new" 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="http://googletesting.blogspot.com/2008/07/how-to-think-about-new-operator-with.html">How to Think About the “new” Operator with Respect to Unit Testing</a>)</li><br /><li><strong>Ask for things, Don'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 "new" operator on those classes (see 1). Only ask for things you directly need, If you are a CarEngine, don't ask for FuelTank, only ask for Fuel. Don't pass in a context/registry/service-locator. So if you are a LoginPage, don't ask for UserContext, instead ask for the User and the Athenticator. Finally don't mix the responsibility of work with configuration, If you are an Authenticator class don'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="http://googletesting.blogspot.com/2008/07/breaking-law-of-demeter-is-like-looking.html">Breaking the Law of Demeter is Like Looking for a Needle in the Haystack</a><a href="http://googletesting.blogspot.com/2008/07/breaking-law-of-demeter-is-like-looking.html">)</a></li><br /><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><br /><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><br /><li><strong>Singletons (global state in sheep'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... 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.</li><br /><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 you 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'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't know how to unit-test the main method!</li><br /><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><br /><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><br /><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't need an interface. (Example: LinkedList, Map, User, EmailAddress, Email, CreditCard, etc...). (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 "new" 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'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><br /><li><strong>Mixing of Concerns</strong>: If summing up what the class does includes the word "and", or class would be challenging for new team members to read and quickly "get it", 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><br /></ol><br />So here is my top 10 list on testability, the trick is translating these abstract concepts into concrete decisions in your code.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-3023874871164884317?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/writing-testable-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Circular Dependency in constructors and Dependency Injection</title>
		<link>https://googledata.org/google-testing/circular-dependency-in-constructors-and-dependency-injection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=circular-dependency-in-constructors-and-dependency-injection</link>
		<comments>https://googledata.org/google-testing/circular-dependency-in-constructors-and-dependency-injection/#comments</comments>
		<pubDate>Thu, 31 Jul 2008 21:50:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeverySo you discovered dependency injection and GUICE and you are happily refactoring and writing new tests for you code until you come across this circular reference.class A {final B b;A(B b){  this.b = b;}}class B {final A a;B(){  this.a =...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/"><span class="blsp-spelling-error" id="SPELLING_ERROR_0">Miško</span> <span class="blsp-spelling-error" id="SPELLING_ERROR_1">Hevery</span></a><br /><br />So you discovered dependency injection and <a href="http://code.google.com/p/google-guice/"><span class="blsp-spelling-error" id="SPELLING_ERROR_2">GUICE</span></a> and you are happily <span class="blsp-spelling-error" id="SPELLING_ERROR_3">refactoring</span> and writing new tests for you code until you come across this circular reference.<br /><pre>class A {<br />final B b;<br />A(B b){<br />  this.b = b;<br />}<br />}<br /><br />class B {<br />final A a;<br />B(){<br />  this.a = new A(this);<br />}<br />}<br /><br />+---------+      +---------+<br />|    A    |<-----|    B    | |         |      |         | |         |----->|         |<br />+---------+      +---------+</pre><br />Hm, dependency injection says that you need to ask for your dependencies and so the resulting code will be:<br /><pre>class A {<br />final B b;<br />A(B b){<br />  this.b = b;<br />}<br />}<br /><br />class B {<br />final A a;<br />B(A a){<br />  this.a = a;<br />}<br />}</pre><br />But now we have a problem, we can't instantiate this (I know <span class="blsp-spelling-error" id="SPELLING_ERROR_5">GUICE</span> can through proxy, but it is not clean and it does not help us in tests). So the real problem in situation like this is mixing of concerns. One of the two objects is hiding another object C. Either A contains C or B contains C. To find out which one it is, <em><strong>list all of the methods in your class A and class B and. The shorter of the two lists is your hidden Class C.</strong></em><br /><pre>+---------+      +---------+<br />|    A    |<-----|  B      | |         |      |  |  +-+ | |         |      |  +->|C| |<br />|         |------+---->| | |<br />|         |      |     +-+ |<br />+---------+      +---------+</pre><br />Suppose B has the shorter list. We now extract all of the methods in B which are accessing the state of hidden C methods into a new object C like this:<br /><pre>                         +---------+<br />+---------+              |    B    |<br />|    A    |<-------------|         | |         |              |         | |         |    +---+     |         | |         |--->| C |<----|         | |         |    +---+     +---------+ +---------+ class C {  C(){  } }  class A {  final C c;  A(C c){    this.c = c;  } }  class B {  final A a;  final C c;  B(A a, C c){    this.a = a;    this.c = c;  } }</pre>When you go through this exercise you will realize that the C was always an object in its own right but you have never thought about it that way, so the new code is actually better <span class="blsp-spelling-error" id="SPELLING_ERROR_9">OO</span>. From testing point of view you can now test each class in isolation.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-7050115864048216306?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/circular-dependency-in-constructors-and-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Write 3v1L, Untestable Code</title>
		<link>https://googledata.org/google-testing/how-to-write-3v1l-untestable-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-write-3v1l-untestable-code</link>
		<comments>https://googledata.org/google-testing/how-to-write-3v1l-untestable-code/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 00:03:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško Hevery, Jonathan Wolter, Russ Ruffer, Brad Cross, and lots of other test infected GooglersThis 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...]]></description>
				<content:encoded><![CDATA[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<br /><br />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.<br /><ul><br /><li> <strong>Make Your Own Dependencies</strong> - Instantiate objects using new in the middle of methods, don'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'ed up. They can't "inject" a dummy, fake, or other mock in to simplify the behavior or make assertions about what you do to it.</li><br /><li> <strong>Heavy Duty Constructors</strong> - 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's even better! You want the transitive dependencies of every constructor to be enormous. Enormous is hard to get under test.</li><br /><li> <strong>Depend on Concrete Classes</strong> - Tie things down to concrete classes - avoid interfaces wherever possible. (They let people substitute the concrete classes you'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 - don't let them!)</li><br /><li> <strong>Conditional Slalom</strong> - 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're not consistently at least 5 conditionals deep, you're spoon feeding testable code to the TDD zealots.</li><br /><li> <strong>Depend on Large Context Objects</strong> - 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><br /><li> <strong>Use Statics</strong> - Statics, statics everywhere! They put a great big crunch in testability. They can't be mocked, and are a smell that you'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're being 3v1L!</li><br /><li> <strong>Use More Statics</strong> - Statics are a really powerful tool to bring TDD Infected engineers to their knees. Static methods can'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't be mocked using mocking libraries (nixing another trick up the pro-testing engineer's sleeve).</li><br /><li> <strong>Use Global Flags</strong> - Why call a method explicitly? Just like L Ron Hubbard, use "mind over matter" 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'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><br /><li> <strong>Use Singletons Everywhere</strong> - Why pass in a dependency and make it obvious when you can use a singleton? It'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's state.</li><br /><li> <strong>Be Defensive - They're out to Get Your Code!</strong> - Defensively assert about the state of parameters passed in methods, constructors, and mid-method. If someone can pass in a null, you'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's not paranoia if <em>they really are out to get you</em>.)</li><br /><li> <strong>Use Primitives Wherever Possible</strong> - Instead of using a "cookie object," 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 -- where objects are mockable (gasp) and nullable, and encapsulate state (who'd want to do that?)</li><br /><li> <strong>Look for Everything You Need</strong> - 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'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/" >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/" >Law of Demeter</a>, or not looking for things.</li><br /><li> <strong>Use static initializes</strong> - 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><br /><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't intend, (like small tests that run in 2 ms instead of 5 minutes).</li><br /><li> <strong>Mix Object Lifecycles</strong> - Have long lived objects reference short lived objects. This confuses people as the long lived object references the short lived object still after it'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><br /><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's or NPE's, depending on your language's vernacular. Why go to all this trouble? Clean, readable, and testable code that works, that'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><br /><li> <strong>Create Utility Classes and Functions/Methods</strong> - For instance, you have a String which is a URL you're passing around (obeying "Use Primitives Wherever Possible"). Create another class with static methods such as isValidUrl(String url). Don'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's even better!</li><br /><li> <strong>Create Managers and Controllers</strong> - all over the place have these Managers and Controllers meddling in the responsibilities of other objects. Don't bother trying to pull that responsibility into other individual objects. Look at a SomeObjectManager class and you have no idea what it's going to do.</li><br /><li> <strong>Do Complicated Creation Work in Objects</strong> - Whenever someone suggests you to use a Factory to instantiate things, know that you are smarter than them. You're more intelligent than they must be, because your objects can have multiple responsibilities and be thousands of lines long.</li><br /><li> <strong>Greenlight if-branches and switch statements</strong> - Go ahead, don't feel dirty about nesting if-branches. It's "more readable" 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's like a terrible choose-your-own-adventure kid's book. You're constantly flipping between classes and juggling patterns and so many more complex concepts. Just if-things out and you'll be fine.</li><br /><li> <strong>Utils, Utils, Utils!</strong> - Code smell? No way - 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's code reuse, and good for everyone, right? Be forewarned, the OO-police will say that functionality belongs in some object, as that object's responsibility. Forget it, you're way to pragmatic to break things down like they want. You've got a product to ship after all!</li><br /><li> <strong>Use "Refactoring" whenever you need to get away with something</strong> - 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're "Refactoring." It'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<br /></h3><ul><li> <strong>Final Methods</strong> - Use final classes and methods all the time. They can't be overridden for testing (-; But don't bother making fields final, or using value objects (without setters) - just let your objects' state be changed by anything and anyone. No sense in guaranteeing state, it'd make things too easy.</li><br /><li> <strong>Handcuff your users to Specific Types</strong> - Use <code>instanceof</code> as much as possible. This will make Mocking a pain, and show people that you're in control of the objects allowed.</li></ul><h3>C++ Specific</h3><ul><li> <strong>Use non-virtual methods</strong> - 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 - then when the testing freaks try to subclass, whooooaoaaaaaa....</li><br /><li> <strong>Never use pure abstract classes</strong> - 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><br /><li> <strong>Macros are your friends</strong> - Always use <code>#ifdef PROD</code> and other compile-time switches to make sure the testies can't get at your really important blocks of code and test them. In fact, this code won't even run: until it gets to production!</li><br /></ul><div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-1997301458069663637?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/how-to-write-3v1l-untestable-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Breaking the Law of Demeter is Like Looking for a Needle in the Haystack</title>
		<link>https://googledata.org/google-testing/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack</link>
		<comments>https://googledata.org/google-testing/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/#comments</comments>
		<pubDate>Mon, 21 Jul 2008 22:31:00 +0000</pubDate>
		<dc:creator><![CDATA[Misko]]></dc:creator>
				<category><![CDATA[Google Testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[by Miško HeveryEvery time I see Law of Demeter violation I imagine a haystack where the code is desperately trying to locate the needle.class Mechanic {Engine engine;Mechanic(Context context) {  this.engine = context.getEngine();}}The Mechanic does no...]]></description>
				<content:encoded><![CDATA[by <a href="http://misko.hevery.com/about/">Miško Hevery</a><br /><br />Every time I see <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" >Law of Demeter</a> violation I imagine a haystack where the code is desperately trying to locate the needle.<br /><pre class="code">class Mechanic {<br />Engine engine;<br />Mechanic(Context context) {<br />  this.engine = context.getEngine();<br />}<br />}</pre><br />The <tt>Mechanic</tt> does not care for the <tt>Context</tt>. You can tell because <tt>Mechanic</tt> does not store the reference to <tt>Context</tt>. Instead the <tt>Mechanic</tt> traverses the <tt>Context</tt> and looks for what it really needs, the <tt>Engine</tt>.  So what is wrong with code like this you say? The problems with such code are very subtle:<br /><ul><br /><li>Most applications tend to have some sort of <tt>Context</tt> object which is the kitchen sink and which can get you just about any other object in the system aka the service locator.</li><br /><li>If you want to reuse this code at a different project, the compiler will not only need <tt>Mechanic</tt> and <tt>Engine</tt> but also the <tt>Context</tt>. But <tt>Context</tt> is the kitchen sink of your application. It tends to have reference to just about every other class in your system, hence the compiler will need those classes too. This kind of code is not very reusable.</li><br /><li>Even if you don't plan to reuse the code, the <tt>Context</tt> has high coupling with the rest of the system. Coupling is transitive, this means <tt>Mechanic</tt> inherits all of the badness through association.</li><br /><li>Your JavaDoc is not very useful! Yes, by examining the API I can see that the Mechanic needs <tt>Context</tt>, but <tt>Context</tt> is the kitchen sink. What does the mechanic really need? (If you don't have source code nearby than it may be hard to figure out).</li><br /></ul><br /><div style="margin: 5px 5pt 5px 5px; display: inline; float: right;"><img class="alignright size-medium wp-image-100" style="border: 1px solid black; margin-right: 5px; margin-left: 5px;" title="needle" src="http://misko.hevery.com/wp-content/uploads/2008/07/needle-200x300.jpg" alt="" width="96" height="144" /></div><br />But here is the real killer! Writing tests for such code base sucks!<br /><ul><br /><li>Every time I have to write a test I have to create a graph of objects (the haystack) which no one really needs or cares for, and into this haystack I have to carefully place the needles (the real object of interests) so that the code under test can go and look for them. I have to create the <tt>Context</tt> just so when I construct the <tt>Mechanic</tt> it can reach in the <tt>Context</tt> and get what it realy needs, the <tt>Engine</tt>. But context is never something which is easy to create. Since context is a kitchen sink which knows just about everything else, its constructor is usually scary. So most of the time I can't even instantiate Mechanic, not to mention run any tests on it. The testing game is over before it even started.</li><br /><li>Ok, but today we have fancy tools such as <a href="http://jmock.org/" >JMock</a> and <a href="http://www.easymock.org/" >EasyMock</a>, surely i can mock out <tt>Context</tt>. Yes, you can! BUT: (1) typical setup of a mock is about 5 lines of code. So your test will contain a lot of junk which will mask the real purpose of the test. (2) These tests will be fragile. Every time you refactor something in context, or how context interacts, you are running the risk of breaking your tests. (False negatives) (3) What if you want to test class <tt>Shop</tt> which needs a reference to <tt>Mechanic</tt>? Well then you have to mock out <tt>Context</tt> again. This mocking tax will be spread all over your tests. In the end the mocking setup will drown out your tests and make for one unreadable test base.</li><br /></ul><br />Please stop looking for the needle in the haystack and just ask for the things you directly need in your code. You will thank me later...<br /><pre>class Mechanic {<br />Engine engine;<br />Mechanic(Engine engine) {<br />  this.engine = engine;<br />}<br />}</pre><br />PS: Now imagine how hard will it be to write a test for this class:<br /><pre class="code">class Monitor {<br />SparkPlug sparkPlug;<br />Monitor(Context context) {<br />  this.sparkPlug = context.<br />        getCar().getEngine().<br />        getPiston().getSparkPlug();<br />}<br />}</pre><br />GOOD LUCK!<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/15045980-276719960416223477?l=googletesting.blogspot.com' alt='' /></div>]]></content:encoded>
			<wfw:commentRss>https://googledata.org/google-testing/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
