<?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>{(something&#124;&#124;other).soft()} &#187; tdd</title>
	<atom:link href="http://www.somethingorothersoft.com/tag/tdd/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.somethingorothersoft.com</link>
	<description>About Software Development And Other Stuff By Igor Zevaka</description>
	<lastBuildDate>Tue, 17 Aug 2010 00:42:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Unit Tests As A Refactoring Tool</title>
		<link>http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/</link>
		<comments>http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/#comments</comments>
		<pubDate>Sat, 20 Feb 2010 07:23:34 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[unit-testing]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=283</guid>
		<description><![CDATA[So I have this class that is a bit too fat and has no unit tests. It&#8217;s way overdue for a clean up. I thought I would investigate how to refactor with unit tests. Application The application in question is a fairly normal case of a business DSL where the domain rules are expressed in <a href="http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>So I have this class that is a bit too fat and has no unit tests. It&#8217;s way overdue for a clean up. I thought I would investigate how to refactor with unit tests.</p>

<h3>Application</h3>

<p>The application in question is a fairly normal case of a business DSL where the domain rules are expressed in XML and the compiler generates an application for different platforms (web, mobile web, PDA, WPF). Code is written in C#, tested with MbUnit v.3 and NMock2.</p>

<p>This particular class parses XML and generates JSON to be later consumed by ExtJS library. The JSON is a declaritive form of the control that users will eventually see. This control is complicated and has many options. Hence the fatness.</p>

<h3>Enter the unit tests</h3>

<p>Now, unit tests are touted to be great for refactoring. They are. The usual approach is to write the tests, make sure they pass, then refactor and make sure the tests don&#8217;t break. Well, I want to take it one step further and let the writing of the tests guide the refactoring.</p>

<p>Thoroughly unit tested code tends to have really good code smells. This is mainly due to fact that in order to test all aspects of a large block of code, you must isolate all of its constituents. This is evident in all projects that are written in a TDD way. They are all very modular and modular is good(I think :-) ).</p>

<p>So my goal here is just simply write the unit tests and see where it takes me. I would imagine that just by making the code testable, it will become a little bit better.</p>

<p>I never invisaged this to become a full blown article, but now that I am here, lets introduce some numbers to make this more scientific. I will be using Microsoft Team Studio Analysis Tools throughout the process. Here is a snapshot of what the class looks like at the start:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/start.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/start.png" alt="" title="start" width="808" height="173" class="alignnone size-full wp-image-284" /></a></p>

<p>As you can see the <code>Build</code> method is too big &#8211; 250 lines. This is bad. It&#8217;s one of those <code>DoIt</code> methods that does everything.</p>

<h3>First refactor</h3>

<p>Alright, lets get cranking. Straight away I noticed that I was reading a particular bit of XML and making decisions based on the node contents. This particular functionality has already been abstracted away in another class, so I might as well use that class. So I just refactored that without writing any tests before or after. That&#8217;s pretty naughty :)) Lets make it proper and rip this code into another function so we can test it.</p>

<p>Starting from the top of the method I am looking at a bit of code that parses an atribute and calls a method that is defined in the base class depending on whether or not the attribute exists.</p>

<h3>Base class dependency</h3>

<p>Now refactoring that into a method is not a problem, the problem is isolating the call to the base class. There is case to be made for having the base class contain all the dependencies that are required for all of its subclasses, however, just by skimming the code it looks like a lot of the methods there are simply in one place for convinience. So this could potentially be a case of Inheritance vs. Composition. Lets start off by abstracting  this particular method into an interface and have our base derive from the interface. Then in our derived class we access that method through a reference to the interface, not implicitly.</p>

<p>This is what it looks like now:</p>

<div>
<pre class="brush: csharp;">
class Builder {
   public DoStuff(string blah){
      //impl
   }
}

class GridBuilder : Builder{
   public void Build() {
      var elem = Element.GetAttribute(&quot;Blah&quot;);
      DoStuff(blah);
   }
}
</pre>
</div>

<p>Let&#8217;s tweak it as described in the previous paragraph:</p>

<div>
<pre class="brush: csharp;">
interface IBuilder {
    DoStuff(string blah);
}

[code lang=&quot;csharp&quot;]
class Builder : IBuilder {
   [Obsolete]
   public DoStuff(string blah){
      //impl
   }
}

class GridBuilder {
   
   IBuilder _Builder;
   
   public GridBuilder() {
     _Builder = this;
   }
   
   public GridBuilder(IClientBuilder b) {
            m_ClientBuilder = b;
    }
   
   public void Build() {
      var elem = Element.GetAttribute(&quot;Blah&quot;);
      _Builder = DoStuff(blah);
   }
}
</pre>
</div>

<p>So what I have done is put that <code>DoStuff</code> into an interface and marked the implementation as Obolete. This is more out of convinience to get the compiler to show me where else this method is being used. Turns out this was the only case where it was used in <code>GridBuilder</code>. I could have just as well used text search, but hey, if there is a fancy compiler feature, why not use it? Notice that I also added a dependency constructor so I can compose <code>GridBuilder</code> in a unit test.</p>

<p>Let's make a unit test for this use of <code>DoStuff</code>. As I am doing that I realised that my base class is in a different assembly and required some code duplication from another test project to make the test not crash. The fact that I had to do that is a pretty bad, but my copying the common setup file and including it in my test project is even worse. We can come back to that later, lets concentrate on what we are doing now. Might as well use the <code>Obsolete</code> attribute to remind me to refactor the unit test later on.</p>

<h3>Finally, I can test <code>Build</code></h3>

<p>So, after a long time setting up <code>GridBuilder</code>'s dependencies I am finally here - the test runs. Lets review what I've achieved so far and have a peek at the metrics. So here is the summary of what was required just to make the test run:</p>

<ul>
<li>Two instances of referring to the base class have been abstractes into two interfaces.</li>
<li>Found a bug where if a required element is present but contains no nodes the builder crashes.</li>
<li>The test creates a total of three mock objects with a total of five <code>Stubs</code> and one <code>Expect</code>.</li>
<li>The test needs to pass in an Xml element with two elements and one atribute.</li>
<li>Found a small refactoring job that is not really related to the unit testing aspect of this excercise.</li>
</ul>

<p>Code metrics:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step1.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step1.png" alt="" title="step1" width="954" height="210" class="alignnone size-full wp-image-286" /></a></p>

<p>So I didn't get anywhere as far as most metrics are concerned, in fact I almost went backwards, if anything. Let's keep going. So now I have a unit test that runs the <code>Build</code> method lets keep trying to test more and more parts of it.</p>

<p>Before I go on, I would like to emphasize the fact that I had to create lots of mocks and pass in lots of dependencies just to make one method not crash. Here is the unit test. Definitely too much for ONE method:</p>

<div>
<pre class="brush: csharp;">

        [SetUp]
        public void Setup() {
            m_Mocks = new Mockery();
            m_Settings = new InlineBuilderSettings {
                Compiler = m_Mocks.NewMock&lt;IWebCompiler&gt;(),
                ComponentName = &quot;Test&quot;
            };
            //Used by setup method
            Stub.On(m_Settings.Compiler).GetProperty(&quot;ServerCompiler&quot;).Will(Return.Value(null));
            Stub.On(m_Settings.Compiler).GetProperty(&quot;ServerType&quot;).Will(Return.Value(typeof(Data.ServerAplication)));
        }
        
        [Test]
        public void BuildShouldCallRequireComponentWhenViewAttribute() {

            var iClientBuilder = m_Mocks.NewMock&lt;IClientBuilder&gt;();
            var iBuilder = m_Mocks.NewMock&lt;IWebBuilder&gt;();

            Builder builder = new Builder(iClientBuilder, iBuilder);
            m_Settings.Element = 
                new XElement(&quot;Grid&quot;, new XAttribute(&quot;View&quot;, &quot;test&quot;), 
                    new XElement(&quot;Source&quot;, new XAttribute(&quot;View&quot;, &quot;DataTest&quot;)),
                    new XElement(&quot;Fields&quot;));

            Expect.Once.On(iClientBuilder).Method(&quot;RequireComponent&quot;).With(&quot;test&quot;, m_Settings.Element).Will();
            Stub.On(iClientBuilder).Method(&quot;GetComponentInfo&quot;).Will(Return.Value(new ComponentInfo()));
            Stub.On(iBuilder).Method(&quot;AddConfig&quot;).Will();
            Stub.On(m_Settings.Compiler).Method(&quot;AddInclude&quot;).Will();
            
            builder.Setup(m_Settings);
            builder.Build();
        }
</pre>
</div>

<p>Realistically, in order to complete the build process we need all those dependencies. That's pretty fundamental. However, it should be possible to reduce the amount of dependencies ONE method has.</p>

<h3>Next refactor</h3>

<p>My next target was a reasonably self contained code block that I did "Extract Method" method on. Two more unit tests. Slight improvement in maintainability and complexity.</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step2.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step2.png" alt="" title="step2" width="996" height="236" class="alignnone size-full wp-image-287" /></a></p>

<p>Next one is a big sucker. This block produces about 5 output objects that are dumped to JSON later on. I actually moved to another two classes. One to perform the build and another to store the output.</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step3.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step3.png" alt="" title="step3" width="896" height="236" class="alignnone size-full wp-image-288" /></a></p>

<p>Good improvement on all counts. Lets keep splitting the Build method and writing tests for it. As I am doing this I decided to make the GridBuilder a namespace within a project. There are a number of classes in it by now, might as well contain them in a folder.</p>

<h3>Day later.</h3>

<p>I have somewhat abandoned refactoring GridBuilder as I found a whole bunch of other tightly coupled classes. The unit tests have proven to be a great tool exposing those dependencies. They also become usefull when the refactoring becomes non-trivial - i.e. goes beyond just moving a block of code out of a method.</p>

<p>This is what the class looked like once I finished with it:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step4.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step4.png" alt="" title="step4" width="975" height="230" class="alignnone size-full wp-image-289" /></a></p>

<p>Now that I ran out of time that I gave myself for this task I think I have a few notes for future.</p>

<ul>
<li>Parsing an XML collection is ugly and tends to get messy when things need to be addded to the inner loop. I think for this scenario I would need some sort of visitor pattern implemented so that you could add things to the inner loop without having to alter the loop itself.</li>
<li>Having implicit dependencies (like a dependency on a property of an actual dependency) totally breaks the unit tests. A situation where you create one mock and then have its method return another mock is a bit ridiculous.</li>
<li>A unit test for a monstrous method will too be monstrous. There is almost 1-to-1 relationship between how fat the method is and how fat its unit test is. I think that if one aims to make unit test simpler, the code under test will in turn become simpler.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Test Driven Development</title>
		<link>http://www.somethingorothersoft.com/2009/08/01/test-driven-development/</link>
		<comments>http://www.somethingorothersoft.com/2009/08/01/test-driven-development/#comments</comments>
		<pubDate>Sat, 01 Aug 2009 05:14:20 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=37</guid>
		<description><![CDATA[I heard a lot of buzz about test driven development. All that time I thought that all that means is writing unit tests. Then I found out about writing tests before writing code. Meh, I thought, no big deal, a bit fussy if you ask me, it still hasn&#8217;t changed my view on the whole <a href="http://www.somethingorothersoft.com/2009/08/01/test-driven-development/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I heard a lot of buzz about test driven development. All that time I thought that all that means is writing unit tests. Then I found out about writing tests before writing code. Meh, I thought, no big deal, a bit fussy if you ask me, it still hasn&#8217;t changed my view on the whole thing.</p>

<p>Then recently I saw some unit tests in a Microsoft article talking about using TDD to create web controls using Model-View-Presenter paradigm. The article itself can be found here <a href="http://msdn.microsoft.com/en-us/magazine/cc188690.aspx">http://msdn.microsoft.com/en-us/magazine/cc188690.aspx</a>.</p>

<p>Its crazy! You write twice as much code! Not only that, you have to use this framework to create mock objects and test methods on the interfaces before even writing them (tests before code, doh).</p>

<p>Having said that, I am willing to give TDD for really just one reason. And the reason is that writing tests that independently test the two halves (e.g. View and Presenter) makes you think upfront about the design of the two interfaces a bit more. This, in turn, precipitates the right design faster, without having to write a lot of either UI or business logic code.</p>

<p>The long  term advantage is quite obvious and is comes from both Separation Of Concerns principles (whatever shape they come in &#8211; MVP, MVC, MVV, MVA) and having unit tests. In some time, if there is a need to rewrite the implementation of any part of the system, the interfaces between them are loosely coupled and testable. The latter, in my opinion, is even more important than the former. Having a testable interface will aid finding the problems in the new implementation more than a &#8220;beautifully&#8221; designed one.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2009/08/01/test-driven-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
