<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[The Code Whisperer]]></title>
  <link href="http://blog.thecodewhisperer.com/atom.xml" rel="self"/>
  <link href="http://blog.thecodewhisperer.com/"/>
  <updated>2012-02-19T15:34:13+02:00</updated>
  <id>http://blog.thecodewhisperer.com/</id>
  <author>
    <name><![CDATA[J. B. Rainsberger]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[10 Ways to Kill Your Design]]></title>
    <link href="http://blog.thecodewhisperer.com/2012/02/19/ten-ways-to-kill-your-design/"/>
    <updated>2012-02-19T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2012/02/19/ten-ways-to-kill-your-design</id>
    <content type="html"><![CDATA[<p>I wish that I could take credit for this article, but I can’t. Instead, I have to credit two people: <a href="http://www.twitter.com/#!/lassekoskela">Lasse Koskela</a> and <a href="http://twitter.com/#!/mhevery">Miško Hevery</a>. I credit Lasse for writing the manuscript that led me to Miško’s article. Look for Lasse’s upcoming book <em>Unit Testing in Java</em> <a href="http://manning.com/koskela2/">at Manning Publications’ site</a>. Let me summarise Miško’s article here, then you can read the details at <a href="http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/">his blog</a>.</p>

<p>Why would I simply summarise someone else’s article on this site? Isn’t that dishonest? Not in this case: Miško wrote essentially the same thing that I say over and over again in my own articles and in my training classes. I consider it unfortunate that he and I have never met nor worked together. We really should. You should read his stuff.</p>

<p>So… 10 ways to kill your design.</p>

<ol>
  <li>Instantiate <a href="http://link.jbrains.ca/yuGPqe">Services</a> wherever the hell you want.</li>
  <li>Grab what you want when you want it.</li>
  <li>Do real work in your constructors.</li>
  <li>Publicise state.</li>
  <li>Embrace singletons.</li>
  <li>Make methods <code>static</code>. (Admittedly, this is more of a problem in Java/C# than Ruby/Python.)</li>
  <li>Inherit implementation.</li>
  <li>Reimplement polymorphism.</li>
  <li>Mix <a href="http://link.jbrains.ca/yuGPqe">Services and Values</a>.</li>
  <li>Keep <a href="http://dictionary.reference.com/browse/conjunction">conjunctions</a> in your variable, method and class names.</li>
</ol>

<p><a href="http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/">Read more about the problems that these “techniques” cause</a>.</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[From dependent tests to independent tests to independent assertions]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/12/20/from-dependent-tests-to-independent-tests-to-independent-assertions/"/>
    <updated>2011-12-20T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/12/20/from-dependent-tests-to-independent-tests-to-independent-assertions</id>
    <content type="html"><![CDATA[<p><span style="float: right; margin-left: 10px; margin-bottom: 10px; width: 3cm"><img src="http://blog.thecodewhisperer.com/images/dhemery-small.jpg" alt="Dale Emery" /></span>
[We might choose to] write tests so that a failure in a predecessor test causes dependent tests not to execute. In object tests, we do this by writing a test method with multiple assertions. – Dale Emery</p>

<p>When multiple assertions check very tightly related things, I don’t mind them, but when they check relatively loosely related things, they act as integrated tests for multiple behaviors that we should consider separating. This is even subtler than the simpler idea of “one action per test”.</p>

<p>If you’d like a <strong>Novice algorithm</strong> to follow:</p>

<ol>
  <li>Look for any test with multiple assertions.</li>
  <li>Move those assertions to the bottom of the test. (If they aren’t already at the bottom, then you might have more than one action per test; this refactoring will help you discover that.)</li>
  <li>Extract all the assertions together into a single method.</li>
</ol>

<p>Now look at the new method. How many different objects does the method use?</p>

<p>If it’s more than one, then you almost certainly have unrelated assertions in the same place, so consider splitting the unrelated assertions into separate methods, then split the test into two so that each test invokes one of the two new separated assertion methods.</p>

<p>If your new assertion method uses only one object, then it might not be so clear whether those assertions are related. You can try this simple test: put all the values you’re checking in your assertions into a single object. Can you think of a good name for it? If yes, then perhaps you’ve just identified a missing abstraction in your system; and if not, then perhaps the assertions have too little to do with each other, in which case, try the trick in the preceding paragraph.</p>

<p>I apologise for not having a good example of this right now. If you point me to one, I’ll analyse it in this space.</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Stop. Write a Learning Test.]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/12/14/when-to-write-learning-tests/"/>
    <updated>2011-12-14T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/12/14/when-to-write-learning-tests</id>
    <content type="html"><![CDATA[<h1 id="the-30-second-version">The 30-second version</h1>

<ul>
  <li><a href="http://www.google.com/search?q=yak+shaving">Where did that yak come from?</a></li>
  <li>When you try to learn a new library at the same time as explore the behavior and design of your application, you slow down more than you think.</li>
  <li>When you can’t figure out how to make the new library work for this thing you want to build, you might spend hours fighting, debugging, swearing.</li>
</ul>

<p>Stop. Write a Learning Test.</p>

<ol>
  <li>Start a new test suite, test class, spec file, whatever you want to call it.</li>
  <li>Write a test that checks the things you tried to check earlier with debug statements.</li>
  <li>Write a test that has nothing to do with your application and its domain.</li>
  <li>Remove unnecessary details from your test.</li>
</ol>

<p>When this test passes, then you understand what that part of the library does. If it behaves strangely, then you have the perfect test to send to the maintainers of the library.<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup></p>

<h1 id="the-details">The Details</h1>

<p>I just did this on a project using the context-free grammar parser <a href="https://github.com/nathansobo/treetop"><em>treetop</em></a>. Of course, I hadn’t used <em>treetop</em> before, so I had to learn it at the same time as design the grammar for the language I wanted to parse. I reached the point where I couldn’t write a <em>grammar rule</em> correctly, and spent probably an hour trying to figure out get it to work.<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup> Fortunately, at that moment, my laptop ran out of power, so I left the coffee shop<sup id="fnref:3"><a href="#fn:3" rel="footnote">3</a></sup> and did the usual thing: <a href="http://c2.com/cgi/wiki?RubberDucking">I explained the problem to my wife so that I could hear myself doing that</a>. After about 15 minutes away from the problem, I decided to write some <a href="http://c2.com/cgi/wiki?LearningTest">Learning Tests</a>.</p>

<h1 id="summary-of-what-i-did">Summary of what I did</h1>

<ol>
  <li>I wrote a Learning Test for a simple case that I thought I already understood well.</li>
  <li>I wrote a Learning Test similar to the problem I had to deal with, to make sure I understood <em>that</em> well.</li>
  <li>I wrote a Learning Test for the exact case that behaved unexpectedly.</li>
</ol>

<p>The whole thing took an hour, and I understood the problem well enough to explain it to my wife. She understood it and agreed that it sounded like a mistake in the library.<sup id="fnref:4"><a href="#fn:4" rel="footnote">4</a></sup> I used this Learning Test to open an issue at github. Now I can proceed without pulling my own hair out.</p>

<h1 id="do-you-want-to-see-the-learning-tests">Do you want to see the Learning Tests?</h1>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span>The case I already understood well  (single_simple_rule_spec.rb)</span> <a href="http://blog.thecodewhisperer.com/_code//learning_tests/single_simple_rule_spec.rb">download</a></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
<span class="line-number">13</span>
<span class="line-number">14</span>
<span class="line-number">15</span>
<span class="line-number">16</span>
<span class="line-number">17</span>
<span class="line-number">18</span>
<span class="line-number">19</span>
<span class="line-number">20</span>
<span class="line-number">21</span>
<span class="line-number">22</span>
<span class="line-number">23</span>
<span class="line-number">24</span>
<span class="line-number">25</span>
<span class="line-number">26</span>
<span class="line-number">27</span>
<span class="line-number">28</span>
<span class="line-number">29</span>
<span class="line-number">30</span>
<span class="line-number">31</span>
<span class="line-number">32</span>
<span class="line-number">33</span>
<span class="line-number">34</span>
<span class="line-number">35</span>
<span class="line-number">36</span>
<span class="line-number">37</span>
</pre></td><td class="code"><pre><code class="ruby"><span class="line"><span class="nb">require</span> <span class="s1">&#39;treetop&#39;</span>
</span><span class="line">
</span><span class="line"><span class="n">describe</span> <span class="s2">&quot;Grammar with a simple rule&quot;</span> <span class="k">do</span>
</span><span class="line">  <span class="n">let</span><span class="p">(</span><span class="ss">:subject</span><span class="p">)</span> <span class="p">{</span> <span class="no">Treetop</span><span class="o">.</span><span class="n">load_from_string</span><span class="p">(</span>
</span><span class="line"><span class="o">&lt;&lt;</span><span class="no">GRAMMAR</span>
</span><span class="line"><span class="sh">grammar SimpleRule</span>
</span><span class="line"><span class="sh">  rule word</span>
</span><span class="line"><span class="sh">    [A-Za-z]+</span>
</span><span class="line"><span class="sh">  end</span>
</span><span class="line"><span class="sh">end</span>
</span><span class="line"><span class="no">GRAMMAR</span>
</span><span class="line">  <span class="p">)}</span>
</span><span class="line">
</span><span class="line">  <span class="n">let</span> <span class="p">(</span><span class="ss">:parser</span><span class="p">)</span> <span class="p">{</span> <span class="n">subject</span><span class="o">.</span><span class="n">new</span> <span class="p">}</span>
</span><span class="line">
</span><span class="line">  <span class="n">it</span> <span class="s2">&quot;doesn&#39;t match empty string&quot;</span> <span class="k">do</span>
</span><span class="line">    <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">should</span> <span class="n">be_false</span>
</span><span class="line">  <span class="k">end</span>
</span><span class="line">
</span><span class="line">  <span class="n">context</span> <span class="s2">&quot;matching single letter, the match result&quot;</span> <span class="k">do</span>
</span><span class="line">    <span class="n">let</span><span class="p">(</span><span class="ss">:result</span><span class="p">)</span> <span class="p">{</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">)</span> <span class="p">}</span>
</span><span class="line">
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">should</span> <span class="n">be_true</span> <span class="p">}</span>
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">text_value</span><span class="o">.</span><span class="n">should</span> <span class="o">==</span> <span class="s2">&quot;a&quot;</span> <span class="p">}</span>
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">to_s</span><span class="o">.</span><span class="n">should_not</span> <span class="o">==</span> <span class="s2">&quot;a&quot;</span> <span class="p">}</span>
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">should_not</span> <span class="n">respond_to</span><span class="p">(</span><span class="ss">:word</span><span class="p">)</span> <span class="p">}</span>
</span><span class="line">  <span class="k">end</span>
</span><span class="line">
</span><span class="line">  <span class="n">context</span> <span class="s2">&quot;matching many letters, the match result&quot;</span> <span class="k">do</span>
</span><span class="line">    <span class="n">let</span><span class="p">(</span><span class="ss">:result</span><span class="p">)</span> <span class="p">{</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;aBcDeF&quot;</span><span class="p">)</span> <span class="p">}</span>
</span><span class="line">
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">should</span> <span class="n">be_true</span> <span class="p">}</span>
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">text_value</span><span class="o">.</span><span class="n">should</span> <span class="o">==</span> <span class="s2">&quot;aBcDeF&quot;</span> <span class="p">}</span>
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">to_s</span><span class="o">.</span><span class="n">should_not</span> <span class="o">==</span> <span class="s2">&quot;aBcDeF&quot;</span> <span class="p">}</span>
</span><span class="line">    <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">should_not</span> <span class="n">respond_to</span><span class="p">(</span><span class="ss">:word</span><span class="p">)</span> <span class="p">}</span>
</span><span class="line">  <span class="k">end</span>
</span><span class="line"><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span>The cases I wasn&#8217;t sure I understood  (single_rule_using_labels_spec.rb)</span> <a href="http://blog.thecodewhisperer.com/_code//learning_tests/single_rule_using_labels_spec.rb">download</a></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
<span class="line-number">13</span>
<span class="line-number">14</span>
<span class="line-number">15</span>
<span class="line-number">16</span>
<span class="line-number">17</span>
<span class="line-number">18</span>
<span class="line-number">19</span>
<span class="line-number">20</span>
<span class="line-number">21</span>
<span class="line-number">22</span>
<span class="line-number">23</span>
<span class="line-number">24</span>
<span class="line-number">25</span>
<span class="line-number">26</span>
<span class="line-number">27</span>
<span class="line-number">28</span>
<span class="line-number">29</span>
<span class="line-number">30</span>
<span class="line-number">31</span>
<span class="line-number">32</span>
<span class="line-number">33</span>
<span class="line-number">34</span>
<span class="line-number">35</span>
<span class="line-number">36</span>
<span class="line-number">37</span>
<span class="line-number">38</span>
<span class="line-number">39</span>
<span class="line-number">40</span>
<span class="line-number">41</span>
<span class="line-number">42</span>
<span class="line-number">43</span>
</pre></td><td class="code"><pre><code class="ruby"><span class="line"><span class="nb">require</span> <span class="s1">&#39;treetop&#39;</span>
</span><span class="line">
</span><span class="line"><span class="n">describe</span> <span class="s2">&quot;Grammar with a simple rule that uses a label&quot;</span> <span class="k">do</span>
</span><span class="line">  <span class="n">context</span> <span class="s2">&quot;Labeled subexpression followed by another expression&quot;</span> <span class="k">do</span>
</span><span class="line">    <span class="n">let</span><span class="p">(</span><span class="ss">:subject</span><span class="p">)</span> <span class="p">{</span> <span class="no">Treetop</span><span class="o">.</span><span class="n">load_from_string</span><span class="p">(</span>
</span><span class="line"><span class="o">&lt;&lt;</span><span class="no">GRAMMAR</span>
</span><span class="line"><span class="sh">grammar SimpleRuleWithLabel</span>
</span><span class="line"><span class="sh">  rule word</span>
</span><span class="line"><span class="sh">    letters:[A-Za-z]+ [A-Za-z]*</span>
</span><span class="line"><span class="sh">  end</span>
</span><span class="line"><span class="sh">end</span>
</span><span class="line"><span class="no">GRAMMAR</span>
</span><span class="line">    <span class="p">)}</span>
</span><span class="line">
</span><span class="line">    <span class="n">let</span> <span class="p">(</span><span class="ss">:parser</span><span class="p">)</span> <span class="p">{</span> <span class="n">subject</span><span class="o">.</span><span class="n">new</span> <span class="p">}</span>
</span><span class="line">
</span><span class="line">    <span class="n">context</span> <span class="s2">&quot;matching many letters, the match result&quot;</span> <span class="k">do</span>
</span><span class="line">      <span class="n">let</span><span class="p">(</span><span class="ss">:result</span><span class="p">)</span> <span class="p">{</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;aBcDeF&quot;</span><span class="p">)</span> <span class="p">}</span>
</span><span class="line">
</span><span class="line">      <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">should</span> <span class="n">respond_to</span><span class="p">(</span><span class="ss">:letters</span><span class="p">)</span> <span class="p">}</span>
</span><span class="line">      <span class="n">it</span> <span class="p">{</span> <span class="n">result</span><span class="o">.</span><span class="n">letters</span><span class="o">.</span><span class="n">text_value</span><span class="o">.</span><span class="n">should</span> <span class="o">==</span> <span class="s2">&quot;aBcDeF&quot;</span> <span class="p">}</span>
</span><span class="line">    <span class="k">end</span>
</span><span class="line">  <span class="k">end</span>
</span><span class="line">
</span><span class="line">  <span class="n">context</span> <span class="s2">&quot;Labeled subexpression without another expression&quot;</span> <span class="k">do</span>
</span><span class="line">    <span class="n">it</span> <span class="s2">&quot;does not represent a valid grammar, even though I think it should&quot;</span> <span class="k">do</span>
</span><span class="line">      <span class="nb">lambda</span> <span class="p">{</span>
</span><span class="line">        <span class="no">Treetop</span><span class="o">.</span><span class="n">load_from_string</span><span class="p">(</span>
</span><span class="line"><span class="o">&lt;&lt;</span><span class="no">GRAMMAR</span>
</span><span class="line"><span class="sh">grammar SimpleRuleWithLabel</span>
</span><span class="line"><span class="sh">  rule word</span>
</span><span class="line"><span class="sh">    letters:[A-Za-z]+</span>
</span><span class="line"><span class="sh">  end</span>
</span><span class="line"><span class="sh">end</span>
</span><span class="line"><span class="no">GRAMMAR</span>
</span><span class="line">      <span class="p">)}</span><span class="o">.</span><span class="n">should</span> <span class="n">raise_error</span><span class="p">(</span><span class="no">RuntimeError</span><span class="p">,</span><span class="sr"> /Expected \#/</span><span class="p">)</span>
</span><span class="line">    <span class="k">end</span>
</span><span class="line">
</span><span class="line">    <span class="n">it</span> <span class="s2">&quot;really should let me refer to the expression as #letters&quot;</span> <span class="k">do</span>
</span><span class="line">      <span class="n">pending</span> <span class="s2">&quot;https://github.com/nathansobo/treetop/issues/21&quot;</span>
</span><span class="line">    <span class="k">end</span>
</span><span class="line">  <span class="k">end</span>
</span><span class="line"><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<div class="footnotes">
  <ol>
    <li id="fn:1">
      <p>Remember, we don’t call them bugs anymore: we call them “mistakes”. In this case, we can’t call it a “mistake” yet, because we might simply have a difference of opinion or mindset.<a href="#fnref:1" rev="footnote">&#8617;</a></p>
    </li>
    <li id="fn:2">
      <p>Note the wording: I already assuming that <em>I</em> have it right and <em>they</em> have it wrong. Bad programmer.<a href="#fnref:2" rev="footnote">&#8617;</a></p>
    </li>
    <li id="fn:3">
      <p>They have a Second Cup in Romania. Canadians get why I’d find that weird.<a href="#fnref:3" rev="footnote">&#8617;</a></p>
    </li>
    <li id="fn:4">
      <p>Smart woman, my wife.<a href="#fnref:4" rev="footnote">&#8617;</a></p>
    </li>
  </ol>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Refactor Your Way to a Dependency Injection Container]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/12/07/refactor-your-way-to-a-dependency-injection-container/"/>
    <updated>2011-12-07T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/12/07/refactor-your-way-to-a-dependency-injection-container</id>
    <content type="html"><![CDATA[<h1 id="the-30-second-version">The 30-second version</h1>

<ul>
  <li>Invert the dependency on a Service, moving the <code>new</code> statement up one level in the call stack.<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup></li>
  <li>Repeat for all dependencies on Services until the corresponding <code>new</code> statements arrive at your application’s entry point. The entry point now creates a large object graph of all your Services in its <code>initialise</code> function.</li>
  <li>Remove duplication in <code>EntryPoint.initialise()</code>:
    <ul>
      <li>Instantiate common objects only once, passing them into the necessary constructors, replacing any Singletons with plain objects.</li>
      <li>Extract the choice of implementation for each Service interface into a lookup table mapping interface type to implementation type.</li>
      <li>Externalise the lookup table to a file, if you like.</li>
    </ul>
  </li>
</ul>

<p>Now you have a customised Dependency Injection Container for your application. To go a little farther:</p>

<ul>
  <li>Remove duplication in <code>EntryPoint.initialise()</code> among three applications.</li>
</ul>

<p>Now you have a generic Dependency Injection Container that probably provides 80% or more of the features you’ll ever need.</p>

<p>I recommend trying this incrementally. Think of the <code>new</code> statements flowing up the call stack, into the entry point, then changing from code into data. Nice, no?</p>

<h1 id="the-details">The Details</h1>

<p>I don’t have much to add.</p>

<p>I hope this helps to demystify dependency injection containers. To read about the technique of injecting dependencies, I refer you to <a href="http://link.jbrains.ca/vN1IiF">one of my articles</a> and then <a href="http://www.google.com/search?q=dependency+injection">a trusty web search</a>.</p>

<p>This technique applies the <a href="http://www.objectmentor.com/resources/articles/dip.pdf">Dependency Inversion Principle</a> repeatedly to move the choice of implementation for an interface up the call stack. This way, concrete things depend on abstract things.</p>

<p>Removing duplication in the entry point respects the principle <a href="http://link.jbrains.ca/s2V3Co">Abstractions in Code, Details in Data</a>, but it does rely on reflection, which can cause some problems. All the better not to scatter this reflection throughout the code causing a serious cohesion problem. Using reflection like this, all in one place, helps balance using a powerful technique with a design that everyone can understand.</p>

<p>Now you know what about 70% of what a dependency injection container does. You can build one. Even if you don’t go that far, the Dependency Inversion Principle will help reducing coupling and highlight cohesion problems in your design. It provides <a href="http://link.jbrains.ca/gmeMhh">another set of mechanics to practise on the way to becoming an accomplished designer</a>.</p>

<div class="footnotes">
  <ol>
    <li id="fn:1">
      <p>I mean “Service” in the <a href="http://link.jbrains.ca/6AtyK">Domain-Driven Design</a> sense.<a href="#fnref:1" rev="footnote">&#8617;</a></p>
    </li>
  </ol>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Rescuing Legacy Code by Extracting Pure Functions]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/11/27/rescuing-legacy-code-by-extracting-pure-functions/"/>
    <updated>2011-11-27T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/11/27/rescuing-legacy-code-by-extracting-pure-functions</id>
    <content type="html"><![CDATA[<p>After running a handful of <a href="http://www.legacycoderetreat.org">Legacy Code Retreats</a> I’ve had the chance to try a number of exercises related to rescuing legacy code. I’d like to share one that has met with very positive reactions from people: extracting <em>pure functions</em>. I use the term <em>pure function</em> to describe a function that only operates on local variables and parameters, but does not touch any state outside the function. No object fields, no global data. I have very little experience in functional programming, so I hope I use the term in a standard way.</p>

<p>No doubt you already know about the <a href="http://c2.com/ppr/wiki/WikiPagesAboutRefactoring/ComposedMethod.html">Composed Method</a> design pattern, which we commonly use to help understand code as we read it. Most commonly you encounter a block of code with a comment that describes what that code does. You then extract that block of code into a method whose name matches the comment. I’ve used this technique for well on a decade to raise the level of abstraction in code, help code document itself, and eliminate misleading comments. While introducing these methods helps me read the code, it sometimes hides the tangle of dependencies that makes separating responsibilities so difficult. For this reason, I recommend trying to extract pure functions instead.</p>

<p>To introduce a pure function, start with a block of code and extract a method for it. Now look at all the fields and global variables that the method reads and introduce each one as a parameter to the method. Now look at all the fields and global variables that the method writes to and turn these into return values. Where the old code invokes the new function, assign each new return value to the corresponding field or global variable. You know you’ve done this correctly if, of course, the overall behhavior of the program hasn’t changed and you can mark the new function as <code>static</code> or whatever your language calls a class-level function.</p>

<p>In some languages, like Java, you’ll have to introduce a new little class to allow you to return multiple values from the new function. If you don’t want to do that right away, then return a <code>Map</code> of return values. Once you see that you need to return similar <code>Map</code>s from different functions, consider replacing those <code>Map</code>s with a new class. Perhaps that new class will attract some code!</p>

<p>When I’ve used this technique, two key things have happened: either I’ve noticed duplication in the parameter lists of the new functions or introducing a parameter has changed the behavior of the system. In the first case, I introduce Parameter Objects for the duplicated parameters, which then probably attract code and become useful domain objects. In the second case, I’ve detected temporal coupling, which requires me to separate the function into two smaller ones so that some output from the first becomes input to the second. This helps me uncover cohesion problems, usually of the type of different things written too close together.</p>

<p>I realise that an example would help right about now, but I would rather create some screencasts than write out examples in code, but I don’t know when exactly I intend to do that. I wanted to share this idea with you without waiting for the energy to put together a suitable screencast.</p>

<p>I invite you to try introducing pure functions into some legacy code and practising the technique as a kata. Get used to the various maneuvers, like introducing Parameter Objects or Return Value Objects or solving temporal coupling by splitting the function in two. It sounds crazy, but I’d like to try a Legacy Code Retreat where we practise only this technique all day. I don’t know whether anyone else would find it valuable enough to try it together for an entire day, over and over and over.</p>

<p>Would you? Add your comments below.</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Detecting Changes in Third-Party Code]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/11/26/detecting-changes-in-third-party-code/"/>
    <updated>2011-11-26T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/11/26/detecting-changes-in-third-party-code</id>
    <content type="html"><![CDATA[<p>One of the people who watched <a href="http://www.infoq.com/presentations/integration-tests-scam">the 2009 version of Integrated Tests Are A Scam</a> recently asked me: <em>I wonder how you deal with updates of third-party libraries. How do you detect subtle API or behaviour changes? At the moment, I write state-based integration tests for these cases and I wonder whether this isn’t a sensible use of integration tests.</em></p>

<p>I write Learning Tests to discover how a third-party library works. I isolate myself from the third-party library through a layer of interfaces and adapter classes that evolve from the common ways I use the third-party library. I call this the “Pattern of Usage API”, as it represents the way my application uses that third-party library. Now my application uses the third-party library through a layer of interfaces, which means that I can introduce Contract Tests on those interfaces. These Contract Tests effectively describe the subset of the third-party library’s behavior on which I depend.</p>

<p>Now when I upgrade the third-party library, I run the Contract Tests against my adapters to that library. Test failures usually indicate a backwards incompatible change in the third-party library. (Sometimes they indicate a trivial difference in the API which requires a trivial fix, such as an API call having been renamed or something.)</p>

<p>Of course, this only helps me detect behavior changes related to computing answers, and not related to responsiveness, reliability, scalability, and so on. For that, I’ll always need system tests.</p>

<p>The Contract Tests are almost always state-based integration tests. I simply limit these to the implementation of Pattern of Usage API and don’t let it leak farther up the call stack. At some point you have to integrated with the Outside World. I simply teach people to look to make that integration thinner.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[When should I remove duplication?]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/09/29/when-should-i-remove-duplication/"/>
    <updated>2011-09-29T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/09/29/when-should-i-remove-duplication</id>
    <content type="html"><![CDATA[<p>As I learn to become a better programmer, I continue to follow <a href="http://link.jbrains.ca/g9P6Jw">the four elements of simple design</a>. Of these, I have observed that “remove duplication” helps me discover an appropriate structure for the thing I want to build. In my classes, we practise removing duplication a lot, in part because most people understand the rule “remove duplication” well enough to find it useful. After the first few weeks of practice, however, programmers following this rule observe varying results: sometimes removing the duplication makes the design much clearer, and sometimes it muddies the water. At this stage, she usually looks for more detailed rules to help decide when to remove duplication and when to leave it alone. I offer some simple rules and guidelines for this situation.</p>

<p>When I can’t decide whether to remove a certain bit of duplication I’ve found, I fall back on two rules:</p>

<ol>
  <li>Remove duplication only after you see <a href="http://link.jbrains.ca/qUxm1s"><em>three</em> copies</a>.</li>
  <li>If you don’t know how to remove this particular kind of duplication, then write more tests. Either you need more examples to see the pattern, or more examples will show a different, better pattern.</li>
</ol>

<p>I also remember two guidelines:</p>

<ol>
  <li>Don’t be afraid to remove duplication by introducing a method or class or interface with a stupid name. Remember that <a href="http://link.jbrains.ca/nP9Fvk">you can always improve the name later</a>.</li>
  <li>If you sense duplication, but don’t really see it, or can’t explain it to others, then <a href="http://link.jbrains.ca/nP9Fvk">make the surrounding names more precise</a>; then maybe you will see the duplication.</li>
</ol>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Writing Contract Tests in Java differently]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/07/17/writing-contract-tests-in-java-differently/"/>
    <updated>2011-07-17T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/07/17/writing-contract-tests-in-java-differently</id>
    <content type="html"><![CDATA[<p>I just wanted to know whether anyone has tried nesting the concrete tests inside the abstract test like this, and if you have, then how do/did you like it?</p>

<div><script src="https://gist.github.com/1084541.js?file="></script>
<noscript><pre><code>
package ca.jbrains.junit;

import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.junit.Test;

public abstract class ListContract {
    @Test
    public void emptyList() throws Exception {
        assertTrue(createEmptyList().isEmpty());
    }

    public abstract List&lt;Object&gt; createEmptyList();

    public static class ArrayListRespectsListContract extends ListContract {
        @Override
        public List&lt;Object&gt; createEmptyList() {
            return new ArrayList&lt;Object&gt;();
        }
    }

    public static class LinkedListRespectsListContract extends ListContract {

        @Override
        public List&lt;Object&gt; createEmptyList() {
            return new LinkedList&lt;Object&gt;();
        }
    }
}
</code></pre></noscript></div>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Contract Tests: An Example]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/07/07/contract-tests-an-example/"/>
    <updated>2011-07-07T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/07/07/contract-tests-an-example</id>
    <content type="html"><![CDATA[<p>I found an example of contract tests in Arlo Belshee’s <a href="http://arlobelshee.com/tag/no-mocks">series of articles about mock-free testing</a>. I must strongly, strongly point out that Arlo uses the term “mock” narrowly to refer to runtime- or bytecode-generated proxies that intercept interface method invocations and provide the ability to set method expectations, in the way that JMock and NMock do. He <em>does not</em> mean the generic term “mock”, where he uses the term “test double” instead. I thank him for that.</p>

<p>If you click <a href="https://github.com/arlobelshee/ArsEditorExample/blob/master/SimulatableApi.Tests/FileSystemCanLocateFilesAndDirs.cs">here</a> you’ll see an almost textbook example of a contract test: that is, a test class that can run the same set of tests for two different implementations of the same interface. I would change only one thing: I’d extract the tests into an abstract superclass—something I otherwise hate to do—and pull the declaration of the method <code>MakeTestSubject()</code> up there, leaving two subclasses, one for the real file system and one for the simulated one. “YAGNI,” you say, and I agree, but I prefer the symmetry of the abstract superclass design to the asymmetry of having one class inherit from the other. I find it easier to grok quickly.</p>

<p>Either way, I feel good seeing contract tests out in the wild. I’m not so crazy after all.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Adding behavior with confidence]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/06/22/adding-behavior-with-confidence/"/>
    <updated>2011-06-22T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/06/22/adding-behavior-with-confidence</id>
    <content type="html"><![CDATA[<h1 id="the-30-second-version">The 30-second version</h1>

<ul>
  <li>Adding behavior confidently involves having fewer parts to change (low duplication), knowing which ones to change (high cohesion), ease of changing just the part you want to change (low coupling), and understanding how you’ve changed it (strong tests).</li>
  <li>Adding behavior requires breaking an existing assumption.</li>
  <li>In a well-factored design, we can easily find the one place we have made that assumption. (Otherwise, why bother refactoring?)</li>
  <li>First, make room for the new code, then add it.</li>
  <li>To make room for the new code, extract the existing code into a method whose name describes the generalisation we want to make, or the idea we want to introduce.</li>
  <li>By making room for the new code, we make that code easier to reuse by reducing its dependence on its surrounding context.</li>
</ul>

<h1 id="want-to-learn-more">Want to learn more?</h1>

<ul>
  <li>Visit the links in this article.</li>
  <li>Attend <a href="http://www.jbrains.ca/training/agile-design-beyond-the-basics">Agile Design: Beyond the Basics</a>.</li>
  <li><a href="http://www.jbrains.ca/schedule-a-working-session">Pair with me</a>.</li>
</ul>

<h1 id="the-details">The Details</h1>

<p>We all want to add behavior to a system confidently, and I have observed that my confidence in adding behavior depends on two factors:</p>

<ul>
  <li>I know where to add code.</li>
  <li>I understand the behavior of the code I am adding.</li>
</ul>

<p>I use test-driven development as the main technique for handling the second of these two factors, but what about the first? I have uncovered a technique that I both use and teach, and I’d like to share that with you. I call this “making room for the new code”, naming it for a phrase I vaguely remember reading in one of the Grand Old XP books. (Did Kent Beck or Ron Jeffries write it? I can’t remember.) This technique helps me quickly find a reasonable first-draft place in the code base to put new code. After I have put the new code in place, and I feel confident that it does what I expect, I then use the <a href="http://link.jbrains.ca/g9P6Jw">Four Elements of Simple Design</a> to guide me in refactoring to improve the design.</p>

<h1 id="a-premise">A premise</h1>

<p>I start with the premise that <strong>adding behavior means breaking an assumption</strong>. By this I mean that whenever we add code to a system in order to extend its behavior, we have to falsify at least one assumption we’ve previously made. For example:</p>

<ul>
  <li>In a payroll system, in order to support a second cheque printer, we likely have to break the assumption that there is only one cheque format.</li>
  <li>In a point of sale system, in order to support separate cash and card payment reports, we likely have to break the assumption that all “we made a sale” events look the same.</li>
  <li>In a mobile phone monitoring system, in order to support billing by the second, we likely have to break the assumption that we only have to count the number of minutes a call lasted.</li>
</ul>

<p>Some of these seem obvious, and others less so, and it bears emphasising that the specific assumption or assumptions we break depends heavily on what we’ve built so far and the way we articulate the soon-to-be-added behavior. Even so, I conjecture that <span class="highlight"><em>for every behavior we want to add to a system, we can identify a non-empty list of assumptions that we <strong>need</strong> to break</em></span>.</p>

<h1 id="the-technique">The technique</h1>

<ol>
  <li>Identify an assumption that the new behavior needs to break.</li>
  <li>Find the code that implements that assumption.</li>
  <li>Extract that code into a method whose name represents the generalisation you’re about to make.</li>
  <li>Enhance the extracted method to include the generalisation.</li>
</ol>

<p>The less duplication you have in the system, the better this works, because duplicate code makes it difficult to find all the code that implements the assumption in question. Similarly, the more appropriate the names in your system, the better this works, because unsuitable names make it difficult to know which code implements the assumption in question, as opposed to something unrelated. You’ll notice that these points relate both to the <a href="http://link.jbrains.ca/g9P6Jw">Four Elements of Simple Design</a> and to the core concepts of <a href="http://link.jbrains.ca/jSNrEJ">Coupling and Cohesion</a>.</p>

<p>Yes, yes…</p>

<div style="text-align: center"><img style="width: 200px" src="http://images.jbrains.ca/handy-right-about-now.png" /></div>

<h1 id="an-example">An example</h1>

<p>We are building a point of sale system, and we’ve just decided to implement sales tax. I live in PEI, Canada, where not only do we exclude sales tax from the price, we have two sales taxes, and we charge the second one <em>on top of</em> the first one. For example:</p>

<p class="example">A $125 item that attracts both GST (the &#8220;Goods and Services&#8221; tax) and PST (provincial sales tax) costs a total of $144.38. GST at 5% costs $6.25, then PST at 10% of $131.25 (= $125 + $6.25) costs $13.13. The total is $125 + $6.25 + $13.13 = $144.38.</p>

<p>Notice that this example implies that GST or PST might or might not apply to a given product, so even before we identify the old assumption to break, we need to note the new assumption we’ll make: <em>we assume that all products attract both GST and PST</em>. Our customers won’t like it, but the tax authorities will love it, and only they have the power to treat us guilty until proven innocent.</p>

<p>Our code has a class like this in it.</p>

<div><script src="https://gist.github.com/1040052.js?file=UserGestureListener.rb"></script>
<noscript><pre><code>class UserGestureListener
  def on_barcode_scanned(barcode)
    product = @catalog.find(barcode)
    if product.nil?
      @display.display_message(ProductNotFoundMessage.with(barcode))
    else
      @display.display_product(product)
      @sale_total += product.price
    end
  end
end</code></pre></noscript></div>

<p>What do we assume now that we can’t allow ourselves to assume any longer? <strong>The sale total should increment by the (net) price of the item we sell.</strong> By <em>net price</em> here, I refer to the pre-tax price, because of course, until now, our system has no notion of “tax”. Fortunately, because we’ve ruthlessly removed duplication so far, computing the running total of the sale requires only this line of code. We can pretty safely apply the technique of this article right here. To do this, we extract the assumption into a new method whose name represents the generalisation we’re about to make. In this case, we don’t want to increase the sale total by the product’s <em>price</em>, but rather by its <em>cost</em>, which includes any additional charges beyond net price. So, we introduce a method for accumulating the scanned product’s cost.</p>

<div><script src="https://gist.github.com/1040052.js?file=UserGestureListener-AddedMethodDescribingGeneralisation.rb"></script>
<noscript><pre><code>class UserGestureListener
  def on_barcode_scanned(barcode)
    product = @catalog.find(barcode)
    if product.nil?
      @display.display_message(ProductNotFoundMessage.with(barcode))
    else
      @display.display_product(product)
      accumulate_cost(product)
    end
  end

  def accumulate_cost(product)
      @sale_total += product.price
  end
end</code></pre></noscript></div>

<p>This creates space for the new code. We test-drive the new code, and end up with this delightful monstrosity.</p>

<div><script src="https://gist.github.com/1040052.js?file=UserGestureListener-Generalised.rb"></script>
<noscript><pre><code>class UserGestureListener
  def on_barcode_scanned(barcode)
    product = @catalog.find(barcode)
    if product.nil?
      @display.display_message(ProductNotFoundMessage.with(barcode))
    else
      @display.display_product(product)
      accumulate_cost(product)
    end
  end

  def accumulate_cost(product)
      @sale_total += ((product.price * 1.05).round * 1.1).round
  end
end</code></pre></noscript></div>

<p>It looks ugly, but it works. In addition to looking ugly, this method has <a href="http://link.jbrains.ca/kqLJMj">Feature Envy</a>. Specifically, the calculation part of <code>#accumulate_cost</code> only talks to <code>product</code>, and so it can move onto the class <code>Product</code>, leaving only the accumulating left behind. You could also say that this method had <a href="http://link.jbrains.ca/lUrZh4">two responsibilities</a>, so I separated them, then notice the feature envy in one of them, then moved it. I can almost always take smaller steps.</p>

<div><script src="https://gist.github.com/1040052.js?file=UserGestureListener-Refactored.rb"></script>
<noscript><pre><code>class UserGestureListener
  def on_barcode_scanned(barcode)
    product = @catalog.find(barcode)
    if product.nil?
      @display.display_message(ProductNotFoundMessage.with(barcode))
    else
      @display.display_product(product)
      @sale_total += product.cost
    end
  end
end

class Product
  def cost
    ((price * 1.05).round * 1.1).round
  end
end
</code></pre></noscript></div>

<p>Notice the <a href="http://amzn.to/mB7yLf">context independence</a> we’ve achieved with the method <code>Product#cost</code>. We can now refine the notion of “cost” freely without worrying about how someone will use that information. We have an easy-to-find, easy-to-extend part of the system where we can add behavior for determining which products attract which taxes, supporting multiple tax calculation policies, and even including shipping, handling and restocking fees. Now we can really add future behavior with confidence.</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A model for improving names]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/06/15/a-model-for-improving-names/"/>
    <updated>2011-06-15T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/06/15/a-model-for-improving-names</id>
    <content type="html"><![CDATA[<p style="text-align: center"><a href="http://assets.jbrains.ca/ImprovingNames.pdf"><img style="width: 500px; margin: 0px auto" src="http://30.media.tumblr.com/tumblr_lmsovxnwmq1qa6fh7o1_500.png" /></a></p>

<p>A model for improving the names of variables, fields, interfaces, classes and namespaces in a system. Practise this and more in my course, <a href="http://www.jbrains.ca/training/agile-design-beyond-the-basics">Agile Design: Beyond the Basics</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Announcing a European Tour in 2011]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/06/08/announcing-a-european-tour-in-2011/"/>
    <updated>2011-06-08T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/06/08/announcing-a-european-tour-in-2011</id>
    <content type="html"><![CDATA[<p><a href="http://announcing.europeantour2011.com"><img style="float: right; width: 215px; margin: 0px; padding-left: 10px; padding-bottom: 10px" src="http://www.jbrains.ca/wp-content/uploads/2011/06/JbrainsEuropeanTour2011-badge.png" />&lt;/img&gt;</a>I’m <a href="http://announcing.europeantour2011.com">touring Europe in 2011</a>. I have planned some public courses and some conferences, and am searching for private consulting and training work. Over the coming weeks I will reveal where I’m appearing on the map. The colors on the map provide a hint! If you’d like to invite me to your event, then please <a href="https://jbrains.wufoo.com/forms/invite-j-b-to-your-event">visit here</a>. See you later this year!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Continuum of Names: an example]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/05/27/the-continuum-of-names-an-example/"/>
    <updated>2011-05-27T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/05/27/the-continuum-of-names-an-example</id>
    <content type="html"><![CDATA[<p>I found someone trying to work on improving names in their code, and <a href="https://gist.github.com/986928">gave them a little advice</a>. It gives a reasonable example of some of the things I think about when naming.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Continuum of Names: A quick summary]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/05/26/the-continuum-of-names-a-quick-summary/"/>
    <updated>2011-05-26T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/05/26/the-continuum-of-names-a-quick-summary</id>
    <content type="html"><![CDATA[<p>Emma López (@hell03610) shared with the world <a href="http://blog.dev.openfinance.es/2011/05/xp2011-modular-design/">her notes</a> from my XP2011 session, “A Simple Approach to Modular Design”. In it, she summarises a model I teach about how to improve names in code. I do plan to write about this in more detail this summer.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Code rejects inheritance-based reuse! An example.]]></title>
    <link href="http://blog.thecodewhisperer.com/2011/05/02/code-rejects-inheritance-based-reuse-an-example/"/>
    <updated>2011-05-02T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2011/05/02/code-rejects-inheritance-based-reuse-an-example</id>
    <content type="html"><![CDATA[<p>We’ve read this before: don’t reuse code by subclassing. Instead, compose objects into a loose network that share responsibility for the system’s behavior. While practising, working through Growing Object-Oriented Systems, I reached the point where Steve and Nat started writing microtests, and decided to stray from the text and try it out on my own. I reached the stage where the first two system tests pass, but in the process, I introduced much cyclic dependency and duplication, particularly related to sending and parsing chat messages. In preparing to address this problem, I noticed some duplication in how the <em>auction</em> handles its incoming chats: sometimes it updated the UI, and sometimes it didn’t. I figured I’d turn those into two chat message handlers, separating the UI behavior from the non-UI behavior, and in so doing, introduced some temporary duplication.</p>

<div><script src="https://gist.github.com/951144.js?file="></script>
<noscript><pre><code>package ca.jbrains.auction.test;

public class Main implements MessageListener {
    // ...
    private void joinAuction(final XMPPConnection connection, String itemId)
            throws XMPPException {

        disconnectWhenUiCloses(connection);
        final Chat chat = connection.getChatManager().createChat(
                auctionId(itemId, connection), new MessageListener() {
                    // SMELL This nested class makes cyclic dependencies too
                    // easy
                    @Override
                    public void processMessage(Chat chat, Message message) {
                        // REFACTOR Replace conditional with polymorphism in
                        // each

                        // SMELL This duplicates code in Main's message
                        // listener,
                        // which probably means an abstraction in the middle is
                        // missing.
                        // REFACTOR? MessageListener parses messages and fires
                        // auction events; AuctionEventListener updates UI or
                        // sends chat message
                        final Object event = Messages.parse(message);
                        if (event instanceof BiddingState) {
                            BiddingState biddingState = (BiddingState) event;
                            if (!Main.SNIPER_XMPP_ID.equals(biddingState
                                    .getBidderName())) {
                                counterBid(chat);
                            }
                        }
                    }
                });

        chat.addMessageListener(this);

        this.dontGcMeBro = chat;

        chat.sendMessage(Messages.joinAuction());
    }
    
    //...
    
    @Override
    public void processMessage(Chat chat, Message message) {
        // SMELL This duplicates code in joinAuction()'s message listener,
        // which probably means an abstraction in the middle is
        // missing.
        // REFACTOR? MessageListener parses messages and fires
        // auction events; AuctionEventListener updates UI or
        // sends chat message
        Object event = Messages.parse(message);
        if (event instanceof BiddingState) {
            BiddingState biddingState = (BiddingState) event;
            if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                signalSniperIsBidding();
            }
        } else {
            signalAuctionClosed();
        }
    }
}</code></pre></noscript></div>

<p>You can probably see a straightforward way to start removing this duplication. To illustrate it, look at the following code snippet.</p>

<div><script src="https://gist.github.com/951160.js?file="></script>
<noscript><pre><code>package ca.jbrains.auction.test;

public class Main {
    public static final class BidsForSniperMessageListener implements
            MessageListener {

        private Main main;

        public BidsForSniperMessageListener(Main main) {
            this.main = main;
        }

        // SMELL This nested class makes cyclic dependencies too
        // easy
        @Override
        public void processMessage(Chat chat, Message message) {
            // REFACTOR Replace conditional with polymorphism in
            // each

            // SMELL This duplicates code in Main's message
            // listener,
            // which probably means an abstraction in the middle is
            // missing.
            // REFACTOR? MessageListener parses messages and fires
            // auction events; AuctionEventListener updates UI or
            // sends chat message
            final Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                    main.counterBid(chat);
                }
            }
        }
    }

    public static class UpdatesMainWindowMessageListener implements
            MessageListener {
        private final Main main;

        public UpdatesMainWindowMessageListener(Main main) {
            this.main = main;
        }

        @Override
        public void processMessage(Chat chat, Message message) {
            // SMELL This duplicates code in joinAuction()'s message listener,
            // which probably means an abstraction in the middle is
            // missing.
            // REFACTOR? MessageListener parses messages and fires
            // auction events; AuctionEventListener updates UI or
            // sends chat message
            Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                    main.signalSniperIsBidding();
                }
            } else {
                main.signalAuctionClosed();
            }
        }
    }

    //...
}</code></pre></noscript></div>

<p>So we have two classes with a common field, a common method signature, and similar method bodies. Extract Superclass seems logical, even though I can&#8217;t think of a decent name for this class so far. No worry: it will come to me.</p>

<div><script src="https://gist.github.com/951166.js?file="></script>
<noscript><pre><code>package ca.jbrains.auction.test;

public class Main {
    public static class FooMessageListener implements MessageListener {
        @Override
        public void processMessage(Chat chat, Message message) {
        }
    }

    public static final class BidsForSniperMessageListener extends
            FooMessageListener {
        
        private final Main main;

        public BidsForSniperMessageListener(Main main) {
            this.main = main;
        }

        @Override
        public void processMessage(Chat chat, Message message) {
            final Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                    main.counterBid(chat);
                }
            }
        }
    }

    public static class UpdatesMainWindowMessageListener extends
            FooMessageListener {

        private final Main main;

        public UpdatesMainWindowMessageListener(Main main) {
            this.main = main;
        }

        @Override
        public void processMessage(Chat chat, Message message) {
            Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                    main.signalSniperIsBidding();
                }
            } else {
                main.signalAuctionClosed();
            }
        }
    }
}</code></pre></noscript></div>

<p>Next, we have to extract the parts that differ from the parts the match each other. I did that by introducing new methods.</p>

<div><script src="https://gist.github.com/951171.js?file="></script>
<noscript><pre><code>package ca.jbrains.auction.test;

public class Main {
    public static class FooMessageListener implements MessageListener {
        @Override
        public void processMessage(Chat chat, Message message) {
        }
    }

    public static final class BidsForSniperMessageListener extends
            FooMessageListener {
        
        private final Main main;

        public BidsForSniperMessageListener(Main main) {
            this.main = main;
        }

        // SMELL This nested class makes cyclic dependencies too
        // easy
        @Override
        public void processMessage(Chat chat, Message message) {
            final Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                handleBiddingStateEvent(chat, biddingState);
            }
        }

        private void handleBiddingStateEvent(Chat chat,
                BiddingState biddingState) {
            if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                main.counterBid(chat);
            }
        }
    }

    public static class UpdatesMainWindowMessageListener extends
            FooMessageListener {

        private final Main main;

        public UpdatesMainWindowMessageListener(Main main) {
            this.main = main;
        }

        @Override
        public void processMessage(Chat chat, Message message) {
            Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                handleBiddingStateEvent(biddingState);
            } else {
                handleAllOtherEvents();
            }
        }

        private void handleAllOtherEvents() {
            main.signalAuctionClosed();
        }

        private void handleBiddingStateEvent(BiddingState biddingState) {
            if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                main.signalSniperIsBidding();
            }
        }
    }
    //...
}</code></pre></noscript></div>

<p>Next, we make <code>processMessage()</code> identical in both classes, so as to pull it up into <code>FooMessageListener</code>. And here, we find our first warning sign about this refactoring. The signatures of <code>handleBiddingStateEvent()</code> don&#8217;t match:</p>

<ul><li><code>BidsForSniperMessageListener.handleBiddingStateEvent(Chat, BiddingState)</code></li>
<li><code>UpdatesMainWindowMessageListener.handleBiddingStateEvent(BiddingState)</code></li>
</ul>
<p>In order to find out whether this will become a problem, I have to add <code>Chat</code> to the parameter list for <code>UpdatesMainWindowMessageListener</code>&#8217;s implementation of the method, at least for now. I imagine I could do something more clever, but I&#8217;m not sure that introducing a closure over a <code>Chat</code> object would simplify matters. I can put that on my &#8220;to try&#8221; list for now. In the meantime, I add the <code>Chat</code> parameter. <a href="http://bit.ly/mnNv95" target="_blank">See the diff.</a></p>

<p>Now to turn similar <code>processMessage()</code> implementations into identical ones, I introduced an empty method. This is another warning sign, since I can&#8217;t envision a &#8220;default&#8221; UI update. Still, I reserve judgment until I have more evidence, and introduce the necessary changes. <a href="http://bit.ly/jjJQJI" target="_blank">See the diff.</a></p>

<p>Now that <code>processMessage()</code> looks identical in both subclasses, we can pull it up into <code>FooMessageListener</code>, for which we still don&#8217;t have a good name. Either <a href="http://bit.ly/mHVAaD" target="_blank">see the diff</a> or look at the final result below.</p>

<div><script src="https://gist.github.com/951183.js?file="></script>
<noscript><pre><code>package ca.jbrains.auction.test;

public class Main {
    public static abstract class FooMessageListener implements MessageListener {
        @Override
        public void processMessage(Chat chat, Message message) {
            final Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                handleBiddingStateEvent(chat, biddingState);
            } else {
                handleAllOtherEvents();
            }
        }

        protected abstract void handleAllOtherEvents();

        protected abstract void handleBiddingStateEvent(Chat chat,
                BiddingState biddingState);
    }

    public static final class BidsForSniperMessageListener extends
            FooMessageListener {

        private final Main main;

        public BidsForSniperMessageListener(Main main) {
            this.main = main;
        }

        @Override
        protected void handleAllOtherEvents() {
            // I don't need to do anything here
        }

        @Override
        protected void handleBiddingStateEvent(Chat chat,
                BiddingState biddingState) {
            if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                main.counterBid(chat);
            }
        }
    }

    public static class UpdatesMainWindowMessageListener extends
            FooMessageListener {

        private final Main main;

        public UpdatesMainWindowMessageListener(Main main) {
            this.main = main;
        }

        @Override
        protected void handleAllOtherEvents() {
            main.signalAuctionClosed();
        }

        @Override
        protected void handleBiddingStateEvent(
                @SuppressWarnings(&quot;unused&quot;) Chat chat, BiddingState biddingState) {
            if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                main.signalSniperIsBidding();
            }
        }
    }
    //...
}</code></pre></noscript></div>

<p>Now that I look at this last version of <code>Main</code>, I see the value in having attempted this refactoring. It clarifies quite well the specific reasons why I won&#8217;t let inheritance play a long-term role in this part of the design. Specifically, look at the little problems with this design.</p>

<ul><li>I still can&#8217;t think of a good name for <code>FooMessageListener</code>, although maybe you&#8217;re screaming one at me as you read. (Sorry; I can&#8217;t hear you.)</li>
<li><code>BidsForSniperMessageListener.handleAllOtherEvents()</code> doesn&#8217;t need to do anything, which might or might not be a problem, but often points to the Refused Bequest smell.</li>
<li><code>UpdatesMainWindowMessageListener.handleBiddingStateEvent()</code> doesn&#8217;t need its <code>chat</code> parameter.</li>
<li>Both subclasses need a reference back to <code>Main</code>, but the superclass <code>FooMessageListener</code> doesn&#8217;t need it. Of course, that says more about <code>Main</code> in general than the <code>FooMessageListener</code> hierarchy: <code>Main</code> violates the Single Responsibility Principle in a variety of delightful ways. That&#8217;s why we&#8217;re here.</li>
</ul>
<p>So let me talk this through: we have subclasses of <code>FooMessageListener</code> that respond to the same logical stimuli, but different subclasses need different data and sometimes a subclasses doesn&#8217;t need to respond to the stimuli at all. <strong>That sounds an awful lot like an event mechanism to me.</strong></p>

<p>And if you look ahead in Steve and Nat&#8217;s book, that&#8217;s not surprising.</p>

<p>So how do we get from here to there? I plan to attack it this way:</p>

<ol><li>Make <code>FooMessageListener</code> an event source for this new type of event, which I&#8217;ll tentatively call an <code>AuctionEvent</code>.</li>
<li>Turn the subclasses into <code>AuctionEventListener</code>s.</li>
<li>Inline stuff back into place.</li>
</ol>
<p>You can follow the detailed changes on <a href="http://bit.ly/kdotl2" target="_blank">this branch</a> starting with <a href="http://bit.ly/mHVAaD" target="_blank">this commit</a>.</p>

<p>By the end of this session, I ended up with a new Auction Event concept, which has started separating the &#8220;chat message&#8221; concept from the &#8220;auction changed&#8221; event. It does, however, lead to other questions, which I&#8217;ve highlighted with <code>SMELL</code> and <code>REFACTOR</code> comments, so look for them. For now, I feel good that, while introducing a hierarchy had its problems, it helped me see how specifically to eliminate it. I trusted the mechanics, and it helped me see where to go next. I know I need to introduce an &#8220;auction closed&#8221; event and perhaps need to introduce an <code>AuctionEvent</code> object to eliminate the need for type checking in <code>AuctionEventSourceMessageListener</code>. We&#8217;ll go there next time, but in the meantime, peruse the current state of the code.</p>

<div><script src="https://gist.github.com/951204.js?file="></script>
<noscript><pre><code>package ca.jbrains.auction.test;

public class Main {
    public interface AuctionEventListener {
        void handleNewBiddingState(BiddingState biddingState);

        void handleGenericEvent(Object object);
    }

    public static class AuctionEventSourceMessageListener implements
            MessageListener {

        private final List&lt;AuctionEventListener&gt; listeners;

        public AuctionEventSourceMessageListener() {
            this.listeners = new ArrayList&lt;AuctionEventListener&gt;();
        }

        public void addListener(AuctionEventListener listener) {
            listeners.add(listener);
        }

        @Override
        public void processMessage(Chat chat, Message message) {
            // SMELL Duplicated loops
            final Object event = Messages.parse(message);
            if (event instanceof BiddingState) {
                BiddingState biddingState = (BiddingState) event;
                for (AuctionEventListener each : listeners) {
                    each.handleNewBiddingState(biddingState);
                }
            } else {
                for (AuctionEventListener each : listeners) {
                    each.handleGenericEvent(event);
                }
            }
        }
    }
    //...
    private void joinAuction(final XMPPConnection connection, String itemId)
            throws XMPPException {

        disconnectWhenUiCloses(connection);

        final AuctionEventSourceMessageListener auctionEventSource = new AuctionEventSourceMessageListener();

        final Chat chat = connection.getChatManager().createChat(
                auctionId(itemId, connection), auctionEventSource);

        // SMELL? Programming by accident that I can't add these listeners in
        // the constructor of the Auction Event Source?
        auctionEventSource.addListener(new AuctionEventListener() {
            @Override
            public void handleNewBiddingState(BiddingState biddingState) {
                // REFACTOR? Should &quot;sniper now losing&quot; be an event?
                if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                    counterBid(chat);
                }
            }

            @Override
            public void handleGenericEvent(Object object) {
                // I can ignore this
            }
        });

        auctionEventSource.addListener(new AuctionEventListener() {
            @Override
            public void handleNewBiddingState(BiddingState biddingState) {
                // REFACTOR? Should &quot;sniper now losing&quot; be an event?
                if (!Main.SNIPER_XMPP_ID.equals(biddingState.getBidderName())) {
                    signalSniperIsBidding();
                }
            }

            @Override
            public void handleGenericEvent(Object object) {
                // REFACTOR Introduce an &quot;auction closed&quot; event
                signalAuctionClosed();
            }
        });

        this.dontGcMeBro = chat;

        chat.sendMessage(Messages.joinAuction());
    }
    //...
}</code></pre></noscript></div>

<p>If you prefer, <a href="http://bit.ly/iNyNbc" target="_blank">look at the changes</a> in moving from <code>MessageListener</code>s to <code>AuctionEventListener</code>s.</p>

<p>I hope I&#8217;ve shown how a code base can reject an attempt to reuse code by inheritance, prefering instead, in this case, composition implemented as an event chain.</p>
<p>&lt;/p&gt;</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Injecting dependencies doesn't have to hurt]]></title>
    <link href="http://blog.thecodewhisperer.com/2010/12/04/injecting-dependencies-doesnt-have-to-hurt/"/>
    <updated>2010-12-04T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2010/12/04/injecting-dependencies-doesnt-have-to-hurt</id>
    <content type="html"><![CDATA[<p>I have noticed a recent swell of comments about the pain of dependency injection, and if this has caused you problems on your project, then I think I can help you by offering a few simple guidelines and a single goal for injecting dependencies.</p>

<h1>The guidelines</h1>

<p>I have formulated these as <a href="http://bit.ly/sYj5Y" target="_blank">Novice or Advanced Beginner</a> rules, and so I have worded them more strongly than I tend to word my advice.</p>

<ul><li>When in doubt, inject each dependency directly into the method that requires it.</li>
<li>Only when you inject the same dependency into multiple methods of the same class, move the parameter into the constructor.</li>
<li>Do not use so-called &#8220;setter injection&#8221; except as an intermediate step in a refactoring aimed at injecting the dependency into a method or the constructor.</li>
<li>Stop using the Service Locator pattern, and instead inject the service into the client.</li>
<li>Stop instantiating collaborating services (in the <a href="http://bit.ly/gyLuWK" target="_blank">Domain-Driven Design sense</a>), and instead inject those services into the client.</li>
<li>When a constructor parameter list becomes uncomfortably long, split the class so that the new classes&#8217; constructor parameter lists don&#8217;t overlap.</li>
<li>If you notice a class using the same dependency through two different object graph routes, split the class so that the new classes receive the dependency directly in their constructors.</li>
<li>If you notice a class using groups of dependencies at different times, split the class so that the new classes only use each cohesive group of dependencies.</li>
</ul>
<p>All these guidelines have their roots in &#8220;remove duplication&#8221; and &#8220;fix bad names&#8221;, two of the <a href="http://bit.ly/g9P6Jw" target="_blank">four elements of simple design</a>.</p>

<h1>So why inject dependencies at all?</h1>

<p>Some people inject dependencies in order to stub, mock or spy on a method for testing. I used to use that as a primary motivation, but over the years that motivation has evolved into something more widely useful. I inject dependencies for one reason: to move the things that change in the direction of the client and the things that don&#8217;t in the direction of the supplier. Or, if you prefer, &#8220;abstractions in code, details in data&#8221;. Or, if you prefer, to avoid abstractions depending on details. Any of those will do.</p>

<h1>You don&#8217;t buy it?</h1>

<p>No problem. I&#8217;ll write more articles in this space showing examples of each of the guidelines, and you&#8217;ll have plenty of opportunity to share your opinions about them.</p>
<p>&lt;/p&gt;</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Integrated Tests Are A Scam]]></title>
    <link href="http://blog.thecodewhisperer.com/2010/10/16/integrated-tests-are-a-scam/"/>
    <updated>2010-10-16T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2010/10/16/integrated-tests-are-a-scam</id>
    <content type="html"><![CDATA[<p style="font-size: small; font-style: italic;">On March 1, 2010 I changed the phrase &#8220;integration tests&#8221; to &#8220;integrated tests&#8221; in this article.</p>
<p><strong>Integrated tests are a scam&mdash;a self-replicating virus that threatens to infect your code base, your project, and your team with endless pain and suffering.</strong></p>
<p>Wait&#8230; <em>what?</em></p>
<p>I mean it. I hate integrated tests. I <em>hate</em> them, and with a passion. Of course, I should clarify what I mean by <em>integrated tests</em>, because, like any term in software, we probably don&#8217;t agree on a meaning for it.</p>
<blockquote>
<p>I use the term <em>integrated test</em> to mean any test whose result (pass or fail) depends on the correctness of the implementation of more than one piece of non-trivial behavior.</p>
</blockquote>
<p>I, too, would prefer a more rigorous definition, but this one works well for most code bases most of the time. I have a simple point: I generally don&#8217;t want to rely on tests that might fail for a variety of reasons. Those tests create more problems than they solve.</p>
<p>You write integrated tests because you can&#8217;t write perfect unit tests. You know this problem: all your unit tests pass, but someone finds a defect anyway. Sometimes you can explain this by finding an obvious unit test you simply missed, but sometimes you can&#8217;t. In those cases, you decide you need to write an integrated test to make sure that all the production implementations you use in the broken code path now work correctly together.</p>
<p>So far, no big deal, but you&#8217;ll meet the monster as soon as you think this:</p>
<blockquote>
<p>If we can find defects even when our tests pass 100%, and if I can only plug the hole with an integrated tests, then <em>we&#8217;d better write integrated tests everywhere</em>.</p>
</blockquote>
<p>Bad idea. Really bad.</p>
<p><img src="http://www.trumanlibrary.org/photographs/85-7.jpg" style="width:400px;" alt="" /></p>
<p>Why so bad? A little bit of simple arithmetic should help explain.</p>
<p>You have a medium-sized web application with around 20 pages, maybe 10 of which have forms. Each form has an average of 5 fields and the average field needs 3 tests to verify thoroughly. Your architecture has about 10 layers, including web presentation widgets, web presentation pages, abstract presentation, an <span class="caps">HTTP</span> bridge to your service <span class="caps">API</span>, controllers, transaction scripts, abstract data repositories, data repository implementations, <span class="caps">SQL</span> statement mapping, <span class="caps">SQL</span> execution, and application configuration. A typical request/response cycle creates a stack trace 30 frames deep, some of which you wrote, and some of which you&#8217;ve taken off the shelf from a wide variety of open source and commercial packages. How many tests do you need to test this application <em>thoroughly</em>?</p>
<p>At least 10,000. Maybe a million. <em>One million</em>.</p>
<p><a href="http://tinyurl.com/dx68z4"><em>Wie ist es m&ouml;glich?!</em></a> Consider 10 layers with 3 potential branch points at each layer. Number of code paths: 3<sup>10</sup> &gt; 59,000. How about 4 branch points per layer?  4<sup>10</sup> &gt; 1,000,000. How about 3 branch and 12 layers? 3<sup>12</sup> &gt; 530,000.</p>
<p>Even if one of your 12 layers has a single code path, 3<sup>11</sup> &gt; 177,000.</p>
<p>Even if your 10-layer application has only an average of 3.5 code paths per layer, 3.5<sup>10</sup> &gt; 275,000<sup class="footnote"><a href="#fn6d7a96adc995137445819fd95bd31a74367d9f83">1</a></sup>.</p>
<p>To simplify the arithmetic, suppose you need <em>only</em> 100,000 integrated tests to cover your application. Integrated tests typically touch the file system or a network connection, meaning that they run on average at a rate of no more than 50 tests per second. Your 100,000-test integrated test suite executes in 2000 seconds or 34 minutes. That means that you execute your entire test suite only when you feel ready to check in. Some teams let their continuous build execute those tests, and hope for the best, wasting valuable time when the build fails and they need to backtrack an hour.</p>
<p>How long do you need to <em>write</em> 100,000 tests? If it takes 10 minutes to write each test&mdash;that includes thinking time, time futzing around with the test to make it pass the first time, and time maintaining your test database, test web server, test application server, and so on&mdash;then you need 2,778 six-hour human-days (or pair-days if you program in pairs). That works out to 556 five-day human-weeks (or pair-weeks).</p>
<p>Even if I overestimate by a factor of five, you still need two full-time integrated test writers for a one-year project <em>and</em> a steady enough flow of work to keep them busy six hours per day <em>and</em> you can&#8217;t get any of it wrong, because you have no time to rewrite those tests.</p>
<p>No. You&#8217;ll have those integrated test writers writing production code by week eight.</p>
<p>Since you won&#8217;t write all those tests, you&#8217;ll write the tests you can. You&#8217;ll write the happy path tests and a few error cases. You won&#8217;t check all ten fields in a form. You won&#8217;t check what happens on February 29. You&#8217;ll jam in a database change rather than copy and paste the 70 tests you need to check it thoroughly. You&#8217;ll write around 50 tests per week, which translates to 2,500 tests in a one-year project. Not 100,000.</p>
<p>2.5% of the number you need to test your application thoroughly.</p>
<p>Even if you wrote the most important 2.5%, recognizing the nearly endless duplication in the full complement of tests, you&#8217;d cover somewhere between 10% and 80% of your code paths, and you&#8217;ll have no idea whether you got closer to 10% or 80% until your customers start pounding the first release.</p>
<p>Do you feel lucky? Well, do you?<sup class="footnote"><a href="#fn">2</a></sup></p>
<p>So you write your 2,500 integrated tests. Perhaps you even write 5,000 of them. When your customer finds a defect, how will you fix it? Yes: with another handful of integrated tests. The more integrated tests you write, the more of a false sense of security you feel. (Remember, you just increased your code path coverage from 5% to 5.01% with those ten integrated tests.) This false sense of security helps you feel good about releasing more undertested code to your customers, which means they find more defects, which you fix with yet more integrated tests. Over time your code path coverage <em>decreases</em> because the complexity of your code base grows more quickly than your capacity to write enough integrated tests to cover it.</p>
<p>&#8230;and you wonder why you spend 70% of your time with support calls?</p>
<p>Integrated tests are a scam. Unreliable, self-replicating time-wasters. They have to go.</p>
<hr />

<p class="footnote" id="fn6d7a96adc995137445819fd95bd31a74367d9f83"><sup>1</sup> True: few code bases distribute their complexity to their layers uniformly. Suppose half your 12 layers have only two branch points&mdash;one normal path and one error path&mdash;while the others have 5 branch points. 2<sup>6</sup>&middot;5<sup>6</sup> = 1,000,000 and for 4 branch points 2<sup>6</sup>&middot;4<sup>6</sup> &gt; 262,000. You can&#8217;t win this game.</p>
<p class="footnote" id="fn"><sup>2</sup> Aslak Helles&oslash;y points to a way to take luck mostly out of the equation. <a href="http://www.pairwise.org/">His technique for choosing high-value tests</a> will certainly help, but it stops short of testing your code <strong>thoroughly</strong>. I believe you can achieve truly thorough focused tests with similar cost to writing and maintaining integrated tests even using the pairwise test selection technique. (Thanks, Aslak, for your comment on April 12, 2009.)</p>
<p style="font-size: small;"><a href="http://blog.thecodewhisperer.com/tagged/integrated-tests-are-a-scam">Read more in this series</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[JMock v. Mockito, but not to the death]]></title>
    <link href="http://blog.thecodewhisperer.com/2010/10/05/jmock-v-mockito-but-not-to-the-death/"/>
    <updated>2010-10-05T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2010/10/05/jmock-v-mockito-but-not-to-the-death</id>
    <content type="html"><![CDATA[<p>I grew up using EasyMock, but near the end of the first draft of JUnit Recipes, I wrote this:</p>

<blockquote>&#8220;In the time between writing this essay and sending the book to be printed, a new dynamic proxy-based mock objects package has appeared on the scene, called jMock (www.jmock.org). It picks up where EasyMock left off, as the EasyMock project went through a temporary lull in activity, between October 2003 and May 2004. Being so new, we do not have any experience using it, and so we cannot say much about it, but it does look promising and bears a look. If you have used EasyMock, then it is worth experimenting with jMock to see the difference. You may find you prefer jMock&#8217;s approach to that of EasyMock.&#8221;</blockquote>

<p>Since 2004 I have used JMock almost exclusively to drive my designs in Java. I even like the strange-looking JMock 2 syntax which, I know, puts me in the minority. In the last two years, other test double libraries have gained mindshare, among which Mockito has become quite prominent. While I can’t give you a feature-by-feature comparison, I can tell you this:</p>

<p>When I want to rescue legacy code, I reach for Mockito. When I want to design for new features, I reach for JMock.</p>

<p>Different central assumptions of JMock and Mockito make each one better at its respective task. By default, JMock assumes that a test double (a “mock”) expects clients not to invoke anything at any time. If you want to relax that assumption, then you have to add a stub. On the other hand, Mockito assumes that a test double (sadly, also a “mock”) allows clients to invoke anything at any time. If you want to strengthen that assumption, then you have to verify a method invocation. This makes all the difference.</p>

<p>When I work with legacy code, I mostly write learning tests to discover how different parts of that legacy code behaves. Usually legacy code has obscene and overwhelming levels of interdependency, and Mockito helps me manage that, by allowing me to worry about one crazy dependency at a time.</p>

<p>When I design for new features, I mostly write design tests that describe the new behavior I want to implement. With the nice green field of a new interface, I need JMock to encourage me to clarify the interaction I need. Whenever my production code attempts to use a collaborator, JMock effectively reminds me to ensure that I want that interaction. Most importantly, JMock stops me from introducing dependencies that I don’t need.</p>

<p>I really like Fred Brooks’ use of the terms <em>essential complexity</em> and <em>accidental complexity</em>. Briefly, a code base’s <em>essential</em> complexity reflects the complexity of the problem. Automating tax audits will result in high essential complexity. A code base’s <em>accidental complexity</em> reflects the complexity we programmers add because we don’t design simply. In short, if it isn’t essential complexity, then it’s accidental complexity. Our job as designers includes minimising accidental complexity.</p>

<p>Mockito helps me tolerate high accidental complexity while I work to reduce it.</p>

<p>JMock tries its best to stop me from introducing accidental complexity.</p>

<p>That explains why I use JMock when designing for new features and why I’ll recommend using Mockito for rescuing legacy code.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Stub your data access layer; it won't hurt]]></title>
    <link href="http://blog.thecodewhisperer.com/2010/09/23/stub-your-data-access-layer-it-wont-hurt/"/>
    <updated>2010-09-23T00:00:00+03:00</updated>
    <id>http://blog.thecodewhisperer.com/2010/09/23/stub-your-data-access-layer-it-wont-hurt</id>
    <content type="html"><![CDATA[<p>I came across this question on the <code>testdrivendevelopment</code> Yahoo! group.</p>
<blockquote>
<p>Hi everyone,</p>
<p>I&#8217;d like some advice/opinions on how to test some existing code. It&#8217;s a web
application using Spring and struts.</p>
<p>I have a class called the ProcessedFilesManager which contains a number of
methods used by Struts Action classes. This manager communicates with five
different DAOs to get the information that some of the Struts actions are
interested in. Now, I want to test this manager class
(ProcessedFilesManager). The way I&#8217;ve started doing it is stubbing up each
of the five DAOs, however, this is proving to be quite painful. I didn&#8217;t
want to use a mocking approach, nor did I want to use a DB solution like
Hypersonic, but now I&#8217;m open to suggestions.</p>
<p>Seeing as there a number of approaches I could use, what do you think would
be best for this situation?</p>
<p>It feels wrong to stub the DAOs because what if I&#8217;m introducing behaviour in
there that differs from the actual DAOs? My tests will not be accurate.</p>
<p>Any advice/comments would be much appreciated.</p>
<p><a href="http://bit.ly/c6MZWa">Read the thread</a></p>
</blockquote>
<p>I used to have this fear, and I do something now that has eliminated that fear.</p>
<p>When I stub a <span class="caps">DAO</span> method, I make an assumption about what that <span class="caps">DAO</span> method does. I used to be worried about making the wrong assumption, but now I have a contract test for the <span class="caps">DAO</span> interface that tests for the assumption I&#8217;m making in my Service test. The contract test gives me confidence that any implementation of the <span class="caps">DAO</span> method passes the same tests, so every implementation of that <span class="caps">DAO</span> method behaves the way I assume it does. Once I have this, I feel comfortable stubbing that <span class="caps">DAO</span> method that way in a Service test.</p>
<p>A contract test is a test for an interface. I describe contract tests in some detail in <a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FJUnit-Recipes-Practical-Methods-Programmer%2Fdp%2F1932394230%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1199051730%26sr%3D8-1&amp;tag=masterprogram-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">JUnit Recipes</a>, recipe 2.6, although back then I called them &#8220;abstract test cases&#8221; because I hadn&#8217;t yet discovered the better name &#8220;contract test&#8221;. If you prefer, I&#8217;ve provided a diagram showing some contract tests for a typical <span class="caps">DAO</span> class.</p>
<p><img src="http://images.jbrains.ca/StubYourWorriesAway/ContractTests.jpg" style="width: 100%; align: center;" alt="" /></p>
<p>Since classes inherit methods from their superclasses, the <code>Hibernate Customer DAO Test</code> will inherit the <em>contract tests</em> from its superclass, as will the <code>JDBC Customer DAO Test</code>. This means that each implementation has to pass not only its own tests (like <code>testClosesSession()</code> or <code>testClosesResultSet()</code>) but also the tests inherited from <code>Customer DAO Contract Test Template</code>. (I call it a &#8220;template&#8221; because it plays the role of template in the Template Method design pattern.) When you test-drive a new implementation of <code>Customer DAO</code>, simply make the new test extend the contract test template and you&#8217;ll automatically inherit its contract tests. This way, I have confidence that any implementation of <code>Customer DAO</code> behaves the way I&#8217;d expect any <code>Customer DAO</code> to behave.</p>
<p>Returning to our example, these contract tests give me confidence to stub the <span class="caps">DAO</span> when I test-drive the Service, and that confidence brings with it a happy side effect. I am confident that <code>findAllWithPendingOrders()</code> only returns customers with pending orders, so I don&#8217;t have to worry about that issue at all when I design the Service that reports all customers with pending orders. Now that I notice it, <code>Report All Customers With Pending Orders Service</code> is really just a <code>Report on Customers Service</code> that needs a <code>Customer Filter</code>, which could be a <code>Pending Orders Customer Filter</code>. I don&#8217;t think I would have felt comfortable with this level of generalization if I weren&#8217;t so confident in the way I&#8217;ve separated the responsibilities.</p>
<p>The next time you want to avoid stubbing a method because you&#8217;re worried you&#8217;ll make a wrong assumption about what the method does, try writing enough contract tests to give you the confidence you need. I think you&#8217;ll like the results.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[RSpec, have_tag(), Spec::Matcher and Nokogiri]]></title>
    <link href="http://blog.thecodewhisperer.com/2010/02/19/rspec-havetag-specmatcher-and-nokogiri/"/>
    <updated>2010-02-19T00:00:00+02:00</updated>
    <id>http://blog.thecodewhisperer.com/2010/02/19/rspec-havetag-specmatcher-and-nokogiri</id>
    <content type="html"><![CDATA[<p>One of my faithful readers at <a href="http://www.jbrains.ca">http://www.jbrains.ca</a> told me that he couldn’t find an RSS feed icon in his Firefox address bar. I thought I could implement that fairly easily, so I agreed to do it. In the process, I wrote this spec:</p>

<div><script src="https://gist.github.com/306627.js?file="></script>
<noscript><pre><code>context &quot;when looking at the address bar&quot; do
  it &quot;should display an RSS feed icon&quot; do
    # While I can't verify this directly, I can use
    # the information at http://bit.ly/abHZ9G as a
    # proxy for verifying this.
    template.stub!(:logged_in?).and_return(true)

    assigns[:postings] = []

    render &quot;/postings/index&quot;, :layout =&gt; true

    # How do I check that the RSS link tag has the correct @href attribute?
  end
end</code></pre></noscript></div>

<p>Ruby follows the Principle of Least Surprise, so I tried this:</p>

<div><script src="https://gist.github.com/306629.js?file="></script>
<noscript><pre><code>response.should have_tag(%Q(link[rel=&quot;alternate&quot;][type=&quot;application/rss+xml&quot;][title=&quot;RSS 2.0&quot;])) do
  with_attribute(:href =&gt; rss_url)
end</code></pre></noscript></div>

<p>That doesn’t work, as I found no <code>#with_attribute</code> nor anything like it. After I dug a little, I found out that I should write this:</p>

<div><script src="https://gist.github.com/306632.js?file="></script>
<noscript><pre><code>response.should have_tag(%Q(link[rel=&quot;alternate&quot;][type=&quot;application/rss+xml&quot;][title=&quot;RSS 2.0&quot;][href=?]), rss_url)</code></pre></noscript></div>

<p>I don’t like this, because it checks two things at once: it looks for an “RSS tag” and checks the <code>href</code> attribute. That HTML implemented the “RSS tag” as attributes on <code>&lt;link&gt;</code> creates the confusion. The extremist in me calls this an <a href="http://www.jbrains.ca/integrated_tests_are_a_scam">integrated test</a>, but I prefer not to go there today. Suffice it to say that when this check failed, I didn’t immediately know why, and I insist on immediately knowing why a check fails. When I’ve done this in the path with XPath assertions in XHTMLUnit or XMLUnit, I’ve resorted to writing duplicate checks that build on one another, so I tried that here:</p>

<div><script src="https://gist.github.com/306634.js?file="></script>
<noscript><pre><code>response.should have_tag(%Q(link[rel=&quot;alternate&quot;][type=&quot;application/rss+xml&quot;][title=&quot;RSS 2.0&quot;]))
response.should have_tag(%Q(link[rel=&quot;alternate&quot;][type=&quot;application/rss+xml&quot;][title=&quot;RSS 2.0&quot;][href=?]), rss_url)</code></pre></noscript></div>

<p>Here I sacrificed duplication to improve the clarity of the assertions. I just now noticed that that contradicts my usual rule that removing duplication matters more than improving clarity. I dno’t know what to say about that just yet. Even if I remove the duplicate code, I still have the duplicate check, so extracting to a method won’t really do much here. I want <code>#with_attribute</code>!</p>

<p>Not deterred, I tried introducing a custom RSpec matcher, since I don’t know what benefit that would give me, but it would benefit me somehow. When I tried to do that, RSpec told me that it couldn’t understand <code>response.should have_tag</code> because it couldn’t find a <code>has_tag?</code> on the response. I didn’t like the looks of the stack trace; I felt I would have to delve deeply into RSpec or <code>assert_select</code>, and I didn’t find myself in the mood to do either, so I switched to Nokogiri.</p>

<div><script src="https://gist.github.com/306635.js?file="></script>
<noscript><pre><code>Spec::Matchers.define :have_rss_feed_at do |rss_url_as_text|
  match do |response|
    html = Nokogiri::HTML(response.body)
    rss_link_tag = html.at(%Q(link[rel=&quot;alternate&quot;][type=&quot;application/rss+xml&quot;][title=&quot;RSS 2.0&quot;]))
    rss_link_tag[&quot;href&quot;].should == rss_url_as_text
  end

  failure_message_for_should do |response|
    &quot;expected to find RSS feed at #{rss_url_as_text} in response:\n#{response.body}&quot;
  end

  failure_message_for_should_not do |response|
    &quot;expected not to find RSS feed at #{rss_url_as_text} in response:\n#{response.body}&quot;
  end

  description do
    &quot;have an RSS feed at #{expected}&quot;
  end
end</code></pre></noscript></div>

<p>Here I got to write the spec the way I wanted to: assume you will find “RSS feed tag”, then check that its <code>href</code> attribute matches the right URL. If the response has no “RSS feed tag” at all, then complain violently, because of the higher severity of the mistake.</p>

<p>Of course, if you have another suggestion, I’d like to see it. Add your comment below.</p>

<p>Special thanks to <a href="http://bit.ly/a3P4aU">Frivolog</a> for helping me get the original <code>have_tag</code> code working.</p>
]]></content>
  </entry>
  
</feed>

