<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Steve Freeman &#187; Coding</title>
	<atom:link href="http://www.higherorderlogic.com/category/things-to-do-with-work/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.higherorderlogic.com</link>
	<description>Working software daily</description>
	<lastBuildDate>Mon, 24 Oct 2011 20:24:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Another reason not to log directly in your code</title>
		<link>http://www.higherorderlogic.com/2011/10/another-reason-not-to-log-directly/</link>
		<comments>http://www.higherorderlogic.com/2011/10/another-reason-not-to-log-directly/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 18:13:52 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Test-Driven]]></category>

		<guid isPermaLink="false">http://www.higherorderlogic.com/?p=815</guid>
		<description><![CDATA[I&#8217;ve been ranting for some time that it&#8217;s a bad idea directly to mix logging with production code. The right thing to do is to introduce a collaborator that has a responsibility to provide structured notifications to the outside world about what&#8217;s happening inside an object. I won&#8217;t go through the whole discussion here but, [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been ranting <a href="http://www.mockobjects.com/2007/04/test-smell-logging-is-also-feature.html" title="logging is alos a feature" target="_blank">for some time</a> that it&#8217;s a bad idea directly to mix logging with production code. The right thing to do is to introduce a collaborator that has a responsibility to provide structured notifications to the outside world about what&#8217;s happening inside an object. I won&#8217;t go through the whole discussion here but, somehow, I don&#8217;t think I&#8217;m winning this one.</p>

<p>Recently, a team I know provided another reason to avoid mixing production logging with code. They have a system that processes messages and have been asked to record all the accepted messages for later reconciliation with an upstream system. They did what most Java teams would do and logged incoming messages in the class that processes them. Then they associated a special appender with that class&#8217;s logger that writes its entries to a file somewhere for later checking. The appenders are configured in a separate <span class="caps">XML </span>file.</p>

<p>One day the inevitable happened and they renamed the message processing class during a refactoring. This broke the reference in the <span class="caps">XML </span>configuration and the logging stopped. It wasn&#8217;t caught for a little while because there wasn&#8217;t a test. So, lesson one is that, if it matters, there should have been a test for it. But this is a pretty rigorous team that puts a lot of effort into doing things right (I&#8217;ve seen much worse), so how did they miss it? </p>

<p>I think part of it is the effort required to test logging. A unit test won&#8217;t do because the structure includes configuration, and acceptance tests run slowly because loggers buffer to improve performance. And part of it is to do with using a side effect of system infrastructure to implement a service. There&#8217;s nothing in the language of the implementation code that describes the meaning of reporting received messages: &ldquo;it&#8217;s just logging&rdquo;.</p>

<p>Once again, if I want my code to do something, I should just say so&hellip;</p>

<p><em>Update:</em> I&#8217;ve had several responses here and on other media about how teams might avoid this particular failure. All of them are valid, and I know there are techniques for doing what I&#8217;m supposed to while using a logging framework.</p>

<p>I was trying to make a different point&mdash;that some code techniques seem to lead me in better directions than others, and that a logging framework isn&#8217;t one of them. Once again I find that the trickiness in testing an example like this is a clue that I should be looking at my design again. If I introduce a collaboration to receive structured notifications, I can separate the concepts of handling messages and reporting progress. Once I&#8217;ve split out the code to support the reconciliation messages, I can test and administer it separately&mdash;with a clear relationship between the two functions.</p>

<p>None of this guarantees a perfect design, but I find I do better if I let the code do the work.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2011/10/another-reason-not-to-log-directly/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Test-First Development 1968</title>
		<link>http://www.higherorderlogic.com/2011/10/test-first-development-1968/</link>
		<comments>http://www.higherorderlogic.com/2011/10/test-first-development-1968/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 14:06:40 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Test-Driven]]></category>

		<guid isPermaLink="false">http://www.higherorderlogic.com/?p=808</guid>
		<description><![CDATA[Seeing Kevlin Henney again at the Goto conference reminded me of a quotation he cited at Agile on the Beach last month. In 1968, NATO funded a conference with the then provocative title of Software Engineering. Many people feel that this is the moment when software development lost its way, but the report itself is [...]]]></description>
			<content:encoded><![CDATA[<p>Seeing <a href="https://twitter.com/#!/KevlinHenney" title="Kevlin Henney">Kevlin Henney</a> again at the <a href="http://gotocon.com/" title="Goto conference">Goto conference</a> reminded me of a quotation he cited at <a href="http://agileonthebeach.com/" title="Agile on the Beach">Agile on the Beach</a> last month.</p>

<p>In 1968, <span class="caps">NATO </span>funded a conference with the then provocative title of <em>Software Engineering</em>. Many people feel that this is the moment when software development lost its way, but <a href="http://homepages.cs.ncl.ac.uk/brian.randell/NATO/nato1968.PDF" title="NATO 1968 software engineering report">the report</a> itself is more lively that its title suggests.</p>

<p>It turns out that &#8220;outside in&#8221; development, with early testing is older than we thought. Here&#8217;s a quote from the report by <a href="http://en.wikipedia.org/wiki/Alan_Perlis" title="Alan Perlis">Alan Perlis</a>:</p>

<blockquote>I&#8217;d like to read three sentences to close this issue.
<ol>
 <li>A software system can best be designed if the testing is interlaced with the designing instead of being used after the design.</li>
 <li>A simulation which matches the requirements contains the control which organizes the design of the system.</li>
 <li>Through successive repetitions of this process of interlaced testing and design the model ultimately becomes the software system itself. I think that it is the key of the approach that has been suggested, that there is no such question as testing things after the fact with simulation models, but that in effect the testing and the replacement of simulations with modules that are deeper and more detailed goes on with the simulation model controlling, as it were, the place and order in which these things are done.</li>
</ol></blockquote>

<p>It&#8217;s all out there in our history, we just have to be able to find it.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2011/10/test-first-development-1968/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>An example of an unhedged software call option</title>
		<link>http://www.higherorderlogic.com/2011/09/an-example-of-an-unhedged-software-call-option/</link>
		<comments>http://www.higherorderlogic.com/2011/09/an-example-of-an-unhedged-software-call-option/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 22:36:57 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Agile Programming]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software culture]]></category>

		<guid isPermaLink="false">http://www.higherorderlogic.com/?p=743</guid>
		<description><![CDATA[At a client, we&#8217;ve been reworking some particularly hairy calculation code. For better or worse, the convention is that we call a FooFetcher to get hold of a Foo when we need one. Here&#8217;s an example that returns Transfers, which are payments to and from an account. In this case, we&#8217;re mostly getting hold of [...]]]></description>
			<content:encoded><![CDATA[<p>At a client, we&#8217;ve been reworking some particularly hairy calculation code. For better or worse, the convention is that we call a <em>FooFetcher</em> to get hold of a <em>Foo</em> when we need one. Here&#8217;s an example that returns Transfers, which are payments to and from an account. In this case, we&#8217;re mostly getting hold of Transfers directly because can identify them<sup>1</sup>.</p>



<pre>public interface TransferFetcher {
  Transfer      fetchFor(TransferId id);
  Transfer      fetchOffsetFor(Transfer transfer);
  Set&lt;Transfer&gt; fetchOutstandingFor(Client client, CustomerReference reference);
  Transfer      fetchFor(CustomerReference reference);
}</pre>



<p>This looks like a reasonable design&mdash;all the methods are to do with retrieving Transfers&mdash;but it&#8217;s odd that only one of them returns a collection of Transfers. That&#8217;s a clue.</p>

<p>When we looked at the class, we discovered that the <code>fetchOutstandingFor()</code> method has a different implementation from the other methods and pulls in several dependencies that only it needs. In addition, unlike the other methods, it has only one caller (apart from its tests, of course). It doesn&#8217;t really fit in the Fetcher implementation which is now inconsistent.</p>

<p>It&#8217;s easy to imagine how this method got added. The programmers needed to get a feature written, and the code already had a dependency that was concerned with Transfers. It was quicker to add a method to the existing Fetcher, even if that meant making it much more complicated, than to introduce a new collaborator. They <a href="http://www.higherorderlogic.com/2010/07/bad-code-isnt-technical-debt-its-an-unhedged-call-option/" title="unhedged call option" target="_blank">sold a Call Option</a>&mdash;they cashed in the immediate benefit at the cost of weakening the model. The team would be ahead so long as no-one needed to change that code.</p>

<p>The option got called on us. As part of our reworking, we needed to change how Transfer objects were constructed so we could handle a new kind of transaction. The structure we planned meant changing another object, say <code>Accounts</code>, to depend on a <code>TransferFetcher</code>, but the current implementation of <code>TransferFetcher</code> depended on <code>Accounts</code> to implement <code>fetchOutstandingFor()</code>. We had a dependency loop. We should have taken a diversion and moved the behaviour of <code>fetchOutstandingFor()</code> into an appropriate object, but then we had our own delivery pressures. In the end, we found a workaround that allowed us to finish the task we were in the middle of, with a note to come back and fix the Fetcher.</p>

<p>The cost of recovery includes not just the effort of investigating and applying a solution (which would have been less when the code was introduced) but also the drag on motivation. It&#8217;s a huge <a href="http://en.wikipedia.org/wiki/Gumption_trap" title="from Zen and the Art of Motrocycle Maintenance" target="_blank">gumption trap</a> to be making steady progress towards a goal and then be knocked off course by an unnecessary design flaw. The research described in <a href="http://www.progressprinciple.com/">The Progress Principal</a> suggests that small blockers like this have a disproportionate impact compared to their size. Time to break for a cup of tea.</p>

<p>I believe that software quality is a cumulative property. It&#8217;s the accumulation of many small good or bad design decisions that either make a codebase productive to work with or just too expensive to maintain.</p> 

<p>&hellip;and, right on cue, Rangwald talks about <a href="http://raganwald.posterous.com/javas-comb-over" title="Tyranny of the urgent" target="_blank">The Tyranny of the Urgent</a>.</p>

<hr/><br />
<p style="font-size: 0.8em;">1) The details of the domain have been changed to protect the innocent, so please don&#8217;t worry too much about the detail.</p>
<p style="font-size: 0.8em;">Thanks to @aparker42 for his comments</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2011/09/an-example-of-an-unhedged-software-call-option/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Is Dependency Injection like Facebook?</title>
		<link>http://www.higherorderlogic.com/2011/07/is-dependency-injection-like-facebook/</link>
		<comments>http://www.higherorderlogic.com/2011/07/is-dependency-injection-like-facebook/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 02:40:05 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/?p=641</guid>
		<description><![CDATA[The problem with social networks I think there&#8217;s a description in Paul Adams&#8217; talk about online vs. offline social networks of how Dependency Injection goes bad, particularly when using one of the many automated frameworks. Adams describes a research subject Debbie who, in &#8220;real life&#8221; has friends and contacts from very different walks of life. [...]]]></description>
			<content:encoded><![CDATA[<h2>The problem with social networks</h2>

<p>I think there&#8217;s a description in <a href="http://www.thinkoutsidein.com/blog/2010/04/presenting-the-real-life-social-network-at-the-ia-summit/" title="online vs. offline social networks" target="_blank">Paul Adams&#8217; talk about online vs. offline social networks</a> of how <a href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">Dependency Injection</a> goes bad, particularly when using one of the <a href="http://en.wikipedia.org/wiki/Spring_Framework" title="Spring" target="_blank">many</a> <a href="http://picocontainer.org/" title="Pico Container" target="_blank">automated</a> <a href="http://code.google.com/p/google-guice/" title="google guice" target="_blank">frameworks</a>.</p>
<img alt="" src="/images/di-friends-and-groups.png" title="Debbie's friends and groups" style="float: right; margin-left: 10px;" />

<p style="text-align: justify;">Adams describes a research subject Debbie who, in &ldquo;real life&rdquo; has friends and contacts from very different walks of life. She has friends from college with alternative lifestyles who post images from their favourite LA gay bars. She also trains local 10-year olds in competitive swimming. Both the college friends and swimming kids have &ldquo;friended&rdquo; her. She was horrified to discover that these two worlds had inadvertently become linked though her social networking account. </p>

<p>This is the &ldquo;<a href="http://www.facebook.com/" title="facebook" target="_blank">Facebook</a> problem&rdquo;. The assumption that all relationships are equivalent was good enough for college dorms but doesn&#8217;t really scale to the rest of the world, hence <a href="http://plus.google.com" title="Google+" target="_blank">Google+</a>. As Adams points out,</p>
<blockquote>Facebook itself is not the problem here. The problem here is that these are different parts of Debbie&#8217;s life that would never have been exposed to each other offline were linked online.</blockquote>

<p>Like most users, Debbie wasn&#8217;t thinking of the bigger picture when she bound the whole of her life together. She was just connecting to people she knew and commenting on some pictures of guys with cute buns.</p>

<h2>Simile alert!</h2>

<p>Let&#8217;s revisit the right-hand side of that illustration.</p>
<img alt="" src="/images/di-ports-and-adapters.png" title="Ports and Adapters" style="float: right; margin-left: 10px;"/>
<p style="text-align: justify;">This is <a href="http://www.natpryce.com" title="Nat Pryce" target="_blank">Nat</a>&#8216;s diagram for the <a href="http://alistair.cockburn.us/Hexagonal+architecture" title="ports and adapters" target="_blank">Ports and Adapters</a> pattern. It illustrates how some people (including us) think system components should be built, with the domain logic in the centre protected from the accidental complexity of the outside world by a layer of adapters. I do <em>not</em> want to have my web code inadvertently linked directly to my persistence code (or even connected to LA gay bars).</p>

<p>That&#8217;s the trouble with the use of DI frameworks in systems that I&#8217;ve seen, there&#8217;s only one level of relationship: get me an object from the container. When I&#8217;m adding a feature, I just want to get hold of some component&mdash;and here&#8217;s an easy way to do it. It takes a lot of rigour to step back at every access to consider whether I&#8217;m introducing a subtle link between components that really shouldn&#8217;t know about each other.</p>

<p>I know that most of the frameworks support managing different contexts but it seems that, frankly, that&#8217;s more thinking and organisation than most teams have time for at the beginning of a project. As for cleaning up after the fact, well it&#8217;s a good way to make a living if the company can afford it and you like solving complex puzzles. More critical, however, is that the Ports and Adapters structure is recursive. Trying to manage the environments of multiple levels of subsystem with most current containers would be, in <a href="http://peripateticaxiom.blogspot.com/" title="Keith Braithwaite" target="_blank">Keith Braithwaite</a>&#8216;s words, &ldquo;impossible and/or insane&rdquo;.</p>

<h2><code>new</code> again</h2>

<p>The answer, I believe, is to save the DI frameworks for the real boundaries of the system, the parts which might change from installation to installation. Otherwise, I gather object assembly into specialised areas of the code where I can build up the run-time structure of the system with the deft use of constructors and <code>new</code>. It&#8217;ll look a bit complex but no worse than the equivalent DI structure (and everyone should learn to read code that looks like lisp).</p>

<p>If I later find that I can&#8217;t get access to some component that I think I need, that&#8217;s not necessarily a bad thing. It&#8217;s telling me that I&#8217;m introducing a new dependency and sometimes that&#8217;s a hint that a component is in the wrong place, or that I&#8217;m trying to use it from the wrong place. The coding bump is a design feedback mechanism that I miss when I can just pull objects out of a container. If I do a good job, I should find that, most of the time, I have just the right components at the time that I need them.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2011/07/is-dependency-injection-like-facebook/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Machiavelli on code quality</title>
		<link>http://www.higherorderlogic.com/2010/04/machiavelli-on-code-quality/</link>
		<comments>http://www.higherorderlogic.com/2010/04/machiavelli-on-code-quality/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 08:04:22 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Agile Programming]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software culture]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/?p=488</guid>
		<description><![CDATA[As the doctors say of a wasting disease, to start with, it is easy to cure but difficult to diagnose. After a time, unless it has been diagnosed and treated at the outset, it becomes easy to diagnose but difficult to cure. &#8212;&#160;Nicolo Machiavelli, The Prince via Dee Hock, Birth of the Chaordic Age]]></description>
			<content:encoded><![CDATA[<blockquote>As the doctors say of a wasting disease, to start with, it is easy to cure but difficult to diagnose. After a time, unless it has been diagnosed and treated at the outset, it becomes easy to diagnose but difficult to cure.</blockquote>
<p style="text-align:right;">&mdash;&nbsp;Nicolo Machiavelli, <em>The Prince</em></p>
<em>via</em> Dee Hock, <i>Birth of the Chaordic Age</i>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2010/04/machiavelli-on-code-quality/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Calling an Oracle stored procedure with a Table parameter with Spring&#8217;s StoredProcedure class</title>
		<link>http://www.higherorderlogic.com/2010/02/calling-an-oracle-stored-procedure-with-a-table-parameter-with-springs-storedprocedure-class/</link>
		<comments>http://www.higherorderlogic.com/2010/02/calling-an-oracle-stored-procedure-with-a-table-parameter-with-springs-storedprocedure-class/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 23:08:00 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/?p=427</guid>
		<description><![CDATA[I don&#8217;t normally do this sort of thing, but this took my colleague Tony Lawrence and me a while to figure out and we didn&#8217;t find a good explanation on the web. This will be a very dull posting unless you need to fix this particular problem. Sorry about that. We happen to be using [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t normally do this sort of thing, but this took my colleague Tony Lawrence and me a while to figure out and we didn&#8217;t find a good explanation on the web. This will be a very dull posting unless you need to fix this particular problem. Sorry about that.</p>

<p>We happen to be using the Spring database helper classes to talk to Oracle with stored procedures. It turns out that there&#8217;s a bug in the driver that means that you have to jump through a few hoops to pass values in when the input parameter type is a table. This should be equivalent to an array, but apparently it isn&#8217;t, so you have to set up the callable statement correctly. Where to do this was not obvious (to us) in the Spring framework.</p>

<p>Here&#8217;s an example stored procedure declaration:</p>



<pre>CREATE TYPE VARCHARTAB IS TABLE OF VARCHAR2(255);

CREATE PACKAGE db_package {
  TYPE list_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
PROCEDURE a_stored_procedure(
  table_in IN list_type
)</pre>



<p>The <code>table_in</code> parameter type <code>list_type</code> is declared within a package, which means we can&#8217;t declare the parameter as an <code>OracleTypes.ARRAY</code> when setting up the statement.  Instead we declare it as the type of the table contents <code>OracleTypes.VARCHAR</code>

</p>



<pre>class MyProcedure extends StoredProcedure {
  public MyProcedure(DataSource dataSource) {
    super(dataSource, &quot;db_package.a_stored_procedure&quot;);
    declareParameter(new SqlParameter(&quot;table_in&quot;, 
                                      OracleTypes.VARCHAR));
    compile();
  }
  
  void call(String... values) {
    execute(withParameters(values));
  }</pre>



<p>Here&#8217;s the money quote. When setting up the parameter, you need to provide it with a <code>SqlTypeValue</code>.
Don&#8217;t use one of the helper base classes that come out of the box, but create an implementation directly. That gives you access to the <code>statement</code>, which you can cast and set appropriately.<br />
</p>
  


<pre>   private Map&lt;String, Object&gt; withParameters(String... values) {
      return ImmutableMap.of(&quot;table_in&quot;,
                             oracleIndexTableWith(50, values));
   }

   private  &lt;T&gt; SqlTypeValue 
   oracleIndexTableWith(final int elemMaxLen, final T... values) {
     return new SqlTypeValue() {
       @Override
       public void setTypeValue(
         PreparedStatement statement, int paramIndex, 
         int sqlType, String typeName) throws SQLException 
      {
         ((OracleCallableStatement)statement).setPlsqlIndexTable(
            paramIndex, values, values.length, values.length,  
            sqlType, elemMaxLen);
       }
     };
   }
}</pre>



<p>That&#8217;s it. Happy copy and paste.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2010/02/calling-an-oracle-stored-procedure-with-a-table-parameter-with-springs-storedprocedure-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keep tests concrete</title>
		<link>http://www.higherorderlogic.com/2009/09/keep-tests-concrete/</link>
		<comments>http://www.higherorderlogic.com/2009/09/keep-tests-concrete/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 12:01:07 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Agile Programming]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Test-Driven]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/?p=244</guid>
		<description><![CDATA[This popped up on a technical discussion site recently. The original question was how to write tests for code that invokes a method on particular values in a list. The problem was that the tests were messy, and the author was looking for a cleaner alternative. Here&#8217;s the example test, it asserts that the even-positioned [...]]]></description>
			<content:encoded><![CDATA[<p>This popped up on a technical discussion site recently. The original question was how to write tests for code that invokes a method on particular values in a list. The problem was that the tests were messy, and the author was looking for a cleaner alternative. Here&#8217;s the example test, it asserts that the even-positioned elements in the parameters are passed to <code>bar</code> in the appropriate sequence.</p>


<pre>public void testExecuteEven() {
  Mockery mockery = new Mockery();

  final Bar bar = mockery.mock(Bar.class);
  final Sequence sequence = new NamedSequence(&quot;sequence&quot;);

  final List&lt;String&gt; allParameters = new ArrayList&lt;String&gt;();
  final List&lt;String&gt; expectedParameters = new ArrayList&lt;String&gt;();

  for (int i = 0; i &lt; 3; i++) {
    allParameters.add(&quot;param&quot; + i);
    if (i % 2 == 0) {
      expectedParameters.add(&quot;param&quot; + i);
    }
  }
  final Iterator&lt;String&gt; iter = expectedParameters.iterator();

  mockery.checking(new Expectations() {
   {
     while (iter.hasNext()) {
       one(bar).doIt(iter.next());
        inSequence(sequence);
      }
    }
  });

  Foo subject = new Foo();
  subject.setBar(bar);
  subject.executeEven(allParameters);
  mockery.assertIsSatisfied();
}</pre>


<p>The intentions of the test are good, but its most striking feature is that there&#8217;s so much computation going on. This doesn&#8217;t need a new technique to make it more readable, it just needs to be simplified.</p>
<p>A unit test should be small and focussed enough that we don&#8217;t need any general behaviour. It just has to deal with one example, so we can make it as concrete as we like. With that in mind, we can collapse the test to this:</p>


<pre>public void testCallsDoItOnEvenIndexedElementsInList() {
  final Mockery mockery = new Mockery();
  final Bar bar = mockery.mock(Bar.class);
  final Sequence evens = mockery.sequence(&quot;evens&quot;);

  final  List&lt;String&gt; params = 
    Arrays.asList(&quot;param0&quot;, &quot;param1&quot;, &quot;param2&quot;, &quot;param3&quot;);

  mockery.checking(new Expectations() {{
    oneOf(bar).doIt(params.get(0)); inSequence(evens);
    oneOf(bar).doIt(params.get(2)); inSequence(evens);
  }});

  Foo subject = new Foo();
  subject.setBar(bar);
  subject.executeEven(params);
  mockery.assertIsSatisfied();
}</pre>


<p>To me, this is more direct, a simpler statement of the example&mdash;if nothing else, there&#8217;s just less code to understand. I don&#8217;t need any loops because there aren&#8217;t enough values to justify them. The expectations are clearer because they show the indices of the elements I want from the list (an alternative would have been to put in the expected values directly). And if I pulled the common features, such as the mockery and the target object, into the test class, the test would be even shorter.</p>
<p>The short version of this post is: be wary of any general behaviour written into a unit test. The scope should be small enough that values can be coded directly. Be especially wary of anything with an <code>if</code> statement. If the data setup is more complicated, then consider using a <a href="http://nat.truemesh.com/archives/000714.html">Test Data Builder</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2009/09/keep-tests-concrete/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IWonderAboutInterfaceNames</title>
		<link>http://www.higherorderlogic.com/2009/04/spreading-the-word-on-roles/</link>
		<comments>http://www.higherorderlogic.com/2009/04/spreading-the-word-on-roles/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 13:52:32 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/blog/2009/04/27/spreading-the-word-on-roles/</guid>
		<description><![CDATA[InfoQ has just published Udi Dahan&#8217;s talk from QCon 2008 on &#8220;Intentions and Interfaces&#8221;. It&#8217;s good to see the message about focussing on Roles rather than Classes being pitched to a new audience. That&#8217;s what we were trying to talk about in our &#8220;Mock Roles, Not Objects&#8221; paper. I wonder, however, about his style for [...]]]></description>
			<content:encoded><![CDATA[<p>InfoQ has just published <a href="http://www.infoq.com/presentations/Making-Roles-Explicit-Udi-Dahan">Udi Dahan&#8217;s talk from QCon 2008</a> on &#8220;Intentions and Interfaces&#8221;. It&#8217;s good to see the message about focussing on Roles rather than Classes being pitched to a new audience. That&#8217;s what we were trying to talk about in our <a href="http://www.mockobjects.com/files/mockrolesnotobjects.pdf">&#8220;Mock Roles, Not Objects&#8221; paper</a>.</p>

<p>I wonder, however, about his style for naming roles:</p>


<pre>interface IMakeCustomerPreferred {
  void MakePreferred();
}
interface IAddOrdersToCustomer {
  void AddOrder(Order order);
}</pre>



<p>It took me a little while to figure it out, but to me the issue is that these interface names bind the role to the underlying implementation, or at least to a larger role. One of the things that Nat Pryce and I discuss in <a href="http://www.mockobjects.com/book">our book</a> is that interfaces need refactoring too. If two interfaces are similar, perhaps there&#8217;s a common concept there and they should be collapsed&mdash;which brings us more pluggable code. This implies that roles, as described by interfaces, should aim to be context-independent. In this case, I might rename one of the interfaces to:</p>



<pre>interface IOrderCollector {
  void AddOrder(Order order)
}</pre>



<p>since there will be contexts in which I really don&#8217;t care that it happens to be a Customer.
That said, I think Dahan has other motivations with this naming scheme, since he also uses it to control retrieval from the <span class="caps">ORM, </span>but there might be other ways to achieve that.</p>

<span style="font-size:0.9em; margin=2em;"><p>A colleague was once accused of being so role-happy, that he defined an Integer as a combination of Addable, Subtractable, Multipliable, and Divideable.</p></span>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2009/04/spreading-the-word-on-roles/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Java synchronisation bug on OS/X?</title>
		<link>http://www.higherorderlogic.com/2009/03/java-synchronisation-bug-on-osx/</link>
		<comments>http://www.higherorderlogic.com/2009/03/java-synchronisation-bug-on-osx/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 11:06:42 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Test-Driven]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/blog/2009/03/18/java-synchronisation-bug-on-osx/</guid>
		<description><![CDATA[I&#8217;ve come across what might be a synchronisation bug while working on the book. The end-to-end tests for our example application use the WindowLicker framework to drive the Swing user interface. Our test infrastructure starts the application up in another thread (it&#8217;s as close as we can get to running from the command line), then [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve come across what might be a synchronisation bug while working on <a href="http://www.mockobjects.com/book/">the book</a>.</p>

<p>The end-to-end tests for our example application use the <a href="http://code.google.com/p/windowlicker/"> WindowLicker</a> framework to drive the Swing user interface. Our test infrastructure starts the application up in another thread (it&#8217;s as close as we can get to running from the command line), then creates a WindowLicker driver which, eventually, creates a Java <span class="caps">AWT</span> Robot. It turns out (we think) that this means that we have two threads trying to load and initialise the <span class="caps">AWT </span>library in parallel, which hangs. Our workaround is to call a delaying method before creating the WindowLicker Driver:</p>


<pre>private void 
makeSureAwtIsLoadedBeforeStartingTheDriverOnOSXToStopDeadlock() {
  try {
    SwingUtilities.invokeAndWait(
      new Runnable() { public void run() {} });
  } catch (Exception e) {
    throw new Defect(e);
  }
}</pre>



<p>That&#8217;s not really what <code>invokeAndWait()</code> is for, but it solves our problem until we can find a better answer, and we hope that the hack is at least self-explanatory.</p>

<p>Does anyone have a better explanation or fix? OS/X 10.5.6, Java 1.5.0_16, White MacBook 2.4 GHz Intel Core Duo. <a href="http://www.natpryce.com">Nat</a>&#8216;s Linux installation works fine.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2009/03/java-synchronisation-bug-on-osx/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mock Roles not Objects, live and in person.</title>
		<link>http://www.higherorderlogic.com/2009/03/mock-roles-not-objects-live-and-in-person/</link>
		<comments>http://www.higherorderlogic.com/2009/03/mock-roles-not-objects-live-and-in-person/#comments</comments>
		<pubDate>Sun, 08 Mar 2009 22:07:51 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Agile Programming]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Test-Driven]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/blog/2009/03/08/mock-roles-not-objects-live-and-in-person/</guid>
		<description><![CDATA[At the recent Software Craftsmanship conference in London, Willem and Marc ran a session on Responsibility-Driven Development with Mocks for about 30 people. Nat Pryce and I were sitting at the back watching and occasionally heckling. The first striking thing was that when Willem and Marc asked who was using &#8220;Mock Objects&#8221; most everyone put [...]]]></description>
			<content:encoded><![CDATA[<p>At the recent Software Craftsmanship conference in London, Willem and Marc ran <a href="http://parlezuml.com/softwarecraftsmanship/sessions/responsibility_driven_design_with_mock_objects.htm">a session on Responsibility-Driven Development with Mocks</a> for about 30 people. <a href="http://www.natpryce.com/">Nat Pryce</a> and I were sitting at the back watching and occasionally heckling. </p>

<p>The first striking thing was that when Willem and Marc asked who was using &#8220;Mock Objects&#8221; most everyone put their hand up (which was nice), but then only a handful also said they were thinking about Roles and Responsibilities when they did (which was frustrating). We first wrote up these ideas in our paper <a href="http://www.mockobjects.com/files/mockrolesnotobjects.pdf">&#8220;Mock Roles Not Objects&#8221;</a> and much of the difficulty we see people have with the technique of Mock Objects comes from focussing on classes rather than relationships.</p> 

<p>As it happens, an example popped up in the rest of the session, which was run as a Coding Dojo. What was interesting to me was how the group managed to turn around its design ideas. Here&#8217;s what I can remember about how it worked out.</p>

<p>The domain was some kind of game, with a hero who moves around an environment slaying dragons and so forth. The first couple of stories were to do with displaying the current room, and then moving from one room to another. It was a little difficult getting started because the limitations of the event didn&#8217;t allow enough time to really drive the design from outer-level requirements, but the group managed to get started with something like:</p>



<pre>describe Hero do
  it &quot;should describe its surroundings&quot; do
    hero = Hero.new(room)  
    
    room.stub!(:description).and_return(&quot;a room with twisty passages&quot;)
    
    console.should_receive(:show).with(&quot;in a room with twisty passages&quot;)
    hero.look(console)
  end
end</pre>

<p>  </p>

<p>The expectation here says that when looking, the hero should write a text describing the room to the console. This was a place to start, but it doesn&#8217;t look right. Why is a hero attached to a room? And <code>hero.look(console)</code> just doesn&#8217;t read well, it&#8217;s hard to tell what it means. The tensions became clearer with the next feature, which was to have the hero move from one room to another. If we write</p>



<pre>hero.move_to(other_room)</pre>


  <br />
<p>how can we tell that this has worked? We could ask the hero to <code>look()</code> again, but that means making an extra call for testing, which is not related to the intent of the test. We could ask the hero what his current room is, but that&#8217;s starting to leak into Asking rather than Telling. There may be a need for the hero to hold on to his current location, but we haven&#8217;t seen it yet.</p>

<p>Suddenly, it became clear that the dependencies were wrong. We already have a feature that can be told about the hero&#8217;s situation, which we can build on. If the feature were to be told about what is happening to the hero, we could use <em>that</em> to detect the change in room. So, our example now becomes:</p>



<pre>describe Hero do
  it &quot;should move to a room&quot; do
    hero = Hero.new(console)  
    
    room.stub!(:description).and_return(&quot;a room with twisty passages&quot;)
    
    console.should_receive(:show).with(&quot;in a room with twisty passages&quot;)
    
    hero.move_to(room)
  end
end</pre>



<p>That&#8217;s better, but it&#8217;s not finished. The term Console sounds like an implementation, not a role. Most of the sword-wielding adventurers that I know don&#8217;t know how to work a Console, but they&#8217;re quite happy to tell of their great deeds to, say, a Narrator (as <a href="http://blog.davidpeterson.co.uk/">David Peterson</a> suggested). If we adjust our example we get.</p>



<pre>describe Hero do
  it &quot;should move to a room&quot; do
    hero = Hero.new(narrator)  
    
    room.stub!(:description).and_return(&quot;a room with twisty passages&quot;)
    
    narrator.should_receive(:says).with(&quot;in a room with twisty passages&quot;)
    
    hero.move_to(room)
  end
end</pre>



<p>The whole example now reads as if it&#8217;s in the same domain, in the language of a <span class="caps">D&amp;D </span>game. It doesn&#8217;t refer to implementation details such as a Console&mdash;we might see that code when we get to the detailed implementation of a Narrator. Obviously, there&#8217;s a lot more we could do, for a start I&#8217;d like to see more structured messages between Hero and Narrator, but the session ran out of time at about this point.</p>

<p>Some lessons:</p>
<ol>
<li>Naming, naming, naming. It&#8217;s the most important thing. A coherent unit of code should have a coherent vocabulary, it should <em>read well</em>. If not, I&#8217;m probably mixing concepts which will make the code harder to understand and more brittle to change than it needs to be.</li>
<li>When I&#8217;m about to write a test, I ask &#8220;if this were to work, who would know&#8221;. That&#8217;s the most revealing question in B/TDD. If there&#8217;s no visible effect from an event, except perhaps for changing a field in the target object, then maybe it&#8217;s worth waiting until there is a visible effect, or maybe there&#8217;s a concept missing, or maybe the structure isn&#8217;t quite right. Before writing more code, I try to make sure I understand its motivation.</li>
</ol>

<p>Willem&#8217;s (and many other people&#8217;s) approach is slightly different. He likes to explore a bit further with the code before really sorting out the names, and he&#8217;s right that there&#8217;s a risk of Analysis-Paralysis. I do that occasionally, but my experience is that the effort of being really picky at this stage forces me to be clearer about what I&#8217;m trying to achieve, to ask those questions I really ought to have answers to, before I get in too deep.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2009/03/mock-roles-not-objects-live-and-in-person/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SOLID Development Principles – In Motivational Pictures</title>
		<link>http://www.higherorderlogic.com/2009/02/solid-development-principles-%e2%80%93-in-motivational-pictures/</link>
		<comments>http://www.higherorderlogic.com/2009/02/solid-development-principles-%e2%80%93-in-motivational-pictures/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 10:25:41 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software culture]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/blog/2009/02/12/solid-development-principles-%e2%80%93-in-motivational-pictures/</guid>
		<description><![CDATA[Excellent series of images from Derick Bailey. Here&#8217;s an example: Single Responsibility Principle Just because you can, doesn&#8217;t mean you should. RT @Jtf]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.lostechies.com/blogs/derickbailey/archive/2009/02/11/solid-development-principles-in-motivational-pictures.aspx">Excellent series of images</a> from Derick Bailey. Here&#8217;s an example:</p>

<div style="padding-left: 2em">
<h4>Single Responsibility Principle</h4>
<p><em>Just because you can, doesn&#8217;t mean you should.</em></p>
<p><img src="/images/SingleResponsibilityPrinciple.jpg" alt="Swiss Army Knife" /></p>
</div>
<p style="font-size: 0.8em">RT <a href="http://blog.jeffreyfredrick.com/">@Jtf</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2009/02/solid-development-principles-%e2%80%93-in-motivational-pictures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Expressiveness makes the difference</title>
		<link>http://www.higherorderlogic.com/2008/12/expressiveness-makes-the-difference/</link>
		<comments>http://www.higherorderlogic.com/2008/12/expressiveness-makes-the-difference/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 21:44:12 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software culture]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/blog/2008/12/17/expressiveness-makes-the-difference/</guid>
		<description><![CDATA[I was chatting with Keith about what the Software Craftsmanship event should really be about, in the context of a discussion of whether some of Jason Gorman&#8217;s list of guitar heroes are actually worth listening to (you still with me?) 1. The next obscure piece of evidence is Maurice Murphy&#8217;s YouTube masterclass. For those who [...]]]></description>
			<content:encoded><![CDATA[<p>I was chatting with <a href="http://peripateticaxiom.blogspot.com/">Keith</a> about what the <a href="http://parlezuml.com/softwarecraftsmanship/">Software Craftsmanship</a> event should really be about, in the context of a discussion of whether some of Jason Gorman&#8217;s <a href="http://parlezuml.com/blog/?postid=592">list of guitar heroes</a> are actually worth listening to (you still with me?) <sup>1</sup>.</p>

<p>The next obscure piece of evidence is Maurice Murphy&#8217;s <a href="http://uk.youtube.com/watch?v=cINXfDwRj0c">YouTube masterclass</a>. For those who don&#8217;t know, Maurice Murphy has been Principal Trumpet in the London Symphony Orchestra for years (nerds without an interest in orchestral music will nonetheless have heard him on the Star Wars sound tracks). What&#8217;s interesting about the video is that what they emphasise most is being musical, making sense of the melody. They have no interest in pyrotechnics and assume that the student knows the basics.</p>

<p>The (barely sustainable) link with master-level coding and performance, we realised, is that both are about being expressive. The master coder/performer has a point of view and they use their considerable technical skills to get it across. The code that really impresses me is almost entirely about the domain, it just reads well. Most of the code most of us see, however,  is stuck a level below, I have to read <em>through</em> the implementation to get to the meaning.</p>

<p>Years ago an <a href="http://people.cs.vt.edu/dtatar/">old friend of mine</a> said that when she first started going to conferences she wouldn&#8217;t be impressed by some of the big names because what they said was obvious. Later, she learned that being obvious can be really hard.</p>

<p><hr/><br />
<span style="text-indent: 2em;">1) <i>Disclaimer</i> I never was into rock guitar heroes, so Jason&#8217;s post was a bit academic for me.</span></p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2008/12/expressiveness-makes-the-difference/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unpack the bag</title>
		<link>http://www.higherorderlogic.com/2008/09/unpack-the-bag/</link>
		<comments>http://www.higherorderlogic.com/2008/09/unpack-the-bag/#comments</comments>
		<pubDate>Sat, 06 Sep 2008 20:35:31 +0000</pubDate>
		<dc:creator>steve.freeman</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.m3p.co.uk/blog/2008/09/06/unpack-the-bag/</guid>
		<description><![CDATA[There&#8217;s a common pattern where an object is constructed with a Context object that carries all the dependencies the new object might need. It&#8217;s often used, for example, with classes that package up domain behaviour based on lower-level services, something like this: public class PriceReconciler { private final Context context; public PriceReconciler(Context context) { this.context [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a common pattern where an object is constructed with a Context object that carries all the dependencies the new object might need. It&#8217;s often used, for example, with classes that package up domain behaviour based on lower-level services, something like this:</p>



<pre>public class PriceReconciler {
  private final Context context;

  public PriceReconciler(Context context) {
    this.context = context;
  }

  public boolean isAvailable(Item item, Price price) {
     Location location = 
        context.getLocationFinder().findLocationFor(item);
     SKU sku = location.lookup(item);
     return context.getCurrencyConverter()
                        .compare(price, sku.cost()) &lt; 0;
  }
 // and so on...
}</pre>



<img width="160" height="200" style="float: right; margin-left:0.6em;"
src="http://www.m3p.co.uk/images/mary-poppins-flying.jpeg" alt="Mary Poppins" />
<span style="text-align: justify"><p>Over time the Context gets used in more and more places, and acquires more and more contents to carry around. It starts to feel like Mary Poppins&#8217; carpet bag (<em>there&#8217;s</em> an old cultural reference) that contains a roomful of furniture. When everything is available everywhere then developers will use what they have in scope and, pretty soon, there are implicit dependencies all over the domain layer.
</p>
<p>A while ago, I was working with a class that used one of these context objects. The class was quite large so, to help us understand it, my pair and I extracted the services it used into fields:</p>
</span>



<pre>public class PriceReconciler {
  private final LocationFinder locationFinder;
  private final CurrencyConverter currencyConverter;
  private final LooseChangeCollector looseChangeCollector;

  public PriceReconciler(Context context) {
    this.locationFinder = context.getLocationFinder();
    this.currencyConverter = context.getCurrencyConverter();
    this.looseChangeCollector = 
      context.getLooseChangeCollector();
  }
 // and so on...
}</pre>



<p>Doing this made clear that the class used only three of the many services available on the context. More interesting, it showed that the <code>looseChangeCollector</code> was only used once, in a method that turned out to be referenced just once&mdash;by a class that also had access to the context. Our extraction highlighted that this behaviour was in the wrong place, it didn&#8217;t really have a relationship with the rest of <code>PriceReconciler</code>, so we moved it to its calling object and simplified the <code>PriceReconciler</code>. With just two dependencies, our
next step was to set them directly in the constructor</p>



<pre>public class PriceReconciler {
  private final LocationFinder locationFinder;
  private final CurrencyConverter currencyConverter;

  public PriceReconciler(LocationFinder locationFinder, 
                         CurrencyConverter currencyConverter) 
 {
    this.locationFinder = locationFinder;
    this.currencyConverter = currencyConverter;
  }
 // and so on...
}</pre>



<p>which made the <code>PriceReconclier</code> just a little easier to reuse since we&#8217;d narrowed its dependencies.</p>

<p>Kent Beck <a href="http://www.threeriversinstitute.org/AbstractVsConcreteParameters.html">wrote recently</a> about this tension between being concrete and abstract parameters. There obviously isn&#8217;t a single answer, except to note that when two or three objects keep turning up together, there&#8217;s probably a missing intermediate concept where some of the behaviour really belongs. The trick, when turning that concept into a type, is to give it a meaningful name so that  it&#8217;s hard to add features that don&#8217;t belong.</p>]]></content:encoded>
			<wfw:commentRss>http://www.higherorderlogic.com/2008/09/unpack-the-bag/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

