<?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>Casual Miracles &#187; Blog</title>
	<atom:link href="http://www.casualmiracles.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.casualmiracles.com</link>
	<description></description>
	<lastBuildDate>Mon, 16 Jan 2012 22:34:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>A Small Example of Applicative Functors with Scalaz</title>
		<link>http://www.casualmiracles.com/2012/01/16/a-small-example-of-applicative-functors-with-scalaz/</link>
		<comments>http://www.casualmiracles.com/2012/01/16/a-small-example-of-applicative-functors-with-scalaz/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 22:32:18 +0000</pubDate>
		<dc:creator>channing</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/?p=689</guid>
		<description><![CDATA[I recently blogged about Functors and mentioned a mysterious beast called Applicative Functor. Here is a simple, complete example that shows how you can use Applicative Functors with the Scalaz library, with references for further reading. What&#8217;s the Problem? Given <a href="http://www.casualmiracles.com/2012/01/16/a-small-example-of-applicative-functors-with-scalaz/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I recently <a href="http://www.casualmiracles.com/2012/01/08/a-small-functor-example/">blogged</a> about Functors and mentioned a mysterious beast called <em>Applicative Functor</em>. Here is a simple, complete example that shows how you can use Applicative Functors with the <a href="http://code.google.com/p/scalaz/" title="Scalaz">Scalaz</a> library, with references for further reading.<br />
<span id="more-689"></span></p>
<h3>What&#8217;s the Problem?</h3>
<blockquote><p>Given a function that takes multiple arguments A,B,… that returns a Result, how can that function by applied to arguments M[A], M[B],… and get M[Result]?</p></blockquote>
<p>where M is an Option, List, etc.</p>
<h3>Applicative Functors</h3>
<p>To understand the mechanics of how applicative functors solve our problem, please refer to the references below, in particular Heiko Seeberger&#8217;s <a href="http://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/">Applicatives are generalized functors</a>.</p>
<p>What I present below is an example of use. I hope you can take it away and benefit from it without necessarily understanding the theory. However, I thoroughly recommend further reading and study, its fun and you will gain much deeper insights.</p>
<p>So without further ado, here&#8217;s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">import</span> scalaz.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">import</span> Scalaz.<span style="color: #000080;">_</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">object</span> Applicatives <span style="color: #0000ff; font-weight: bold;">extends</span> App <span style="color: #F78811;">&#123;</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * Lets assume some Options which must be applied to a function.
   */</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> x<span style="color: #000080;">:</span>Option<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">2</span>.<span style="color: #000000;">some</span> <span style="color: #004000; font-style: italic;">// scalaz enrichment for options</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> y<span style="color: #000080;">:</span>Option<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">3</span>.<span style="color: #000000;">some</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> z<span style="color: #000080;">:</span>Option<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">5</span>.<span style="color: #000000;">some</span>
&nbsp;
  <span style="color: #004000; font-style: italic;">// Lets add them without applicative functors</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> usingFor <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>theX <span style="color: #000080;">&lt;</span>- x<span style="color: #000080;">;</span> theY <span style="color: #000080;">&lt;</span>- y<span style="color: #000080;">;</span> theZ <span style="color: #000080;">&lt;</span>- z<span style="color: #F78811;">&#41;</span> 
                   <span style="color: #0000ff; font-weight: bold;">yield</span> theX + theY + theZ
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">val</span> usingMaps <span style="color: #000080;">=</span> x flatMap 
                    <span style="color: #F78811;">&#40;</span>theX <span style="color: #000080;">=&gt;</span> y flatMap 
                      <span style="color: #F78811;">&#40;</span>theY <span style="color: #000080;">=&gt;</span> z map 
                        <span style="color: #F78811;">&#40;</span>theZ <span style="color: #000080;">=&gt;</span> theZ + theY + theX<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/* With scalaz we can do the following instead of for or maps
   * First we need to put the function in the right form, curried.
   * To understand why please read the references I've given below.
   */</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> addInts <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span> <span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">:</span>Int, b<span style="color: #000080;">:</span>Int, c<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> a + b + c <span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">curried</span>
&nbsp;
  <span style="color: #004000; font-style: italic;">// apply the function to x, y and z</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> sum <span style="color: #000080;">=</span> x <span style="color: #000080;">&lt;*&gt;</span> <span style="color: #F78811;">&#40;</span>y <span style="color: #000080;">&lt;*&gt;</span> <span style="color: #F78811;">&#40;</span>z map addInts<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #004000; font-style: italic;">// Some(10)</span>
&nbsp;
  <span style="color: #004000; font-style: italic;">// Scalaz offers an alternative syntax that is easier to use</span>
  <span style="color: #F78811;">&#40;</span>x |<span style="color: #000080;">@</span>| y |<span style="color: #000080;">@</span>| z<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span><span style="color: #000080;">_</span> + <span style="color: #000080;">_</span> + <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span>   <span style="color: #004000; font-style: italic;">// Some(10)</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * If one of the options is a none
   * then the result of the whole expression will be none.
   */</span>
  <span style="color: #F78811;">&#40;</span>x |<span style="color: #000080;">@</span>| none<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span><span style="color: #000080;">_</span> + <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> <span style="color: #004000; font-style: italic;">// None</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * The function can be any method, including 'apply'
   */</span>
  <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #0000ff; font-weight: bold;">class</span> Person<span style="color: #F78811;">&#40;</span>age<span style="color: #000080;">:</span> Int, height<span style="color: #000080;">:</span>Double, name<span style="color: #000080;">:</span> String<span style="color: #F78811;">&#41;</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * Person.apply method is a function (Int, Double, String) =&gt; Person
   */</span>
  <span style="color: #F78811;">&#40;</span>some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span> |<span style="color: #000080;">@</span>| some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1.1</span><span style="color: #F78811;">&#41;</span> |<span style="color: #000080;">@</span>| none<span style="color: #F78811;">&#91;</span>String<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>Person.<span style="color: #000000;">apply</span> <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span>  
  <span style="color: #004000; font-style: italic;">// none</span>
&nbsp;
  <span style="color: #F78811;">&#40;</span>some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">4</span><span style="color: #F78811;">&#41;</span> |<span style="color: #000080;">@</span>| some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1.1</span><span style="color: #F78811;">&#41;</span> |<span style="color: #000080;">@</span>| <span style="color: #6666FF;">&quot;Angelica&quot;</span>.<span style="color: #000000;">some</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>Person.<span style="color: #000000;">apply</span> <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> 
  <span style="color: #004000; font-style: italic;">// Some(Person(4, 1.1, Angelica))</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * The beauty of this is that it works with ANY higher kind, eg. List
   * or your own types!
   */</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> l1 <span style="color: #000080;">=</span> <span style="color: #F78811;">1</span> <span style="color: #000080;">::</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">::</span> Nil
  <span style="color: #0000ff; font-weight: bold;">val</span> l2 <span style="color: #000080;">=</span> <span style="color: #F78811;">3</span> <span style="color: #000080;">::</span> <span style="color: #F78811;">4</span> <span style="color: #000080;">::</span> Nil
&nbsp;
  <span style="color: #F78811;">&#40;</span>l1 |<span style="color: #000080;">@</span>| l2<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span><span style="color: #000080;">_</span> + <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> <span style="color: #004000; font-style: italic;">// List(4, 5, 5, 6)</span>
  <span style="color: #F78811;">&#40;</span><span style="color: #000080;">&lt;</span>xml/<span style="color: #000080;">&gt;</span> |<span style="color: #000080;">@</span>| <span style="color: #000080;">&lt;</span>xml2/<span style="color: #000080;">&gt;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#123;</span><span style="color: #000080;">_</span> ++ <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> <span style="color: #004000; font-style: italic;">// List(&lt;xml&gt;&lt;/xml&gt;&lt;xml2&gt;&lt;/xml2&gt;)</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<h4>Further Reading</h4>
<ul>
<li>Learn You a Haskell&#8217;s Chapter on <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids">Functors, Applicative Functors and Monoids</a>
<li>Heiko Seeberger&#8217;s <a href="http://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/">Applicatives are generalized functors</a>
<li><a href="http://scalaz.github.com/scalaz/scalaz-2.9.1-6.0.2/doc.sxr/scalaz/example/ExampleApplicative.scala.html#23252">Scalaz Applicative Examples</a>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2012/01/16/a-small-example-of-applicative-functors-with-scalaz/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Small Functor Example</title>
		<link>http://www.casualmiracles.com/2012/01/08/a-small-functor-example/</link>
		<comments>http://www.casualmiracles.com/2012/01/08/a-small-functor-example/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 20:54:57 +0000</pubDate>
		<dc:creator>channing</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/?p=622</guid>
		<description><![CDATA[In the world of functional programming you will quickly come across the concept of a Functor. What I present below is a simple example that might provide some intuition, with references for further reading. What&#8217;s the Problem? We often want <a href="http://www.casualmiracles.com/2012/01/08/a-small-functor-example/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>In the world of functional programming you will quickly come across the concept of a Functor. What I present below is a simple example that might provide some intuition, with references for further reading.<br />
<span id="more-622"></span></p>
<h3>What&#8217;s the Problem?</h3>
<p>We often want to use a function that takes an instance of A and returns an instance of B in a context where we have an instance of <em>M[A]</em> and need an instance of <em>M[B]</em>. The most common example is the <em>map</em> method on List, Option, etc.</p>
<p>So the problem is: </p>
<blockquote><p>Given a function f that takes an A and returns a B, how can we construct a new function that takes an M[A] and returns an M[B] <strong>for any M</strong>?</p></blockquote>
<h3>Functors</h3>
<p>A Functor accepts a function, A ⇒ B, and returns a new function M[A] ⇒ M[B], where M is any <em>kind</em>.</p>
<p>So without further ado, here&#8217;s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> Functorise <span style="color: #0000ff; font-weight: bold;">extends</span> App <span style="color: #F78811;">&#123;</span>
&nbsp;
  <span style="color: #004000; font-style: italic;">// This is a Functor</span>
  <span style="color: #0000ff; font-weight: bold;">trait</span> Functor<span style="color: #F78811;">&#91;</span>M<span style="color: #F78811;">&#91;</span><span style="color: #000080;">_</span><span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
&nbsp;
    <span style="color: #008000; font-style: italic;">/* convert f into a function mapping M[A] to M[B]
     * eg. if M were List, and f was Int ⇒ String
     * fmap would yield List[Int] ⇒ List[String]
     */</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fmap<span style="color: #F78811;">&#91;</span>A, B<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>f<span style="color: #000080;">:</span> A ⇒ B<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> M<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span> ⇒ M<span style="color: #F78811;">&#91;</span>B<span style="color: #F78811;">&#93;</span>
  <span style="color: #F78811;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/* Here are a couple of examples for Option and List Functors
   * They are implicit so they can be used below in enrichWithFunctor
   */</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">object</span> OptionFunctor <span style="color: #0000ff; font-weight: bold;">extends</span> Functor<span style="color: #F78811;">&#91;</span>Option<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fmap<span style="color: #F78811;">&#91;</span>A, B<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>f<span style="color: #000080;">:</span> A ⇒ B<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Option<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span> ⇒ Option<span style="color: #F78811;">&#91;</span>B<span style="color: #F78811;">&#93;</span> 
      <span style="color: #000080;">=</span> option ⇒ option map f
  <span style="color: #F78811;">&#125;</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">object</span> ListFunctor <span style="color: #0000ff; font-weight: bold;">extends</span> Functor<span style="color: #F78811;">&#91;</span>List<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> fmap<span style="color: #F78811;">&#91;</span>A, B<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>f<span style="color: #000080;">:</span> A ⇒ B<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span> ⇒ List<span style="color: #F78811;">&#91;</span>B<span style="color: #F78811;">&#93;</span> 
      <span style="color: #000080;">=</span> list ⇒ list map f
  <span style="color: #F78811;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/* enrichWithFunctor is an implicit to enrich any kind 
   * with an fmap method.
   * List, Option and any other Foo[X] can be enriched with the
   * new method.
   */</span>
  <span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">def</span> enrichWithFunctor<span style="color: #F78811;">&#91;</span>M<span style="color: #F78811;">&#91;</span><span style="color: #000080;">_</span><span style="color: #F78811;">&#93;</span>, A<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>m<span style="color: #000080;">:</span> M<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> <span style="color: #F78811;">&#123;</span>
&nbsp;
    <span style="color: #008000; font-style: italic;">/* fmap requires an implicit functor, whose type is M, to which it
     * delegates to do the real work
     */</span>
    <span style="color: #0000ff; font-weight: bold;">def</span> mapWith<span style="color: #F78811;">&#91;</span>B<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>f<span style="color: #000080;">:</span> A ⇒ B<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">implicit</span> functor<span style="color: #000080;">:</span> Functor<span style="color: #F78811;">&#91;</span>M<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> M<span style="color: #F78811;">&#91;</span>B<span style="color: #F78811;">&#93;</span> 
      <span style="color: #000080;">=</span> functor.<span style="color: #000000;">fmap</span><span style="color: #F78811;">&#40;</span>f<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>m<span style="color: #F78811;">&#41;</span>
  <span style="color: #F78811;">&#125;</span>
&nbsp;
  <span style="color: #004000; font-style: italic;">// some examples</span>
&nbsp;
  println<span style="color: #F78811;">&#40;</span>List<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span>, <span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span> mapWith <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span> + <span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #004000; font-style: italic;">// List(2, 3)</span>
&nbsp;
  println<span style="color: #F78811;">&#40;</span>some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span> mapWith <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span> + <span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span> mapWith <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span> <span style="color: #000080;">*</span> <span style="color: #F78811;">3</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #004000; font-style: italic;">// Some(6)</span>
&nbsp;
  println<span style="color: #F78811;">&#40;</span>none<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> mapWith <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span> + <span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #004000; font-style: italic;">// None</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">def</span> some<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">:</span> A<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Option<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Some<span style="color: #F78811;">&#40;</span>a<span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> none<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span><span style="color: #000080;">:</span> Option<span style="color: #F78811;">&#91;</span>A<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> None
<span style="color: #F78811;">&#125;</span></pre></div></div>

<h3>What is Going On?</h3>
<p>Lets take the <em>List(1, 2) mapWith (_ + 1)</em> example and go through it. </p>
<p>There is no <em>mapWith</em> method on List, so an implicit method is searched for that can turn the List into something that does have a <em>mapWith</em> method. Thus, <em>enrichWithFunctor</em> is found and called with the <em>List(1, 2)</em> which returns an anonymous class with the <em>mapWith</em> method required. </p>
<p>By the way, to understand more about that M[_], watch <a href="http://vimeo.com/28793245">Daniel Spiewak&#8217;s High Wizardry in the Land of Scala</a> talk.</p>
<p>That anonymous class also has a type parameter, M, which has now been fixed to List, and so <em>mapWith</em> in this class looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> mapWith<span style="color: #F78811;">&#91;</span>B<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>f<span style="color: #000080;">:</span> A ⇒ B<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">implicit</span> functor<span style="color: #000080;">:</span> Functor<span style="color: #F78811;">&#91;</span>List<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span>B<span style="color: #F78811;">&#93;</span> 
  <span style="color: #000080;">=</span> functor.<span style="color: #000000;">fmap</span><span style="color: #F78811;">&#40;</span>f<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>m<span style="color: #F78811;">&#41;</span></pre></div></div>

<p>The <em>mapWith</em> method requires an implicit Functor[List] to be available, and the ListFunctor object is just that. So when <em>functor.fmap(f)</em> is called, it is the ListFunctor&#8217;s <em>fmap</em> method being called.</p>
<p><em>ListFunctor.fmap(f)</em> takes a function, in our example its <em>(i:Int) ⇒ i + 1</em>, and returns a new function <em>(list:List[Int]) ⇒ list.map(_ + 1)</em>. </p>
<p>Finally, <em>m</em>, the <em>List(1, 2)</em> we started with that was enriched with the <em>mapWith</em> method, is applied to the new function which results in a new List. </p>
<h3>But Why?</h3>
<p>All we&#8217;ve done here is create a complicated looking bunch of code that just ends up calling methods on Option and List that already exist, specifically the map method.</p>
<p>Yes, in these examples thats true.</p>
<p>The real idea is that we&#8217;ve created <em>a general abstraction for all kinds, including those that don&#8217;t have a map method</em>. All a user of this code needs to do is have an implicit Functor in scope for the kind they would like to map over.</p>
<p>Furthermore, this is a building block for some interesting things that come next like Applicative Functors.</p>
<p>Finally, you don&#8217;t need to implement this yourself, <a href="http://code.google.com/p/scalaz/">Scalaz</a> has it already for you to exploit.</p>
<h4>Further Reading</h4>
<ul>
<li>Learn You a Haskell&#8217;s Chapter on <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids">Functors, Applicative Functors and Monoids</a>
<li>Heiko Seeberger&#8217;s fantastic <a href="https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/">Introduction to Category theory in Scala</a>
<li><a href="http://scalaz.github.com/scalaz/scalaz-2.9.1-6.0.2/doc.sxr/scalaz/example/ExampleFunctor.scala.html">Scalaz Functor Examples</a>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2012/01/08/a-small-functor-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Successful Delivery</title>
		<link>http://www.casualmiracles.com/2012/01/06/a-successful-delivery/</link>
		<comments>http://www.casualmiracles.com/2012/01/06/a-successful-delivery/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 22:06:05 +0000</pubDate>
		<dc:creator>channing</dc:creator>
				<category><![CDATA[Casual Miracles]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Software Process]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/?p=572</guid>
		<description><![CDATA[Over the last few months, we&#8217;ve been working on delivering HSBC&#8217;s Clearing Connectivity Layer and OTC Cleared Trade Acceptance System. We went live early December, and in fact, we delivered our first release early. The system enables HSBC to handle <a href="http://www.casualmiracles.com/2012/01/06/a-successful-delivery/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Over the last few months, we&#8217;ve been working on delivering HSBC&#8217;s Clearing Connectivity Layer and OTC Cleared Trade Acceptance System. We went live early December, and in fact, we delivered our first release early.</p>
<p><span id="more-572"></span></p>
<p>The system enables HSBC to handle the processing of all cleared interest rate and credit derivatives from multiple market participants. The first release provided full connectivity to the <a title="LCH Clearnet" href="http://www.lchclearnet.com/">London Clearing House</a>, with the <a title="CME" href="http://www.cmegroup.com/">Chicago Mercantile Exchange</a> and the <a title="ICE" href="http://www.theice.com/">Intercontinental Exchange</a> following shortly.</p>
<p>We had a tight deadline and quite a lot of things to figure out. The project had been difficult to analyse in the past as a result of changes in legislation and many other unknowns. So how did we do it?</p>
<h4>Talking</h4>
<p>The first thing we always do is talk to the business and figure out what is needed. Not in abstract business terms or strategic direction, but what the <em>actual</em> user sitting in front of our app is <em>actually</em> going to see, do and expect. Whilst the general business background is useful context and necessary, it is woefully inadequate for building a system.</p>
<p>Having the people who are going to <em>actually</em> build your system talk, <em>in person</em>, to the people that are <em>actually</em>, physically, going to use that system is critical. Not managers talking to managers but the people doing the work. And we do that every day, for every feature!</p>
<h4>Minimal Viable Product</h4>
<p>The next critical step is establishing the absolute minimum that will enable the system to be useful, and deliver that. <strong>Nothing else!</strong> (until next week)</p>
<p>It is surprisingly difficult to help stakeholders become accustomed to focussing on what is needed for the next release. IT has done a really good job of telling people they need to write down all their requirements for the next year or they will not get them. We have quite a bit of work to do to undo that ridiculous notion. But when the business understand that we aren&#8217;t saying we won&#8217;t let them have a feature, just that we want them to prioritise what they want for the next release (next week), and they can change their mind whenever they like, they are very happy.</p>
<h4>Who Else Cares?</h4>
<p>I have talked about the business as if they are the only interested party. Not so. We talk to every stakeholder we can find: senior management, BAs, support people, release people, release boards, architects; everyone who might ever have some kind of interest in the system. They all have needs that have to be addressed and prioritised. On one project we were able to name 23 different stakeholder roles for a project, which was surprising to everyone who thought there was only one stakeholder.</p>
<h4>Planning</h4>
<p>Having established a backlog of stuff, we maintain it by planning weekly with all stakeholders, and marvel at how much priorities change, new work appears and old work disappears from week to week. But thats all good! Every change is welcome, and shows how badly wrong things would have gone had we tried to <em>plan-it-up-front</em>.</p>
<h4>Where&#8217;s the Code?</h4>
<p>Every day, the team has a stand up to discuss what they are going to do. Then, we implement some features.</p>
<ol>
<li>pair up with another team member in the stand up</li>
<li>talk to the user and find out what they want, sketch ideas out on paper or mock them up until enough is understood</li>
<li>write a failing acceptance test with the user. We use <a title="Specs2" href="http://etorreborre.github.com/specs2/">Specs2</a> but you can use whatever you like so long as it produces some kind of user visible result</li>
<li>make the acceptance test pass by typing some code in your IDE, writing unit tests as necessary</li>
</ol>
<p>However, a lot of what we did involved communication with other systems too for which we required <em>real</em> samples of messages since nothing had schemas etc. This was where a lot of time was spent, again in dialog with stakeholders to ensure that the messages we process and respond with were correct.</p>
<h4>Good, all done then!</h4>
<p>No. When we think we&#8217;ve finished a feature we demo it to the user as soon as possible &#8211; we don&#8217;t wait to the end of the iteration. They can play with it and change things which they often do when they see something working for real.  And thats all good, we want them to have something useful.</p>
<h4>Builds?</h4>
<p>Part of the development practice is to commit code frequently ensuring tests always pass. People are surprised by how often we mean by <em>frequently</em>. We mean <em>every single time you complete a piece of work and all the tests pass locally</em>. That happens about once an hour but can be more frequent.</p>
<p>We also use <a title="TeamCity" href="http://www.jetbrains.com/teamcity/">TeamCity</a> to keep us sane but again there are many alternatives.</p>
<p>Finally, deployment. At the start of all project&#8217;s we always have a single mantra about deployment: <em>Thou must automate the deployment</em>. More than that, the same deployment script should work on every dev, test, uat and production environment. Sometimes, the production environment needs to be subtly different, but we try to make the other environments as close to production as possible.</p>
<h4>Technology</h4>
<p>We built the system in Scala with Liftweb. It was tested with Specs2 and we used sbt for builds. Scala is significantly more productive than Java, and Liftweb enabled us to build a robust, secure, dynamic web application very quickly.</p>
<h4>Summary</h4>
<p>Is this starting to sound familiar? Yup, its basically an agile method using practices from XP, Scrum, Kanban, anything that works <em>for this client in this project with this team</em>. And no, you can&#8217;t transplant it to another team! They will have to figure out what works for them, and when we move to another project, we have to figure out what will work for the new environment.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2012/01/06/a-successful-delivery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Small Example of the Scalaz IO Monad</title>
		<link>http://www.casualmiracles.com/2012/01/03/a-small-example-of-the-scalaz-io-monad/</link>
		<comments>http://www.casualmiracles.com/2012/01/03/a-small-example-of-the-scalaz-io-monad/#comments</comments>
		<pubDate>Tue, 03 Jan 2012 18:03:31 +0000</pubDate>
		<dc:creator>channing</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/?p=594</guid>
		<description><![CDATA[I wanted a very tiny example of using the IO Monad in the brilliant Scalaz library, and here it is. I present the example without explanation, the web does not need another set of explanations about this subject but I <a href="http://www.casualmiracles.com/2012/01/03/a-small-example-of-the-scalaz-io-monad/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I wanted a very tiny example of using the IO Monad in the brilliant <a href="https://github.com/scalaz/scalaz" title="Scalaz">Scalaz</a> library, and here it is.</p>
<p><span id="more-594"></span>I present the example without explanation, the web does not need another set of explanations about this subject but I have found the following blogs useful, with a mix of theoretical explanation and practical examples:</p>
<ul>
<li><a href="http://www.stackmob.com/2011/12/scalaz-post-part-2/">Functional IO in Scala with Scalaz</a>
<li><a href="http://blog.sigfpe.com/2007/11/io-monad-for-people-who-simply-dont.html">The IO Monad for People who Simply Don&#8217;t Care</a>
<li><a href="http://apocalisp.wordpress.com/2011/12/19/towards-an-effect-system-in-scala-part-2-io-monad/">Towards an Effect System in Scala, Part 2: IO Monad</a>
</ul>
<p>All this example does is print out the names of files in a directory.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">import</span> scalaz.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">import</span> Scalaz.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">import</span> scalaz.<span style="color: #000000;">effects</span>.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">import</span> java.<span style="color: #000000;">io</span>.<span style="color: #000080;">_</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">object</span> TheIO <span style="color: #0000ff; font-weight: bold;">extends</span> App <span style="color: #F78811;">&#123;</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">val</span> dirInIO <span style="color: #000080;">=</span> io <span style="color: #F78811;">&#123;</span> <span style="color: #0000ff; font-weight: bold;">new</span> File<span style="color: #F78811;">&#40;</span>System.<span style="color: #000000;">getProperty</span><span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;user.dir&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#125;</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">def</span> filesInIO <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>dir <span style="color: #000080;">&lt;</span>- dirInIO<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> dir.<span style="color: #000000;">listFiles</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">def</span> namesInIO <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>theFiles ← filesInIO<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> theFiles.<span style="color: #000000;">map</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">getName</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">def</span> printNamesInIO <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>all ← namesInIO<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">yield</span> all.<span style="color: #000000;">map</span><span style="color: #F78811;">&#40;</span>println<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">val</span> result <span style="color: #000080;">=</span> printNamesInIO
&nbsp;
  println<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Nothings happened yet, lets go!&quot;</span><span style="color: #F78811;">&#41;</span>
  result.<span style="color: #000000;">unsafePerformIO</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2012/01/03/a-small-example-of-the-scalaz-io-monad/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>A little Scalaz magic</title>
		<link>http://www.casualmiracles.com/2011/11/22/a-little-scalaz-magic/</link>
		<comments>http://www.casualmiracles.com/2011/11/22/a-little-scalaz-magic/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 22:12:06 +0000</pubDate>
		<dc:creator>channing</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/?p=539</guid>
		<description><![CDATA[Here are a few useful things you can do easily with Scalaz to make you code a little simpler. The sample below makes use of Applicative Functors which you don&#8217;t need to understand to benefit from their use, but its <a href="http://www.casualmiracles.com/2011/11/22/a-little-scalaz-magic/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Here are a few useful things you can do easily with <a title="Scalaz" href="http://code.google.com/p/scalaz/">Scalaz</a> to make you code a little simpler.<br />
<span id="more-539"></span><br />
The sample below makes use of Applicative Functors which you don&#8217;t need to understand to benefit from their use, but its interesting to learn more about them. See the references below for more information about applicative functors.</p>
<p>Here&#8217;s some code which is based on an <a href="http://scalaz.github.com/scalaz/scalaz-2.9.1-6.0.2/doc.sxr/scalaz/example/ExampleApplicative.scala.html">example</a> on Scalaz&#8217;s website.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">import</span> scalaz.<span style="color: #000080;">_</span>
<span style="color: #0000ff; font-weight: bold;">import</span> Scalaz.<span style="color: #000080;">_</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">object</span> Applicatives <span style="color: #0000ff; font-weight: bold;">extends</span> App <span style="color: #F78811;">&#123;</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * Lets pretend you have two optional values, but you want to apply some
   * function to their contents safely.
   * You also don't want to fiddle about with flatmap / map / for / yield
   * Then do this:
   */</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> x<span style="color: #000080;">:</span>Option<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> y<span style="color: #000080;">:</span>Option<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">3</span><span style="color: #F78811;">&#41;</span>
&nbsp;
  <span style="color: #F78811;">&#40;</span>x |<span style="color: #000080;">@</span>| y<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> 	<span style="color: #004000; font-style: italic;">// Some(5)</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * The |@| method is a pimp (enrichment! sorry), on Option in this case,
   * that builds 'something' that applies the function _ + _
   */</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * If one of the options is a none
   * then the result of the whole expression will be none.
   * (I am using scalaz's some and none because it means less boilerplate)
   */</span>
  <span style="color: #F78811;">&#40;</span>some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span> |<span style="color: #000080;">@</span>| none<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> <span style="color: #004000; font-style: italic;">// None</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * The function can be any method, including 'apply'
   */</span>
  <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #0000ff; font-weight: bold;">class</span> Person<span style="color: #F78811;">&#40;</span>age<span style="color: #000080;">:</span> Int, height<span style="color: #000080;">:</span>Double, name<span style="color: #000080;">:</span> String<span style="color: #F78811;">&#41;</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   *  ⊛ = |@| just for fun
   */</span>
  <span style="color: #F78811;">&#40;</span>some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span> ⊛ some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1.1</span><span style="color: #F78811;">&#41;</span> ⊛ none<span style="color: #F78811;">&#91;</span>String<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>Person.<span style="color: #000000;">apply</span> <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span>  <span style="color: #004000; font-style: italic;">// none because an arg was none</span>
  <span style="color: #F78811;">&#40;</span>some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">4</span><span style="color: #F78811;">&#41;</span> ⊛ some<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1.1</span><span style="color: #F78811;">&#41;</span> ⊛ <span style="color: #6666FF;">&quot;Angelica&quot;</span>.<span style="color: #000000;">some</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>Person.<span style="color: #000000;">apply</span> <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> <span style="color: #004000; font-style: italic;">// Some( Person(4, 1.1, Angelica) )</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * did you catch the &quot;Angelica&quot;.some - another bit of enriching by scalaz
   */</span>
&nbsp;
  <span style="color: #008000; font-style: italic;">/*
   * It works with ANY higher kind, eg. List
   */</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> l1 <span style="color: #000080;">=</span> <span style="color: #F78811;">1</span> <span style="color: #000080;">::</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">::</span> Nil
  <span style="color: #0000ff; font-weight: bold;">val</span> l2 <span style="color: #000080;">=</span> <span style="color: #F78811;">3</span> <span style="color: #000080;">::</span> <span style="color: #F78811;">4</span> <span style="color: #000080;">::</span> Nil
&nbsp;
  <span style="color: #F78811;">&#40;</span>l1 ⊛ l2<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span><span style="color: #000080;">_</span> + <span style="color: #000080;">_</span><span style="color: #F78811;">&#125;</span> <span style="color: #004000; font-style: italic;">// List(4, 5, 5, 6)</span>
&nbsp;
<span style="color: #F78811;">&#125;</span></pre></div></div>

<h3>References</h3>
<ol>
<li>Eric Torrebore has a very nice <a href="http://etorreborre.blogspot.com/2011/06/essence-of-iterator-pattern.html">article</a> explaining much of this.</li>
<li>Learn You a Haskell has a great <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids">chapter</a> on applicative functors amongst other things.</li>
<li>Heiko Seeberger <a href="http://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/">blog post</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2011/11/22/a-little-scalaz-magic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Burndown, Prediction, Confidence and Risk</title>
		<link>http://www.casualmiracles.com/2011/05/16/burndown-prediction-confidence-and-risk/</link>
		<comments>http://www.casualmiracles.com/2011/05/16/burndown-prediction-confidence-and-risk/#comments</comments>
		<pubDate>Mon, 16 May 2011 20:49:18 +0000</pubDate>
		<dc:creator>lance</dc:creator>
				<category><![CDATA[Software Process]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/blog/?p=395</guid>
		<description><![CDATA[One of Casual Miracles&#8217; clients had a long running project with a big specification up front. This is not the mode in which we usually like to work. It is, however, an opportunity for an experiment with burndown charts. Having <a href="http://www.casualmiracles.com/2011/05/16/burndown-prediction-confidence-and-risk/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>One of Casual Miracles&#8217; clients had a long running project with a big specification up front. This is not the mode in which we usually like to work. It is, however, an opportunity for an experiment with burndown charts.</p>
<p><span id="more-395"></span></p>
<p>Having obtained estimates for all of the work, and with contracts duly signed, etc., the work was begun. And so, we tracked the burndown:</p>
<p><a href="/wp-content/uploads/2011/05/burndown.jpg"><img class="aligncenter size-full wp-image-473" title="Burndown" src="/wp-content/uploads/2011/05/burndown.jpg" alt="Burndown" width="495" height="375" /></a><br />
The chart above shows the first 43 days of burndown.</p>
<p>One common question that we try to answer with the burndown charts is: &#8216;What day do we expect the burndown to reach 0?&#8217;. That is: &#8216;When do we expect to finish?&#8217; The assumption is that historical performance predicts future performance. In our case, the question is more like: &#8216;Is there any reason to suspect we might not finish by the contracted date?&#8217;</p>
<p>One simple way of answering this question is to look at ratios: we have completed (551 - 302) estimated days of work in 43 days, so we can expect to take 43 * 551 / (551 - 302) = 96 days to finish everything.</p>
<p>A more &#8216;sophisticated&#8217; approach is to put a linear regression line through the burndown and extrapolate. This tells us that we will reach 0 remaining estimate on day 85, but it fails to give an indication of the confidence we can have about this prediction. We can use the the correlation coefficient to give some idea of this, but it is difficult to know what to do with it.</p>
<p>In fact, the questions above are not really the right ones. The question we should be asking is: &#8216;How confident can we be that the burndown will reach zero <em>on or before</em> a given date?&#8217;.</p>
<p>In order to answer this, we need a different approach. One such approach is based on the <a href="http://en.wikipedia.org/wiki/Monte_Carlo_method">Monte Carlo Method</a>, which in this case translates to asking: &#8216;Assuming the future burndown is similar to the historical data, what fraction of the possible futures result in the burndown reaching zero on or before a given date (or between two dates)?&#8217;</p>
<p>We can apply this method by starting with the estimate on the last burndown day for which we have an estimate (day 43), choosing a day from the history randomly, determining the change in burndown between this day and the preceding one, and then applying that change to the estimate we have for day 43. This then becomes the estimate for day 44 and we repeat the process, until the estimate reaches 0. This then represents one simulated burndown, and we repeat the whole process thousands of times to obtain a distribution of estimates for each future day.</p>
<p>The chart below shows the first result from applying this method:</p>
<p><a href="/wp-content/uploads/2011/05/burndownWithMedian.jpg"><img class="aligncenter size-full wp-image-474" title="Burndown With Median Line" src="/wp-content/uploads/2011/05/burndownWithMedian.jpg" alt="Burndown With Median Line" width="495" height="374" /></a></p>
<p>The line extending the historical burndown is the &#8216;Median Line&#8217;. This is obtained by determining the estimate for each day for which half of the simulations yield a higher estimate and half yield a lower estimate. When this line intersects the Day Number axis (day 97), it tells us that half of the simulated burndowns have reached a zero estimate on or before day 97 and half have not. Based on this information (and speaking somewhat informally), we have a half chance of delivering on or before day 97 and a half chance of delivering afterwards.</p>
<p>Knowing this is interesting information, but it is reasonable to ask what is the spread of simulation results. After all, if all simulations terminate within a very tight spread centred around day 97, we can still reasonably accurately predict the end day. If however, the spread is very wide, some other action might be suggested.</p>
<p>We can obtain an idea of the spread in the same way as we obtained the median line. If, for each day, we ask &#8216;What value of estimates (centred around the median value) contain x% of the simulated results on each simulated day?&#8217;. This will give us &#8216;confidence intervals&#8217; around the median:</p>
<p><a href="/wp-content/uploads/2011/05/burndownWithIntervals.jpg"><img class="aligncenter size-full wp-image-475" title="Burndown With Confidence Intervals" src="/wp-content/uploads/2011/05/burndownWithIntervals.jpg" alt="Burndown With Confidence Intervals" width="497" height="376" /></a></p>
<p>The chart above shows the 50%, 90% and 99% confidence intervals. Consider the 90% confidence interval, which is enclosed by the dark green curves starting at the final known burndown day (43, 302) and terminating at (74, 0) and (124, 0). On each simulated day, the set of estimates between these two curves contain 90% of the simulated burndowns. Because we placed the intervals symmetrically around the median line, the space underneath the lower curve represents 5% of the simulated estimates (those that represent the team performing above expectations), and the space above the upper curve represents the final 5% of the simulated estimated (those that represent the team performing below expectations).</p>
<p>Clearly the spread is quite wide! If we wanted to give a date that represented 95% confidence, we should choose choose day 124, which is 27 days after the median line predicts, or a difference of 25%. It is also 28 days (also about 25%) after our simple ratio based estimate given at the beginning of this article and 39 days (40%) after the the linear regression estimate.</p>
<p>The astute reader might notice two important things:</p>
<ol>
<li>The day at which the confidence interval curves reach a Remaining Estimate of 0 spreads out alarmingly as the required confidence increases. i.e. the 50%, 90% and 99% upper confidence envelopes require 10%, 28% and 45% respectively more days to reach 0 than the median line does.</li>
<li>The confidence intervals are distributed symmetrically around the median line when a vertical slice is taken through the chart. Indeed, the histograms giving rise to these confidence intervals are near-Gaussian (courtesy of the Central Limit Theorem), at least until some of the simulations are terminated when they reach 0 remaining estimate. This is not true when a horizontal slice is taken. In particular, when those curves reach the Remaining Estimate of 0, it is plain to see that, for example, the lower envelope for the 90% confidence interval is 97 - 74 = 23 days below the median, whereas the corresponding upper curve is 124 - 97 = 27 days above the median.</li>
</ol>
<p>The first of these points suggests that, even at this advanced state of the project, requiring high confidence about the delivery date demands significant &#8216;contingency&#8217;, with the 99% upper confidence envelope prediction being more than a factor of 2 larger than the corresponding lower confidence envelope prediction. Similarly, the ratio between the upper 99% confidence envelope prediction and the median prediction is just under 1.5.</p>
<p>The second point suggests that it is easier to run late than it is to run early, which will come as no surprise to development teams and their customers everywhere. Indeed, the skew also implies that when things are running late, it is possible for even more tardiness to result. This is intuitively true since, with less work remaining to be done, it is less likely that significant estimation &#8216;errors&#8217; will occur.</p>
<p>Of course, we should not take all of this too seriously; a great deal has been made of very little historical data. Attention to a burndown chart often causes teams to adjust scope and other factors to bring the project in on time. The date is far more likely to be missed because of some unmitigated risk, such as the absence of a team member for an extended period of time.</p>
<p>In a subsequent article, once the delivery is complete, I will return to this topic with the remainder of the burndown data and see how well the confidence intervals modelled the future.</p>
<p>&nbsp;</p>
<p><em>Update: About a week after I wrote this article, a series of events occurred that made it impossible to complete the graph in the way that I&#8217;d hoped.</em></p>
<p><em>First, one of the &#8216;key&#8217; developers left the team. The notion of &#8216;key&#8217; developer (due to functional silos) is something that I&#8217;d been trying to eliminate since starting with the organisation, but the team had not had sufficient time to get to grips with each other&#8217;s work.</em></p>
<p><em>Since the team was not large, the developer leaving implied that timescales would change. This caused the client to panic somewhat, leading to a review of the planning. During this review, it was discovered that the original requirements were hopelessly inadequate in term of both &#8216;completeness&#8217; and &#8216;correctness&#8217;. After more analysis, the total scope required was estimated at six times (!) the original estimate and much of the remaining original work envisaged was de-prioritised or deemed to be no longer required.</em></p>
<p><em>Given the significantly extended timescales, a couple of the developers who had been intending to hang on until the delivery decided to resign, since the delivery was now clearly much more remote.</em></p>
<p><em>Shortly after this, a member of the executive team who I had a good relationship with was replaced by someone else (not because of this project). It very quickly became obvious that this new executive had a strong belief in process over people, big requirements up front and all manner of things I have railed against for years. This clearly spelled the end of my time with this client.</em></p>
<p><em>Although I had warned of much of this risk early in the project, I take no pleasure in its materialisation. </em><em>It could have all been completely different.</em></p>
<p><em>As I said in the first paragraph above: This is not the mode in which we usually like to work.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2011/05/16/burndown-prediction-confidence-and-risk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Type Names From An Earlier Age</title>
		<link>http://www.casualmiracles.com/2010/09/13/type-names-from-an-earlier-age/</link>
		<comments>http://www.casualmiracles.com/2010/09/13/type-names-from-an-earlier-age/#comments</comments>
		<pubDate>Mon, 13 Sep 2010 20:14:18 +0000</pubDate>
		<dc:creator>lance</dc:creator>
				<category><![CDATA[Quality]]></category>
		<category><![CDATA[Software Process]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/blog/?p=349</guid>
		<description><![CDATA[The typical architectures and layering of code in 'the enterprise' frequently exhibit poor systems of naming which causes developers to jump through hoops to try to maintain the layers because of lack of abstraction. This in turn results in an unwieldy codebase that is more concerned with accidental implementation complexity than codifying domain knowledge. <a href="http://www.casualmiracles.com/2010/09/13/type-names-from-an-earlier-age/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p><em>How would this be done in an earlier age?</em></p>
<p>This is the question I frequently ask myself when searching for the names of domain concepts.</p>
<p>The typical architectures and layering of code in &#8216;the enterprise&#8217; frequently exhibit poor systems of naming which causes developers to jump through hoops to try to maintain the layers because of lack of abstraction. This in turn results in an unwieldy codebase that is more concerned with accidental implementation complexity than codifying domain knowledge.</p>
<p><span id="more-349"></span></p>
<p>As an example consider the &#8216;data access object&#8217;, usually referred to as a &#8216;DAO&#8217;. It is common in enterprise Java systems to have a number of classes whose names include a DAO suffix to handle the persistence needs for the system. The problem with this naming scheme, if this is the extent of the abstraction, is that it is an implementation concern; there is nothing in the business domain called a &#8216;DAO&#8217;.</p>
<p>Once the DAO naming scheme has been adopted, it has a profoundly limiting effect on the use of the classes that are so named. Developers treat the DAO classes as something that must only be used at the edges of the system, frequently requiring a &#8216;service layer&#8217; to be bought into existence, partially in order to keep the domain model free of coupling to the persistence layer.</p>
<p>There is nothing wrong with a service layer in principle if its purpose is to orchestrate behaviour at a high level. But far too much behaviour is usually found in these service layers because domain model objects are rightly not allowed to become aware of the DAOs. The effect of this is that the service layer needs to find precisely those things required by the domain logic before finally handing control over to the domain model. The service layer therefore becomes far too familiar with the details of the domain logic which means that at least two places have to change if the domain logic changes.</p>
<p>One lamentably common solution to this problem is to move all domain logic into the  service layer, resulting in an anaemic domain model.</p>
<p>However, there is frequently something in the real world that does represent the place where certain types of objects are stored and this should be represented directly in code with a type named after the domain concept.</p>
<p>If there is no such thing, which often occurs because the modern world has replaced that mechanism with a set of database tables or some equivalent, then I appeal to my opening question: <em>How would this be done in an earlier age?</em></p>
<p>For example, consider the order management system I have used for examples in other articles. Somewhere in such a system, there is the concept of an &#8216;order&#8217;. Then, we must have a mechanism for persisting orders. If we refer to this as an &#8216;OrderDAO&#8217; and take the abstraction no further, we give ourselves all of the problems mentioned earlier. However, in an earlier age, orders would have been written down, modified and deleted in an &#8216;order book&#8217;, and this is how the concept can be named in the order management system.</p>
<p>Now, the OrderBook may be, in Java, an interface whose implementation in the running system uses all of the machinery that enterprise Java developers love: Hibernate, Spring, etc. That implementation might even be called something like HibernateOrderBook or, god help us, OrderDAO. The point is that the rest of the order management system knows only about an OrderBook, which is a strong domain concept and hence may be packaged with the domain model and passed around the domain model without reservation. More of the domain logic can therefore be kept in the domain model rather than in services.</p>
<p>Interestingly, this approach frequently clarifies another hot issue at the moment: when and what to mock when unit testing (in the specific sense of interaction testing).</p>
<p>From the point of view of a class that must make use of the OrderBook, all that matters is that the OrderBook is sent something like write(&#8230;), delete(&#8230;) or find(&#8230;) messages with the appropriate arguments. How it writes, deletes or finds is irrelevant, because that is a delegated concern whose implementation should be completely unknown to the subject under test. Bear in mind it could be Hibernate or JDBC, an in memory collection, an invocation of a Rest service using XML over HTTP or teleportation using tangled quantum effects. Any test that verifies more than the message send is overspecified, and hence suffers from the well documented, numerous effects of over-specified definitions. Therefore mocking is entirely appropriate.</p>
<h1>Conclusion</h1>
<p>Naming is important; it is a fundamental aspect of abstraction. The wrong name can profoundly warp the way people think about a problem which frequently results in a profoundly warped solution. Sometimes, it is hard to find a name because nothing like the thing you are trying to name exists in the appropriate domain.</p>
<p>In such circumstances, I often find the name by thinking about how the problem was solved before the invention of computers: <em>How would this be done in an earlier age?</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2010/09/13/type-names-from-an-earlier-age/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rank, Authority and Power</title>
		<link>http://www.casualmiracles.com/2010/09/06/rank-authority-and-power/</link>
		<comments>http://www.casualmiracles.com/2010/09/06/rank-authority-and-power/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 21:12:46 +0000</pubDate>
		<dc:creator>lance</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/blog/?p=354</guid>
		<description><![CDATA[One of the characteristics of many teams that Casual Miracles has helped over the past few years is that team members have felt a lack of authority to make changes that are necessary to achieve success. Frequently this occurs despite <a href="http://www.casualmiracles.com/2010/09/06/rank-authority-and-power/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>One of the characteristics of many teams that Casual Miracles has helped over the past few years is that team members have felt a lack of authority to make changes that are necessary to achieve success. Frequently this occurs despite senior management telling them that they can make the changes they want to.</p>
<p><span id="more-354"></span></p>
<p>Sometimes this is due to organisational constraints. In some very hierarchical, command-and-control organisations, by the time the message reaches those who have the ideas, it has been corrupted beyond recognition, and appears to be an admonishment to maintain the status quo or instruction to move in a different direction completely. Even without these confusions, and within a relatively shallow local hierarchy (one or two layers of management), team members can inhibit themselves because of a sense of impotence, with each team member thinking that others have greater authority because of a whole host of factors.</p>
<p>In most organisations hierarchical rank is a major component of a person&#8217;s authority and power. But the concept of rank is a complex, multi-dimensional notion that frequently speaks to our primate brains. Furthermore, rank is dependent on context and is relational; a person only has rank with respect to others and in a particular  situation &#8211; there is no absolute rank.</p>
<h1>The Problem</h1>
<p>One such organisation we worked with recently suffered from just this issue. Various well-intentioned management attempts to help the team had actually reinforced this sense of lack of authority. </p>
<p>We ran retrospectives to try to get the team to cohere around certain issues and solutions. Almost every retrospectives followed a pattern of identifying issues, coming up with solutions and then declaring the solutions impossible because the team lacked the authority to apply the solutions.</p>
<h1>An Exercise</h1>
<p>Several years ago, I attended a course run by Ben Fuchs and Joseph Pelrine of <a href="http://www.cateams.com">CATeams</a> entitled &#8216;The Deep Dynamics of Agile Teams&#8217;. A large part of this course was about rank, and this is where the ideas and material came from for this exercise.</p>
<p>After a (too) brief introduction to the concept of rank, we gave everybody a questionnaire which asked them to assess their own rank on 25 distinct dimensions (e.g. position in the formal hierarchy, education, gender, intelligence, self-confidence, etc.) placed into 3 categories (Situational, Social and Personal).</p>
<p>Having done that, we then asked everybody to pair up. We gave each team member another copy of the questionnaire, asking them to assess their partner&#8217;s rank in the same way. Having done that, we asked the pair to discuss the differences in the two assessments of each member of the pair.</p>
<p>What is striking about this process is that usually, individuals will assess their own rank lower than their partner&#8217;s assessment on many dimensions. In this instance, almost everybody afforded their partners greater rank than their partner had afforded themselves.</p>
<p>This is quite common and was actually the point of the exercise when Fuchs and Pelrine asked us to do it on the course.</p>
<h1>Taking it a Bit Further</h1>
<p>Somewhat on a whim, we asked each person to provide us with two post-it notes.</p>
<p>On the first, we asked them to write &#8216;&lt;&#8217;, &#8216;=&#8217; or &#8216;&gt;&#8217; if they felt that, in general, their partner had assessed their rank lower, equal to or higher respectively, than their own assessment of their rank.</p>
<p>On the second, we asked them to write &#8216;&lt;&#8217;, &#8216;=&#8217; or &#8216;&gt;&#8217; if they felt that, in general, they assessed their partner&#8217;s rank lower, equal to or higher than their partner had assessed his or her own rank.</p>
<p>Of course, given that software development teams (including testers, BAs and project managers) frequently believe that they have impeccable logic, this request was regarded with incredulity; &#8216;surely the results will be symmetrical?&#8217; they asked.</p>
<p>However, once the team had done as we asked, we put the post it notes on display and found that in response to the first question, just over half of the people present felt that their partners had ranked them higher than they had ranked themselves. However, in response to the second, almost all believed that they had ranked their partners higher than than their partners had ranked themselves.</p>
<p>So to some extent the participants&#8217; assessment of their own rank even coloured their assessment of the questionnaire results.</p>
<h1>Conclusion</h1>
<p>The message is that we frequently assess our own rank lower than other people assess it. The gap between our assessment and the assessment others make of us represents rank, authority and power that we can use if only we are prepared to wield it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2010/09/06/rank-authority-and-power/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Scaladays 2010</title>
		<link>http://www.casualmiracles.com/2010/05/20/scaladays-2010/</link>
		<comments>http://www.casualmiracles.com/2010/05/20/scaladays-2010/#comments</comments>
		<pubDate>Thu, 20 May 2010 14:45:42 +0000</pubDate>
		<dc:creator>channing</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/blog/?p=343</guid>
		<description><![CDATA[I attended Scaladays 2010 at EPFL in Lausanne, Switzerland in April. at which Nigel Warren and I presented the work we had done on porting Fly’s Java client library to Scala. You can watch all the Scaladays videos on the <a href="http://www.casualmiracles.com/2010/05/20/scaladays-2010/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I attended <a href="http://days2010.scala-lang.org/">Scaladays 2010</a> at EPFL in Lausanne, Switzerland in April. at which Nigel Warren and I presented the work we had done on porting <a href="http://www.flyobjectspace.com/">Fly’s</a> Java client library to Scala. You can watch all the <a href="http://days2010.scala-lang.org/node/136">Scaladays videos</a> on the Scaladays website and so I will not dwell on the talks, which were excellent. Instead, I want to talk about Scala and its community, led by Martin Ordersky.</p>
<p><span id="more-343"></span></p>
<p>It has become clear to me, as it did with Java 15 years ago, that Scala is an incredibly important language and almost certainly Java’s successor. There is no reason for anyone intending to build applications for the JVM to choose Java over Scala.</p>
<p>Any Java developer is capable of writing Scala in a basic sense, that is, write exactly what they would write in Java but in Scala’s syntax. They can even start by mixing Java and Scala if they feel uncomfortable about jumping all the way in. Developers can choose to use Scala on parts of a system or even just in tests. Scala’s tight integration with Java libraries and frameworks enables developers to make use of the Java ecosystem as they normally would which is incredibly valuable.</p>
<p>However, Scala has a great deal of headroom. It enables much more concise, simpler, reusable and elegant software to be written for those that have the will to learn functional programming and a little practical type theory. Importantly, Scala offers Java developers a way to move from idiomatic Java to idiomatic Scala in small steps, there is no need for a wholesale leap into the unknown. In short, Scala offers a migration path to a better way to build robust software.</p>
<p>A reason why Scala is important is that it offers mechanisms for controlling complexity. In The Structure and Interpretation of Computer Programs, Abelson and Sussman said:</p>
<p><em>In our study of program design, we have seen that expert programmers control the complexity of their designs with the same general techniques used by designers of all complex systems. They combine primitive elements to form compound objects, they abstract compound objects to form higher-level building blocks, and they preserve modularity by adopting appropriate large-scale views of system structure.</em></p>
<p>Scala facilitates this abstraction and combination that results in simpler, more robust software in a number of ways: functional programming techniques, object oriented techniques, a rich type system and mechanisms to build components. In Scalable Component Abstractions, Martin Odersky and Matthias Zenger describe abstractions for the construction of reusable components:</p>
<p><em>abstract type members, explicit selftypes, and modular mixin composition. Together, these abstractions enable us to transform an arbitrary assembly of static program parts with hard references between them into a system of reusable components.</em></p>
<p>Making <em>full</em> use of Scala does not come for free, there is a lot to learn. Fortunately, the Scala community is very friendly which is in large part due to Martin and his team’s efforts. The community is full of very smart people who are very willing to help novices. It is not unusual for questions asked on mailing lists to be answered by Martin or other leaders in the Scala community. This friendly environment is actively fostered so that beginners feel comfortable asking basic questions without fear of angry replies to RTFM.</p>
<p>There are those that think that Scala is a complex language and they are right to a certain extent, but you can be productive in Scala without using advanced features, just not as productive as you would be if you learnt about those features.</p>
<p>Most objections to new languages like Scala and Clojure can be reduced to, “I don’t understand this after 2 mins of skimming the website so its too academic”. Not very good really and not worthy of further argument.</p>
<p>Learning Scala has real benefits in understanding more about computing in general, and it lets you do it gently whilst being productive. Give it a try!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2010/05/20/scaladays-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Maintainable Acceptance Tests</title>
		<link>http://www.casualmiracles.com/2010/03/04/writing-maintainable-acceptance-tests/</link>
		<comments>http://www.casualmiracles.com/2010/03/04/writing-maintainable-acceptance-tests/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 01:20:08 +0000</pubDate>
		<dc:creator>lance</dc:creator>
				<category><![CDATA[Quality]]></category>
		<category><![CDATA[Software Process]]></category>

		<guid isPermaLink="false">http://www.casualmiracles.com/blog/?p=283</guid>
		<description><![CDATA[Over the past six months or so, there has been a fair amount of negative commentary about automated acceptance / integration / system testing. The thrust of this commentary is that testing at this level tends to be brittle, slow <a href="http://www.casualmiracles.com/2010/03/04/writing-maintainable-acceptance-tests/">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Over the past six months or so, there has been a fair amount of negative commentary about automated acceptance / integration / system testing. The thrust of this commentary is that testing at this level tends to be brittle, slow and have a high maintenance overhead. None of this needs to be true, but producing a robust suite of tests requires an uncommon adherence to good practice.</p>
<p><span id="more-283"></span></p>
<p>To be sure, this kind of automated test will run slower than unit tests, because almost all of the machinery of the system under test is going to be involved. But I have seen many implementations that are much slower than they need to be because of one or two technical choices.</p>
<p>The advice that I offer here does not guarantee fast and robust tests, but if you don&#8217;t follow this advice and you don&#8217;t somehow deal with the issues raised in this article, I am pretty sure your tests will be slow and time-consuming to maintain as the test suite grows.</p>
<p>By way of example, let us consider an online book seller. The kind of test that can be built with the aid of many libraries might well look like this:</p>
<pre>public void testSearchAndOrder() {
    type("username", "JRHartley");
    type("password", "verysecret");
    click("Submit");

    type("searchField", "Fly Fishing Hartley");
    click("Search");

    assertEquals("Fly Fishing"), innerHtml("searchresults/tr[1]/td[1]");
    assertEquals("J.R.Hartley"), innerHtml("searchresults/tr[1]/td[2]");

    click("searchresults/tr[1]/td[1]");
    click("Order");

    assertPageTitle("Your order has been placed");
}</pre>
<p>This will certainly test the functionality. However, there are two things wrong with it:</p>
<ul>
<li>Who is &#8216;JRHartley&#8217;? Why is he buying &#8216;Fly Fishing&#8217;? <em>i.e.</em> Is there something significant about that author or that book in the &#8216;standard test dataset&#8217;? No? Then this test is overspecified. Yes? Then the test is dependent on something that is not stated clearly. In either case, it is dependent on a &#8216;standard dataset&#8217;.</li>
<li>Is JRHartley really interested in clicking buttons, typing into text fields, <em>etc.</em>? <em>i.e.</em> is the logic we are testing really about button clicks and typing? This test is specifying mechanisms rather than outcome.</li>
</ul>
<p>These issues contribute to brittleness and difficulties with maintenance. In addition, the dependency on standard data frequently leads to slow tests because there is more data than required.</p>
<p>My general approach to these problems is to focus on <strong>abstraction</strong> and <strong>composability</strong>. The solutions shown below achieve these fundamental aspects of software development partially by using a domain specific language in fluent interface style (although the fluency is limited and I usually go considerably further). By good fortune, Debasish Ghosh describes an approach to building DSLs <a href="http://debasishg.blogspot.com/2010/02/dsl-grow-your-syntax-on-top-of-clean.html">here</a> that is precisely what I am advocating.</p>
<p>However, this choice is largely irrelevant. You could achieve the results with, for example,  FIT, Fitness, Concordion or some other tool instead. I have never used those tools and suspect that I don&#8217;t really want to, but if you like them, go for it.</p>
<h3>Dependency on a &#8216;Standard Dataset&#8217;</h3>
<p><strong>Note:</strong> Although this section refers to databases, the same argument applies if, for example, your system accepts feed files from other systems and processes them.</p>
<p>My preference is for each test to start with an empty database schema and to populate it with exactly what is needed. This tends to:</p>
<ul>
<li>prevent one test from destroying the data that another test depends on</li>
<li>prevent tests from becoming dependent on an incidental aspect of the data</li>
<li>prevent more and more data being added to the database in order to accomodate new tests without breaking previous tests</li>
<li>make tests run quickly because there is very little data in the database</li>
</ul>
<p>However, I do not want each test to have a bunch of database inserts, because doing so will make the test fragile with respect to database changes and in any case, doing this specifies the test at the wrong level. Therefore the <strong>database setup must be abstracted</strong>.</p>
<p>In order to truly achieve this, the abstraction must be above the level of database tables; for example, if tests need to know that in order to add a <em>book</em> to the database, a <em>publisher</em> must be created first, each test:</p>
<ul>
<li>has structural knowledge of the database leading to duplication of information</li>
<li>contains information that is not relevant to the test leading to overspecified tests</li>
</ul>
<p>In the example above, as far as the test is concerned, the book needs two attributes: a name and an author. Undoubtedly, the book will have many more attributes and relationships in the database, but none of these are relevant to this test and so should not be part of the setup. My DSL will therefore start to look like this:</p>
<pre>public void testOrderBook() {
    given()
        .aBook()
            .title("Fly Fishing")
            .author("Hartley");

    ...
}</pre>
<p>The <em>given()</em> method is an entry point into the fluent interface and this expression should be read &#8216;Given a book with title &#8220;Fly Fishing&#8221; and author &#8220;Hartley&#8221;&#8216;. The important aspect of this is that the <em>book()</em> method initialises all of the book&#8217;s fields and knows how to build a book with integrity in the database. I usually initialise fields to random values.</p>
<p>This deals with the dependency on the standard data issue. However, it does not eliminate the over-specificity of the test. To put it simply, while the test is interested in the title and author, it should be non-specific about what title and author is actually used.</p>
<h3>Overspecificity</h3>
<p>In order to solve this problem, we need to allow the title and author to be given to us, rather than prescribed. As said earlier, my convention is to randomise any unspecified fields. So not specifying an author and title will result in what we want.</p>
<pre>public void testOrderBook() {
    Book book = given().aBook();

    ...
}</pre>
<p>We can now express the rest of the test using the book&#8217;s properties. We will see how to do that later.</p>
<p>Some might feel uncomfortable that something important has been lost from this fixture; the fact that the test does depend on an author and title and yet we are not setting up the book with a particular author and title. If that really bothers you, it is easily remedied (I&#8217;ll use the more terse form above for the rest of the article though):</p>
<pre>public void testOrderBook() {
    String author = given().anAuthor();
    String title = given().aBookTitle();

    Book book = given()
        .aBook()
            .author(author)
            .title(title);

    ...
}</pre>
<p>The important point is that the test is now free of pre-existing fixture data and is minimally specific.</p>
<h3>Specify Tests In Business Terms</h3>
<p>The other concern in the original test was that it was expressed in terms of what to type into form fields and what buttons to click. We should hide this away:</p>
<pre>public void testOrderBook() {
    Book book = given().aBook()

    ...

    then()
        .searchingFor(book.getTitle() + " " + book.getAuthor());

    resultsIn()
        .searchResults(book);

    ...
}</pre>
<p>The logic of how to do the search is hidden behind the <em>searchingFor(&#8230;)</em> method. The only relevant thing passed is the search term. Subsequently, we make sure that the results returned from the search contain the book. We could be more specific and assert that the search results contain only one book. Of course, for that to have any real relevance, more than one book would have to be created in the database.</p>
<p>This test now does not directly depend on button clicks and, apart from a few artifacts of the Java language, is pretty easy to understand at the level of business interactions.</p>
<p>Finally, we want to place the order:</p>
<pre>public void testOrderBook() {
    Book book = given().aBook();
    User user = given().aUser();

    loginAs(user);

    then()
        .searchingFor(book.getTitle() + " " + book.getAuthor())

    resultsIn()
        .searchResults(book);

    then()
        .select(book)
        .order()

    resultsIn()
        .anOrder(book, user);
}</pre>
<p>And once again, details about how the order is placed and how we verify that the order has been placed are abstracted away. Of course, if the user was able to check their orders on a web-page, we could use that page to determine that the order has been placed. Otherwise, we might go to the database to make sure that an entry has been added to an appropriate table. We might also expect an email to be sent, so the <em>anOrder(Book, User)</em> method might verify that too. The point is that all of that can be hidden in <em>anOrder(Book, User)</em> and can be changed over time if necessary.</p>
<h3>Emergent Goodness</h3>
<p>The approach described above brings enough benefits as it is; fixture data independence and tests specified at the level of the business process. However, there are now two things that also emerge:</p>
<ul>
<li>Because the DSL is written in fluent interface style in Java, as more tests are written, the fluent interface helps to guide the writing of tests. New tests can be composed very quickly.</li>
<li>The test is not tied to an implementation. The fact that this started life as a test for a web-app does not mean that it will always be so. An entire test suite can be reused to test, for example, a REST api, or a B2B messaging system for book supplies. All that is needed is to reimplement the model behind the DSL appropriately. This may not be a small task, but the fact remains that the tests themselves can be used in many ways.</li>
</ul>
<p>This latter point has been exercised on one of our recent projects in which there were multiple ways of using the system (web-app, REST API and message queues each offering the same functionality to clients).</p>
<h3>Conclusion</h3>
<p>In order to keep automated acceptance tests maintainable, fast and flexible, focus on those staples of solid development: abstraction and composability. Avoid &#8216;standard data sets&#8217; and express tests in terms of business processes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.casualmiracles.com/2010/03/04/writing-maintainable-acceptance-tests/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  www.casualmiracles.com/blog/feed/ ) in 0.79721 seconds, on Feb 6th, 2012 at 9:43 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 6th, 2012 at 10:43 am UTC -->
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- Quick Cache Is Fully Functional :-) ... A Quick Cache file was just served for (  www.casualmiracles.com/blog/feed/ ) in 0.00115 seconds, on Feb 6th, 2012 at 10:26 am UTC. -->
