<?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>Zilverblog</title>
	<atom:link href="http://blog.zilverline.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.zilverline.com</link>
	<description>_Zilverline blog</description>
	<lastBuildDate>Mon, 16 Apr 2012 11:33:08 +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>Architect in Scrum</title>
		<link>http://blog.zilverline.com/2012/04/16/architect-in-scrum/</link>
		<comments>http://blog.zilverline.com/2012/04/16/architect-in-scrum/#comments</comments>
		<pubDate>Mon, 16 Apr 2012 09:05:59 +0000</pubDate>
		<dc:creator>Michael Franken</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Scrum]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[architect]]></category>
		<category><![CDATA[architecting]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[lean]]></category>
		<category><![CDATA[scrum]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=917</guid>
		<description><![CDATA[Last friday I gave a Masterclass called &#8216;Lean Agile Architecting&#8217; to architects. Very interesting masterclass and a couple of things struck me. The issue for architects in an Agile environment is their position and responsibility. The thing with the change from waterfall to agile is that architects feel their role is being undercut, the team just <a href='http://blog.zilverline.com/2012/04/16/architect-in-scrum/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Last friday I gave a Masterclass called &#8216;Lean Agile Architecting&#8217; to architects. Very interesting masterclass and a couple of things struck me. <em>The</em> issue for architects in an Agile environment is their position and responsibility.</p>
<p>The thing with the change from waterfall to agile is that architects feel their role is being undercut, the team just goes fast and are only paying attention to the Product Owner. The standard answer they seem to get is: &#8216;then join the team&#8217;, but they feel reluctant to do so, and most of the times they can not fully commit (full time). So they pass, and they feel miserable about it, since now this Agile project is going to make mistakes, and can not learn from past experiences and their expertise.</p>
<p>The answer lies in the closer observation of the definition of Agile and Architecture.<br />
<span id="more-917"></span></p>
<p>Going agile is not the same as going fast, as the Agile Manifesto&#8217;s first principle says:</p>
<blockquote><p>Our highest priority is to satisfy the customer through <em>early</em> and <em>continuous</em> delivery of valuable software.</p></blockquote>
<p>So not just fast (early), but continuous too! And that&#8217;s the whole point of the position of architecture in Scrum/XP/Agile. In order to be able to continue to go fast, we have to make sure we mind our architecture, since architecture is:</p>
<blockquote><p>The set of design decisions that minimize the cost of development, maintenance and use (my definition, close enough to Grady Booch&#8217;s)</p></blockquote>
<p>So the whole point is that architects make sure that teams can go fast now and ever after, and that the cost of use and maintenance is proportional to the development investment. So architecture is not a stable deliverable or document, much better to speak about architecting; the process of keeping the architecture aligned with the product development and agile process.</p>
<p>Architecting is about identifying stakeholders that might be overlooked by the team and Product Owner, such as Support, Legal and 3rd party vendors. Architecting is about challenging the Product Owner and team to go slow, in order to be able to go fast by high quality standards, such as readability, 95%+ test coverage, early integration and performance testing, refactoring and the boy scout rule.</p>
<p>So architects, make sure you identify and represent stakeholders, and get their points on the Product Backlog (yes, it may contain non-functionals) by working closely with the Product Owner. You are a major stakeholder! Assist the team by making them go slow for a good reason, namely to serve previously overlooked stakeholders. There is a subtle balance here, if in doubt go fast with the Product Owner, and only address the issue when velocity drops because of technical debt.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2012%2F04%2F16%2Farchitect-in-scrum%2F&amp;title=Architect%20in%20Scrum" id="wpa2a_2"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2012/04/16/architect-in-scrum/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Picking the right abstraction</title>
		<link>http://blog.zilverline.com/2012/04/11/picking-the-right-abstraction/</link>
		<comments>http://blog.zilverline.com/2012/04/11/picking-the-right-abstraction/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 20:09:58 +0000</pubDate>
		<dc:creator>Erik Rozendaal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[abstraction]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=856</guid>
		<description><![CDATA[Recently I had to adapt some older Java code to support a new requirement: an existing CSV report needed to include a user&#8217;s email address, translated from the user id. Pretty simple, but how does the CSV report generator translate the user id to an email address? The obvious implementation is to simply pass the <a href='http://blog.zilverline.com/2012/04/11/picking-the-right-abstraction/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Recently I had to adapt some older Java code to support a new requirement: an existing CSV report needed to include a user&#8217;s email address, translated from the user id. Pretty simple, but how does the CSV report generator translate the user id to an email address?<br />
<span id="more-856"></span></p>
<p>The obvious implementation is to simply pass the <code>UserDao</code> directly to the report class<sup><a href="#fn1" id="r1">[1]</a></sup>:</p>
<p>[code lang=java]<br />
package com.example.fizzbuzz.reports;</p>
<p>import com.example.fizzbuzz.dao.UserDao;<br />
import com.example.fizzbuzz.domain.User;</p>
<p>public class FizzBuzzCsvReport extends CsvReport {</p>
<p>    private final UserDao userDao;</p>
<p>    public FizzBuzzCsvReport(UserDao userDao) {<br />
        this.userDao = userDao;<br />
    }</p>
<p>    public String[] headers() {<br />
        return new String[] { "Fizzy", "Buzzy", "Email" };<br />
    }</p>
<p>    public String[] row(FizzBuzz data) {<br />
        User user = userDao.findById(data.getUserId());<br />
        return new String[] {<br />
            data.getFizz(),<br />
            data.getBuzz(),<br />
            user.getEmail()<br />
        };<br />
    }<br />
}<br />
[/code]</p>
<p>The <code>UserDao</code> is injected into the constructor of the <code>FizzBuzzCsvReport</code> and used in the <code>row</code> method to translate the user id into an email address. Simple and probably what most Java code would look like. Unfortunately, this is not the right solution<sup><a href="#fn2" id="r2">[2]</a></sup>. Let&#8217;s write a unit test:</p>
<p>[code lang=java]<br />
package com.example.fizzbuzz.reports;</p>
<p>import static org.junit.Assert.*;<br />
import static org.mockito.Mockito.*;<br />
import org.junit.Test;</p>
<p>import com.example.fizzbuzz.dao.UserDao;<br />
import com.example.fizzbuzz.domain.Role;<br />
import com.example.fizzbuzz.domain.User;</p>
<p>public class FizzBuzzCsvReportTest {<br />
    @Test<br />
    public void test_row_generation() {<br />
        UserDao userDao = mock(UserDao.class);<br />
        when(userDao.findById("userid")).thenReturn(<br />
            new User("userid", "user name", "user@example.com", new Role[] { Role.ADMINSTRATOR }));<br />
        FizzBuzzCsvReport subject = new FizzBuzzCsvReport(userDao);</p>
<p>        String[] result = subject.row(new FizzBuzz("fizz", "buzz", "userid"));</p>
<p>        assertArrayEquals(<br />
            new String[] { "fizz", "buzz", "user@example.com" },<br />
            result);<br />
    }<br />
}<br />
[/code]</p>
<p>That&#8217;s quite a bit of overhead just to perform a simple check! Why is it so hard to write the test? We&#8217;re even <a href="http://stackoverflow.com/questions/2697783/what-does-program-to-interfaces-not-implementations-mean">programming to an interface, not an implementation</a>!</p>
<p>The main problem is not that <code>UserDoa</code> is not an abstraction (it is), but that it is the wrong abstraction for this usage. <code>UserDao</code> abstracts over how users are stored<sup><a href="#fn3" id="r3">[3]</a></sup>, and by passing in the <code>UserDao</code> to the report we unnecessarily couple the report to the details of how users are represented and managed within the rest of our system. Note that using a dynamic language doesn&#8217;t really help either. The coupling would be less (no need to agree on the exact type) but the report would still require an object that responds to the <code>findById</code> message with an object that responds to the <code>getEmail</code> message.</p>
<p>So what would be the right abstraction? Let&#8217;s go back to the new requirement: &#8220;given the user id, add the user&#8217;s email address&#8221;. What&#8217;s the simplest abstraction that could work here? Let&#8217;s just use a <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html">function</a>:</p>
<p>[code lang=java]<br />
package com.example.fizzbuzz.reports;</p>
<p>import com.google.common.base.Function;</p>
<p>public class FizzBuzzCsvReport extends CsvReport {</p>
<p>    private final Function<String, String> userIdToEmail;</p>
<p>    public FizzBuzzCsvReport(Function<String, String> userIdToEmail) {<br />
        this.userIdToEmail = userIdToEmail;<br />
    }</p>
<p>    public String[] headers() {<br />
        return new String[] { "Fizzy", "Buzzy", "Email" };<br />
    }</p>
<p>    public String[] row(FizzBuzz data) {<br />
        return new String[] {<br />
            data.getFizz(),<br />
            data.getBuzz(),<br />
            userIdToEmail.apply(data.getUserId())<br />
        };<br />
    }<br />
}<br />
[/code]</p>
<p>Now the report is fully decoupled from our application&#8217;s user infrastructure and is much easier to test:</p>
<p>[code lang=java]<br />
package com.example.fizzbuzz.reports;</p>
<p>import static org.junit.Assert.*;<br />
import java.util.Collections;<br />
import org.junit.Test;<br />
import com.google.common.base.Functions;</p>
<p>public class FizzBuzzCsvReportTest {<br />
    @Test<br />
    public void test_row_generation() {<br />
        FizzBuzzCsvReport subject = new FizzBuzzCsvReport(Functions.forMap(<br />
            Collections.singletonMap("userid", "user@example.com")));</p>
<p>        String[] result = subject.row(new FizzBuzz("fizz", "buzz", "userid"));</p>
<p>        assertArrayEquals(<br />
            new String[] { "fizz", "buzz", "user@example.com" },<br />
            result);<br />
    }<br />
}<br />
[/code]</p>
<p>We use the handy <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Functions.html#forMap(java.util.Map)"><code>Functions.forMap</code></a> method to create a function from a map<sup><a href="#fn4" id="r4">[4]</a></sup> and use this in our test. Compared to the previous version, setup boilerplate has been reduced by 57.1%<sup><a href="#fn5" id="r5">[5]</a></sup>. </p>
<p>Obviously, the actual production code (for example, the controller that let&#8217;s the user download the CSV) will still have to adapt the <code>UserDao</code> to the <code>Function</code> interface to make use of the <code>FizzBuzzCsvReport</code>. This is straightforward and only needs to be defined once. With Java 8&#8242;s upcoming <a href="http://openjdk.java.net/projects/lambda/">lambda support</a> this will be even easier. To summarize:</p>
<ul>
<li>Prefer simple, well-understood abstractions over home-grown variants (in this case a <code>Function&lt;String, String&gt;</code> versus a <code>UserDao</code>).</li>
<li>By defining the <code>FizzBuzzCsvReport</code> in terms of a <code>Function&lt;String, String&gt; userIdToEmail</code> we make clear what the report needs and also limits what it can do (<a href="http://en.wikipedia.org/wiki/Principle_of_least_privilege">principle of least privilege</a>). With the <code>UserDao</code> approach we wouldn&#8217;t know what exactly the report is using that DAO for, it could even be deleting users!</li>
<li>Using an abstraction like <code>Function</code> gives you a huge library of pre-defined tools: adapting maps as functions, using <a href="http://code.google.com/p/guava-libraries/issues/detail?id=489#c5">memoization or caching</a>, function composition, etc. Compare this to having to write your own caching adapter for a <code>UserDao</code>!</li>
<li>Function is just the start. There are <a href="http://blog.sigfpe.com/2009/01/haskell-monoids-and-their-uses.html">many others</a> that are <a href="http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-map">simple</a> and <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids">widely applicable</a>.</li>
</ul>
<style>
span:target {
  background-color: #F0F0F0;
}
</style>
<p><small><br />
Footnotes:<br />
<span id="fn1"><a href="#r1">[1]</a> Code simplified for explanatory reasons.</span><br />
<span id="fn2"><a href="#r2">[2]</a> There are many other possible solutions for this example, but see <a href="#fn1">footnote 1</a>.</span><br />
<span id="fn3"><a href="#r3">[3]</a> Abstracting over how users are stored was very useful when we replaced LDAP with a web based user management system.</span><br />
<span id="fn4"><a href="#r4">[4]</a> In many languages collections are automatically functions. Scala&#8217;s <a href="http://www.scala-lang.org/api/current/scala/collection/immutable/Map.html">Map</a> and other collections already extend <a href="http://www.scala-lang.org/api/current/scala/Function1.html">scala.Function1</a>, so you can pass a <code>Map</code> whenever a function is expected. Ruby 1.9&#8242;s <a href="http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-5B-5D">Array</a>, <a href="http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-5B-5D">Hash</a>, <a href="http://www.ruby-doc.org/core-1.9.3/Proc.html#method-i-5B-5D">Proc</a> (Ruby&#8217;s function class), and <a href="http://www.ruby-doc.org/core-1.9.3/String.html#method-i-5B-5D">String</a> classes all respond to the <code>[]</code> method, etc.</span><br />
<span id="fn5"><a href="#r5">[5]</a> 98% of all statistics are made up.</span><br />
</small></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2012%2F04%2F11%2Fpicking-the-right-abstraction%2F&amp;title=Picking%20the%20right%20abstraction" id="wpa2a_4"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2012/04/11/picking-the-right-abstraction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The power of feedback in Scrum</title>
		<link>http://blog.zilverline.com/2012/04/01/the-power-of-feedback-in-scrum/</link>
		<comments>http://blog.zilverline.com/2012/04/01/the-power-of-feedback-in-scrum/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 20:17:00 +0000</pubDate>
		<dc:creator>Mark Suurmond</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Scrum]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[Battleship]]></category>
		<category><![CDATA[Feedback]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[Power]]></category>
		<category><![CDATA[scrum]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=834</guid>
		<description><![CDATA[Searching the web for new Agile games I came across: You sunk my Methodology. This game seemed like a strong metaphor to show the power of early feedback, while using Scrum. In order to use this game in a presentation Bob, Daniel and I made a Javascript (standalone) version of it which uses variable iterations <a href='http://blog.zilverline.com/2012/04/01/the-power-of-feedback-in-scrum/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Searching the web for new Agile games I came across: You sunk my <a href="http://tastycupcakes.org/2012/02/you-sunk-my-methodology/"target="_blank">Methodology</a>. This game seemed like a strong metaphor to show the power of early feedback, while using Scrum. </p>
<p>In order to use this game in a presentation Bob, Daniel and I made a Javascript (standalone) version of it which uses variable iterations of shooting at the enemy&#8217;s ships. Board layouts are random and you get 40 shots in total to destroy the enemy&#8217;s fleet. After each iteration you get feedback about hits and misses. If you use iterations of 1, you are playing the regular battleship-game.</p>
<p>Each shot costs 10.000 and when you sink a ship you get the_ships_size * 50.000 (e.g. the submarine of size 3 will reward you with 150.000). If you keep track of the balance after each iteration, you could also try to get across the idea that stopping after a few iterations might give &#8216;good enough&#8217; rewards.</p>
<p>It can be downloaded from our GitHub repository as a <a href="https://github.com/zilverline/battleship/zipball/master">zip</a> or you can take a look at our <a href="https://github.com/zilverline/battleship">code</a>. Just double click on the index.html (in the public folder) to start a game. </p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2012%2F04%2F01%2Fthe-power-of-feedback-in-scrum%2F&amp;title=The%20power%20of%20feedback%20in%20Scrum" id="wpa2a_6"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2012/04/01/the-power-of-feedback-in-scrum/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Play! 2.0: A First Impression</title>
		<link>http://blog.zilverline.com/2012/02/21/play-2-0-a-first-impression/</link>
		<comments>http://blog.zilverline.com/2012/02/21/play-2-0-a-first-impression/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 14:22:44 +0000</pubDate>
		<dc:creator>Erik Rozendaal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[play framework]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=749</guid>
		<description><![CDATA[Play! is a web framework for Java and Scala. Play promises to bring the developer productivity of web frameworks like Ruby on Rails to the Java and Scala languages. Of course, it wouldn&#8217;t make much sense just to copy Rails. So Play adds its own spin: Play 2.0 is fully statically type checked, giving the <a href='http://blog.zilverline.com/2012/02/21/play-2-0-a-first-impression/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.playframework.org/2.0">Play!</a> is a web framework for Java and Scala. Play promises to bring the developer productivity of web frameworks like <a title="Ruby on Rails" href="http://rubyonrails.org/">Ruby on Rails</a> to the Java and Scala languages. Of course, it wouldn&#8217;t make much sense just to copy Rails. So Play adds its own spin: Play 2.0 is fully statically type checked, giving the developer quick feedback when something doesn&#8217;t make any sense.</p>
<p>Now that Play 2.0 is getting closer to final release I took some time to dive in. Here are my first impressions, using the Scala APIs.<br />
<span id="more-749"></span></p>
<h2>TL;DR</h2>
<p>Pros:</p>
<ul>
<li>Automatic recompile on refresh gives you extremely quick feedback.</li>
<li>High modularity makes Play easy to learn, use, and extend.</li>
<li>Very easy deployment to production environments.</li>
<li>Type safe templates and routes make it easier to keep your application consistent.</li>
<li>High performance with support for both synchronous and asynchronous HTTP handling.</li>
<li>Java and Scala APIs are quite similar, so should allow easy transfer of skills.</li>
<li>Support for pre-compiled assets including <a href="http://coffeescript.org/">CoffeeScript</a>, <a href="http://lesscss.org/">LESS CSS</a>, and the <a href="http://code.google.com/closure/compiler/">Closure JavaScript compiler</a>.</li>
<li>Sessions are simple cookies, making it easy to scale or perform zero-downtime upgrades.</li>
</ul>
<p>Cons:</p>
<ul>
<li>Support for <a href="https://play.lighthouseapp.com/projects/82401/tickets/8">WAR packaging</a> is not planned until 2.1. This is needed if you need to deploy in a Servlet Container.</li>
<li>Not backwards compatible with the older Play 1.x framework.</li>
<li>Custom <code>conf/routes</code> format instead of simple DSL like <a href="http://www.scalatra.org/">Scalatra</a> or <a href="http://spray.cc">spray.cc</a>.</li>
<li>Many APIs rely on singletons (Scala) or static methods (Java), which can make testing challenging. However, fake implementations of the main abstractions are provided (Application, Request, etc).</li>
</ul>
<h2>Out of the box experience</h2>
<p>Getting started with Play is straigthforward. Just download the distribution, unpack it, and add it to your $PATH. After that type <code>play new my-app</code>, select your application&#8217;s name (defaults to <code>my-app</code> in this example), and type (Scala, Java, or empty). After choosing the Scala application type I ended up with a new directory containing just a few directories and files (with just 19 lines of Scala code and 17 lines of HTML templates).</p>
<p>Starting the application is as easy as typing <code>play run</code> and pointing your browser to <a href="http://localhost:9000/">http://localhost:9000/</a>. The initially load takes a while as it needs to compile templates and Scala sources. After the page loads you get a nice explanation what to do next and plenty of documentation links:</p>
<p><a href="http://blog.zilverline.com/wp-content/uploads/2012/02/welcome.png"><img class="alignright size-full wp-image-771" title="welcome" src="http://blog.zilverline.com/wp-content/uploads/2012/02/welcome.png" alt="" width="914" height="641" /></a></p>
<h2>Controllers and templates</h2>
<p>The first thing you encounter in any web framework is to mapping from HTTP requests to your code. In Play this is extremely straightforward. The request method and path are located in the <code>conf/routes</code> file and the indicated method is invoked in your controller. An example route entry is:</p>
<pre>GET     /            controllers.Application.index</pre>
<p>So whenever the home page is requested the <code>controllers.Application.index</code> method is invoked. Notice that you&#8217;ll get a compile time error if this method does not exist or requires parameters. So if you add the following to the <code>conf/routes</code> file:</p>
<pre>GET     /:page       controllers.Application.page(page, format ?= "html")</pre>
<p>and refresh your browser you&#8217;ll quickly see an error message:</p>
<p><a href="http://blog.zilverline.com/wp-content/uploads/2012/02/route-error.png"><img class="alignright size-full wp-image-756" title="Compilation Error" src="http://blog.zilverline.com/wp-content/uploads/2012/02/route-error.png" alt="Compilation Error" width="914" height="641" /></a></p>
<p>Fixing this is easy, just add the missing method to the <code>controller.Application</code> object:</p>
<div id="gist-1859530" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">def</span> <span class="n">page</span><span class="o">(</span><span class="n">name</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">format</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">=</span> <span class="nc">Action</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nc">Ok</span><span class="o">(&lt;</span><span class="n">p</span><span class="o">&gt;</span><span class="nc">You</span> <span class="n">requested</span> <span class="n">page</span> <span class="o">{</span><span class="n">name</span><span class="o">}</span> <span class="n">in</span> <span class="n">format</span> <span class="o">{</span><span class="n">format</span><span class="o">}&lt;/</span><span class="n">p</span><span class="o">&gt;.</span><span class="n">toString</span><span class="o">).</span><span class="n">as</span><span class="o">(</span><span class="nc">HTML</span><span class="o">)</span></div><div class='line' id='LC3'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1859530/2bf32fefaaac09630a6e87d41ac26ef745b4b0e5/action.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1859530#file_action.scala" style="float:right;margin-right:10px;color:#666">action.scala</a>
            <a href="https://gist.github.com/1859530">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>As you can see a controller action is just a method that returns an <code>Action</code>. The <code>Action</code> in turn returns an <code>Ok</code> response, which translates into a HTTP <code>200 OK</code> response. What I like here is that the controller method is directly linked from the <code>conf/routes</code> file without me having to remember any mapping conventions. There is also no complicated rendering pipelines that are typically associated with component based web frameworks like JSF or Wicket.</p>
<p>In this action we directly returned a piece of HTML. It is also possible to use templates. Let&#8217;s change the index page to link to our new controller action. By changing the <code>index.scala.html</code> template to:</p>
<div id="gist-1859530" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>@(message: String)</div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'>@main(&quot;Welcome to Play 2.0&quot;) {</div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;@routes.Application.page(&quot;</span><span class="na">1984</span><span class="err">&quot;,</span> <span class="err">&quot;</span><span class="na">PDF</span><span class="err">&quot;)&quot;</span><span class="nt">&gt;</span>page example<span class="nt">&lt;/a&gt;</span></div><div class='line' id='LC5'>}</div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1859530/20f226c50e80a347b2fcbf237836ced80dc886c4/index.scala.html" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1859530#file_index.scala.html" style="float:right;margin-right:10px;color:#666">index.scala.html</a>
            <a href="https://gist.github.com/1859530">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>a new link is rendered that maps to the new route. After refreshing the browser you can now click the link to navigate to your new page action. Extremely straightforward and especially nice is the use of type safe URLs and the light-weight template syntax (just using the <code>@</code> sign to add some Scala code in your HTML template).</p>
<p>Also nice is that templates are turned into ordinary methods (with the first line of the template becoming the parameter list) that can be called from controllers, other templates, or tests. In the template above the <code>main</code> template is invoked to render layout around the provided link.</p>
<h2>Forms</h2>
<p>Play also has support for forms, validation, and binding form data to domain objects. Unlike most other web frameworks it is not necessary to alter your domain objects to use them with forms. Specifically, there is no need to add a default constructor or any setters. Here is an example domain object <code>User</code> with a form definition:</p>
<div id="gist-1859530" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">import</span> <span class="nn">play.api.data._</span><span class="o">,</span> <span class="nc">Forms</span><span class="o">.</span><span class="k">_</span><span class="o">,</span> <span class="n">validation</span><span class="o">.</span><span class="nc">Constraints</span><span class="o">.</span><span class="k">_</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="c1">// Domain object</span></div><div class='line' id='LC4'><span class="k">case</span> <span class="k">class</span> <span class="nc">User</span><span class="o">(</span><span class="n">name</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">age</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="c1">// Form definition</span></div><div class='line' id='LC7'><span class="k">val</span> <span class="n">userForm</span> <span class="k">=</span> <span class="nc">Form</span><span class="o">(</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="n">mapping</span><span class="o">(</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="s">&quot;name&quot;</span> <span class="o">-&gt;</span> <span class="n">nonEmptyText</span><span class="o">,</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="s">&quot;age&quot;</span> <span class="o">-&gt;</span> <span class="n">number</span><span class="o">(</span><span class="n">min</span> <span class="k">=</span> <span class="mi">0</span><span class="o">,</span> <span class="n">max</span> <span class="k">=</span> <span class="mi">150</span><span class="o">)</span></div><div class='line' id='LC11'>&nbsp;&nbsp;<span class="o">)(</span><span class="nc">User</span><span class="o">.</span><span class="n">apply</span><span class="o">)(</span><span class="nc">User</span><span class="o">.</span><span class="n">unapply</span><span class="o">))</span></div><div class='line' id='LC12'>&nbsp;&nbsp;</div><div class='line' id='LC13'><span class="c1">// Form submit action</span></div><div class='line' id='LC14'><span class="k">def</span> <span class="n">register</span> <span class="k">=</span> <span class="nc">Action</span> <span class="o">{</span> <span class="k">implicit</span> <span class="n">request</span> <span class="k">=&gt;</span></div><div class='line' id='LC15'>&nbsp;&nbsp;<span class="n">userForm</span><span class="o">.</span><span class="n">bindFromRequest</span><span class="o">.</span><span class="n">fold</span><span class="o">(</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">errors</span> <span class="k">=&gt;</span> <span class="nc">BadRequest</span><span class="o">(</span><span class="n">views</span><span class="o">.</span><span class="n">html</span><span class="o">.</span><span class="n">index</span><span class="o">(</span><span class="n">errors</span><span class="o">)),</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">user</span> <span class="k">=&gt;</span> <span class="nc">Redirect</span><span class="o">(</span><span class="n">routes</span><span class="o">.</span><span class="nc">Application</span><span class="o">.</span><span class="n">index</span><span class="o">))</span></div><div class='line' id='LC18'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1859530/c342701b80d04588ca30ec9f827366c5141c6c60/form.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1859530#file_form.scala" style="float:right;margin-right:10px;color:#666">form.scala</a>
            <a href="https://gist.github.com/1859530">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The form defines two fields with validation and the mapping from the form fields to the domain object (in this case by using the Scala generated <code>User.apply</code> and <code>User.unapply</code> methods).</p>
<p>The <code>register</code> action uses the form definition to perform validation and bind data from the request to the domain object. In case of errors, the page is rerendered with the validation errors. Otherwise a new user instance is available (and in this case a simple redirect is performed, a real application would probably save the user somewhere). Notice that it is not possible to get a (partially) invalid user object, unlike most other form validation frameworks (like Ruby on Rails, Spring MVC, and Wicket).</p>
<p>To render the form there are some predefined form helpers (also available in <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> variant). Unfortunately the field names are not statically checked against the form definition:</p>
<div id="gist-1859530" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>@(registrationForm: Form[User])</div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'>@helper.form(action = routes.Application.register) {</div><div class='line' id='LC4'>&nbsp;&nbsp;@helper.inputText(registrationForm(&quot;name&quot;))</div><div class='line' id='LC5'>&nbsp;&nbsp;@helper.inputText(registrationForm(&quot;age&quot;))</div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="nt">&lt;input</span> <span class="na">type=</span><span class="s">&quot;submit&quot;</span> <span class="na">value=</span><span class="s">&quot;Register&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC7'>}</div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1859530/cb012f5dcc2bc7402e72dcf0d82938bfd85e72f8/form.scala.html" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1859530#file_form.scala.html" style="float:right;margin-right:10px;color:#666">form.scala.html</a>
            <a href="https://gist.github.com/1859530">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<h2>Databases</h2>
<p>Play comes with built-in support for SQL/JDBC databases. The simplest way to use this to first enable the datasource in <code>conf/application.conf</code>:</p>
<pre>db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"</pre>
<p>Then add a schema evolution file <code>conf/evolutions/default/1.sql</code>:</p>
<div id="gist-1859530" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="o">#</span> <span class="c1">--- !Ups</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="k">create</span> <span class="k">table</span> <span class="n">users</span> <span class="p">(</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="n">name</span> <span class="nb">text</span> <span class="k">primary</span> <span class="k">key</span><span class="p">,</span> </div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="n">age</span> <span class="nb">int</span> <span class="k">not</span> <span class="k">null</span><span class="p">);</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="o">#</span> <span class="c1">--- !Downs</span></div><div class='line' id='LC8'>&nbsp;</div><div class='line' id='LC9'><span class="k">drop</span> <span class="k">table</span> <span class="n">users</span><span class="p">;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1859530/a10b0ec49f511c5af07fb5acfca86ca4e8c519ba/1.sql" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1859530#file_1.sql" style="float:right;margin-right:10px;color:#666">1.sql</a>
            <a href="https://gist.github.com/1859530">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>When you refresh the browser Play will notify you that you need to apply the schema migration:</p>
<p><a href="http://blog.zilverline.com/wp-content/uploads/2012/02/schema-evolution.png"><img class="alignright size-full wp-image-773" title="schema-evolution" src="http://blog.zilverline.com/wp-content/uploads/2012/02/schema-evolution.png" alt="" width="914" height="641" /></a></p>
<p>Pressing the &#8216;Apply this script now!&#8217; button will immediately perform the database migration.</p>
<p>Now that we have a running database it is easy to query using the JDBC API and the <a href="https://github.com/playframework/Play20/wiki/ScalaAnorm">Anorm</a> wrapper library:</p>
<div id="gist-1859530" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">import</span> <span class="nn">play.api.db._</span><span class="o">,</span> <span class="n">anorm</span><span class="o">.</span><span class="k">_</span><span class="o">,</span> <span class="n">play</span><span class="o">.</span><span class="n">api</span><span class="o">.</span><span class="nc">Play</span><span class="o">.</span><span class="n">current</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="k">def</span> <span class="n">registeredUsers</span> <span class="k">=</span> <span class="nc">DB</span><span class="o">.</span><span class="n">withConnection</span> <span class="o">{</span> <span class="k">implicit</span> <span class="n">connection</span> <span class="k">=&gt;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="nc">SQL</span><span class="o">(</span><span class="s">&quot;select name, age from users&quot;</span><span class="o">)().</span><span class="n">map</span><span class="o">(</span><span class="n">row</span> <span class="k">=&gt;</span> <span class="nc">User</span><span class="o">(</span><span class="n">row</span><span class="o">[</span><span class="kt">String</span><span class="o">](</span><span class="s">&quot;name&quot;</span><span class="o">),</span> <span class="n">row</span><span class="o">[</span><span class="kt">Int</span><span class="o">](</span><span class="s">&quot;age&quot;</span><span class="o">))).</span><span class="n">toList</span></div><div class='line' id='LC5'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1859530/997ba2caca6ad7639139b72928f52b5c50497cc2/users.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1859530#file_users.scala" style="float:right;margin-right:10px;color:#666">users.scala</a>
            <a href="https://gist.github.com/1859530">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Since <code>DB.withConnection</code>/<code>DB.withTransaction</code> gives you a plain JDBC connection it is also easy to use any other Java or Scala tool to handle database persistence.</p>
<h2>Deployment</h2>
<p><a href="https://github.com/playframework/Play20/wiki/Production">Deploying</a> a Play application is easy. My preference would be to use the <code>play dist</code> command that builds a ZIP archive. Then you only need a Java runtime and database installation on your production server to run your application (everything else is included in the ZIP, including the Scala libraries and a <code>start</code> script).</p>
<p>Another option is to use the <code>play stage</code> command to run the application in-place. Combine this with a <code>git push</code> to <a href="http://www.heroku.com/">Heroku</a> or your own production server and you&#8217;re ready to go.</p>
<h2>Performance</h2>
<p>Play is build on <a href="http://www.jboss.org/netty">Netty</a>, which provides very high HTTP server performance. Play supports both synchronous and asynchronous IO, so handling many long-lived connections should be possible (and Play provides excellent support for streaming using its <a href="https://github.com/playframework/Play20/wiki/Iteratees">Iteratees based data stream support</a>). Integration with <a href="http://akka.io/">Akka 2.0</a> should give you all the tools you need to build high-performance and highly-scalable applications.</p>
<p>To give you an idea, I had no trouble getting more than 10.000 HTTP requests per second (tested using <a href="http://jmeter.apache.org/">jmeter</a>) on my mid-2010 MacBook Pro (2.66 GHz Intel Core i7). The rendered HTML page was fairly trivial (just the user registration form as shown above), but it is good to know basic performance is very good.</p>
<h2>Conclusion</h2>
<p>This was just a first quick look at Play 2.0, but I&#8217;m quite impressed with the ease of learning, development, and deployment. Play 2.0 is a worthy addition to the <a href="http://blog.typesafe.com/typesafe-stack-adds-play-framework">Typesafe Stack</a> and should give Java and Scala developers a very good platform to build web applications on.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2012%2F02%2F21%2Fplay-2-0-a-first-impression%2F&amp;title=Play%21%202.0%3A%20A%20First%20Impression" id="wpa2a_8"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2012/02/21/play-2-0-a-first-impression/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Use your Daily Scrum as a success driver</title>
		<link>http://blog.zilverline.com/2011/08/24/use-your-daily-scrum-as-a-success-driver/</link>
		<comments>http://blog.zilverline.com/2011/08/24/use-your-daily-scrum-as-a-success-driver/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 15:16:16 +0000</pubDate>
		<dc:creator>Sander Nieuwenhuizen</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Scrum]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=705</guid>
		<description><![CDATA[Development teams new to Scrum are introduced to a number of mandatory aspects that come with the framework. One of these is the Daily Scrum, or often referred to as the Daily Standup (meeting) or Standup in short. The purpose of this meeting is to synchronize the status of the development team and to do <a href='http://blog.zilverline.com/2011/08/24/use-your-daily-scrum-as-a-success-driver/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Development teams new to Scrum are introduced to a number of mandatory aspects that come with the framework. One of these is the Daily Scrum, or often referred to as the Daily Standup (meeting) or Standup in short. The purpose of this meeting is to synchronize the status of the development team and to do this in a short and focused manner. In this post I&#8217;d like to discuss an anti-pattern I see observing and being part of Daily Scrum meetings and how to overcome it.<br />
<span id="more-705"></span></p>
<p><strong>It&#8217;s all about a shared goal</strong><br />
First I&#8217;d like to emphasize the essence of Agile and Scrum. It is all about delivering maximum value to your customer and/or end users. In order to achieve this (rather complex) goal, instead of working in a traditional hierarchical organizational setting in which management dictates and workers act, you work together as a group in order to achieve the best possible results. In fact this means not only the development team should work together as one, but the business and management in the organization should be aligned as well. All involved should strive for this same goal and realize they&#8217;re in it together.</p>
<p><strong>Nice, now back to the standup meeting</strong><br />
To determine and synchronize the current status in a sprint Scrum describes to ask each development team member (as taken from the <a href="http://www.scrum.org/storage/scrumguides/" target="_blank">Scrum Guide</a>):</p>
<ul>
<li>What has been accomplished since the last meeting?</li>
<li>What will be done before the next meeting?</li>
<li>What obstacles are in the way?</li>
</ul>
<p>At the end of this meeting every team member should be up to date with the team&#8217;s current status and should have clearly determined what to do for the rest of the day.</p>
<p><strong>Anti-pattern: the team actually is a group of individuals</strong><br />
In the real world however I see some different behavior and scenario&#8217;s. The most fundamental issue is that the team not having a shared goal. This is mostly reflected by developers individually working on backlog items or tasks. There is little or no cooperation going on and no real concern to finish a top class product as a group. The effect this has on a team is that the Daily Scrum is not running smoothly, or even considered a nuisance. The individuality symptom is often reflected through the three default questions asked using a slight twist (however, with a dramatic effect):</p>
<ul>
<li>What have <strong><em>you</em></strong> done since the last meeting?</li>
<li>What will <strong><em>you</em></strong> do before the next meeting?</li>
<li>What obstacles are in <strong><em>your</em></strong> way?</li>
</ul>
<p>The effect: the team accepts and embraces the fact of being individuals. Working as individual subgroups is a step forward, but a small one. There are a couple of risks involved when in this situation:</p>
<ul>
<li>The team and organization are dependent on individual team members. If such a team member is not in, the team struggles to do the work normally executed by that person. It limits the notion of collective code ownership, given by XP</li>
<li>Team members are focused on their own tasks with their own concerns and have little focus on the customer / end users</li>
<li>How can you make sure you will reach your commonly shared goal?</li>
</ul>
<p>A typical sprint backlog when in this situation will look like the one display below.</p>
<div id="attachment_739" class="wp-caption aligncenter" style="width: 583px"><a href="http://blog.zilverline.com/wp-content/uploads/2011/08/troubled-sprint-backlog.png"><img class="size-full wp-image-739 " title="Troubled sprint backlog" src="http://blog.zilverline.com/wp-content/uploads/2011/08/sprint-backlog1.png" alt="" width="573" height="375" /></a><p class="wp-caption-text">A troubled sprint backlog (image created by Henrik Kniberg)</p></div>
<p><strong>A few tips how to overcome this and work towards a shared goal and shared team responsibility</strong></p>
<ul>
<li>First, be sure to have one (!). Without having a goal, everything is acceptable. When having one, make sure this goal is spread and known by everyone involved. Every individual needs to be able to breathe the goal</li>
<li>It is allowed to have more than one Daily Scrum a day.<br />
It often comes as a surprise that Scrum allows you to synchronize more than once a day. I especially advice teams that are in a stressful situation &#8211; say prepping the Sprint Review meeting &#8211; to have frequent short meetings to make sure to deliver a great product Increment. It may be the term Daily Scrum is actually a bit unlucky</li>
<li>Focus on what you can do together as a team</li>
</ul>
<p>Try to ask questions like:</p>
<ul>
<li>When can <strong><em>we</em></strong> have this item finished?</li>
<li>What do <strong><em>we</em></strong> need to do to wrap up this item?</li>
<li>What can <strong><em>we</em></strong> do before the end of the day?</li>
<li>What do <strong><em>we</em></strong> need to do for the Sprint Review?</li>
</ul>
<p>I&#8217;ve seen asking these questions help teams to achieve shared responsibility towards reaching the end goal.</p>
<p>Remember: no single individual is responsible for reaching the goal.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2011%2F08%2F24%2Fuse-your-daily-scrum-as-a-success-driver%2F&amp;title=Use%20your%20Daily%20Scrum%20as%20a%20success%20driver" id="wpa2a_10"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2011/08/24/use-your-daily-scrum-as-a-success-driver/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Big -but not so visible- charts</title>
		<link>http://blog.zilverline.com/2011/04/12/big-but-not-so-visible-charts/</link>
		<comments>http://blog.zilverline.com/2011/04/12/big-but-not-so-visible-charts/#comments</comments>
		<pubDate>Tue, 12 Apr 2011 21:38:50 +0000</pubDate>
		<dc:creator>Lars Vonk</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Scrum]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=603</guid>
		<description><![CDATA[I am a big fan of Big Visible Charts, also referred to as Information Radiators. By radiating information using such charts everything is visible and people can use that information to act upon it. Recent observations made me realize that not all charts are visible though. Even when they are big and in your face. <a href='http://blog.zilverline.com/2011/04/12/big-but-not-so-visible-charts/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I am a big fan of <a href="http://xprogramming.com/articles/bigvisiblecharts/">Big Visible Charts</a>, also referred to as Information Radiators. By radiating information using such charts everything is visible and people can use that information to act upon it. Recent observations made me realize that not all charts are visible though. Even when they are big and in your face.<br />
<span id="more-603"></span><br />
Currently I am working at a client that is located in the centre of Amsterdam above the old postal office. In January or early February the postal office closed. This was announced about a year ago and I remember big visible signs were on the walls and doors to point the customer to the fact it was closing; on which date and where the new postal office would be located (this was next door actually).</p>
<p>A few weeks after it closed I started noticing that whenever I was outside grabbing some fresh air (or smoking if you wish <img src='http://blog.zilverline.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> ) people still came in, walked the up the stairs to find out that the postal office was closed. This happened every single day for a couple of weeks at least 3 times per cigarette. And these people were not only tourists but also knowledgeable Amsterdammers. </p>
<p>In the first couple of weeks the only thing that changed was that the original postal office sign itself was removed. People still walked the stairs only to find out the postal office was moved. After the first couple of weeks the new owner probably got fed up with people coming up to the new store and asking directions to the postal office:<br />
A new big sign was placed in front of the door that indicated the postal office was moved. At the same time the new postal office next door placed huge banners with their logo.</p>
<p><a href="http://blog.zilverline.com/wp-content/uploads/2011/04/chart1.jpg"><img src="http://blog.zilverline.com/wp-content/uploads/2011/04/chart1-150x150.jpg" alt="Chart in front of Postal office" title="Chart in front of Postal office" width="150" height="150" class="alignnone size-thumbnail wp-image-610" /></a><br />
<i>New big sign.</i></p>
<p><a href="http://blog.zilverline.com/wp-content/uploads/2011/04/postal-office.jpg"><img src="http://blog.zilverline.com/wp-content/uploads/2011/04/postal-office-150x150.jpg" alt="Postal office next door" title="Postal office" width="150" height="150" class="alignnone size-thumbnail wp-image-613" /></a><br />
<i>Postal office next door.</i></p>
<p>So clearly these Big Visible Charts should be noticed by everyone you think right? Well wrong. While enjoying fresh air I observed some people looked at the sign but ignored it, and some people didn&#8217;t even look at the sign and walked straight by it.<br />
When observing this I realized I experienced the same things in projects. Even though the information was there, it was visible and big, it was still ignored. Why did this happen? Why do people ignore this information? Here is my short analysis:</p>
<ul>
<li><b>The sign was not clear.</b> Looking closer at the sign you see a lot of information. It is so much people probably don&#8217;t know where to start reading. If this happens people will discard the complete sign.<br />
<a href="http://blog.zilverline.com/wp-content/uploads/2011/04/chart2.jpg"><img src="http://blog.zilverline.com/wp-content/uploads/2011/04/chart2-150x150.jpg" alt="" title="Chart in front of Postal office - zoom" width="150" height="150" class="alignnone size-thumbnail wp-image-611" /></a><br />
<i>Sign with information overload</i></p>
<li><b>Habit.</b> Habits are difficult to kill. This probably applies to most Amsterdammers who came into the building expecting the postal office. They knew from their year long experience the postal office is there. They probably discarded the sign as advertisement or something else and just went straight for their goal.
<li><b>Pointed to the wrong direction.</b> I noticed several tourist were brought to the location by taxi drivers. The taxi drivers didn&#8217;t know it was moved. Without questioning the tourists followed directions and just walked in the building to discover the postal office was gone.
</ul>
<p>Just when I wanted to blog about these findings something interesting happened. This week they replaced the sign with a newer version. To me this one is much clearer. I posted in front of the door for 4 times already and no one came up to me to ask directions for the new postal office. People stopped to read the sign and actually followed the directions.<br />
<a href="http://blog.zilverline.com/wp-content/uploads/2011/04/new-chart.jpg"><img src="http://blog.zilverline.com/wp-content/uploads/2011/04/new-chart-150x150.jpg" alt="Improved chart in front of Postal office" title="Improved chart in front of Postal office" width="150" height="150" class="alignnone size-thumbnail wp-image-612" /></a><br />
<i>Improved sign</i></p>
<p><b>How does this relate to my work?</b><br />
From time to time I experience what can happen if radiated information is not understood, not seen or misinterpreted. This goes from completely ignoring the information, to killing a project after the first sprint because the &#8220;radiated&#8221; velocity was not enough.<br />
When using Big Visible Charts we should take care on what we want to achieve by radiating this information, otherwise we might not reach the goal we want to achieve. When I started to think about this more consciously I discovered that I actually apply the <b>following guidelines</b> when creating these charts:</p>
<ul>
<li><b>Educate!</b> Big Visible Charts are not enough. People must learn how to read these charts and act upon it. This especially goes for doing Agile projects in traditional environments. People in these settings are typically not used to get that much information in such short time.
<li>If it is <b>outward-facing information</b> (e.g. for stakeholders) then the readers need to be able to understand it in a couple of seconds. Don&#8217;t use a lot of words, but use pictures or simple charts instead.
<li>If it is <b>inward-facing information</b> (e.g. for team members, product owner) then it can be fine-grained with details.
<li>You could try to <b>physically separate</b> the outward-facing information charts from the inward-facing information charts.
</ul>
<p>What guidelines do you apply while creating Big Visible Charts?</p>
<blockquote><p>
PS: After googling I also found some studies about successful (commercial) signs, for instance: http://web1.msue.msu.edu/imp/modtd/33719792.html. This also contains stuff like color schemes and such. Do you know more?
</p></blockquote>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2011%2F04%2F12%2Fbig-but-not-so-visible-charts%2F&amp;title=Big%20-but%20not%20so%20visible-%20charts" id="wpa2a_12"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2011/04/12/big-but-not-so-visible-charts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serializing strings, Unicode, and randomized testing using ScalaCheck</title>
		<link>http://blog.zilverline.com/2011/04/07/serializing-strings-unicode-and-randomized-testing-using-scalacheck/</link>
		<comments>http://blog.zilverline.com/2011/04/07/serializing-strings-unicode-and-randomized-testing-using-scalacheck/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 20:40:18 +0000</pubDate>
		<dc:creator>Erik Rozendaal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[ScalaCheck]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=557</guid>
		<description><![CDATA[While implementing a simple event store for an example application I needed to serialize JSON data to binary arrays and turn those bytes back into the original JSON. Obviously, that&#8217;s a piece of cake! [scala] // try1.scala def serialize(string: String) = string.getBytes; def deserialize(bytes: Array[Byte]) = new String(bytes); def test(string: String) { val actual = <a href='http://blog.zilverline.com/2011/04/07/serializing-strings-unicode-and-randomized-testing-using-scalacheck/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>While implementing a simple event store for an example application I needed to serialize JSON data to binary arrays and turn those bytes back into the original JSON. Obviously, that&#8217;s a piece of cake!</p>
<p><span id="more-557"></span></p>
<p>[scala]<br />
// try1.scala<br />
def serialize(string: String) = string.getBytes;<br />
def deserialize(bytes: Array[Byte]) = new String(bytes);<br />
def test(string: String) {<br />
  val actual = deserialize(serialize(string))<br />
  println(if (string == actual) &#8220;OK &#8220;.format(string)<br />
          else &#8220;FAIL expected  got &#8220;.format(string, actual))<br />
}</p>
<p>test(&#8220;&#8221;)<br />
test(&#8220;foo&#8221;)<br />
test(&#8220;the quick brown fox jumps over the lazy dog&#8221;)<br />
test(&#8220;\u2192&#8243;)<br />
[/scala]</p>
<p>Save this to a file (<code>try1.scala</code>) or get it from github at <a href="https://github.com/erikrozendaal/scalacheck-blog" title="erikrozendaal/scalacheck-blog">erikrozendaal/scalacheck-blog</a> and run it with the Scala &#8220;interpreter&#8221;:</p>
<p>[bash]<br />
$ scala try1.scala<br />
OK<br />
OK<br />
OK FAIL <?> expected got <?><br />
[/bash]</p>
<p>Oops, the last test fails on my laptop: <code>FAIL expected &lt;?&gt; got &lt;?&gt;</code>. The error message is not very helpful, but it turns out the default encoding used by Java on Mac OS X is <code>MacRoman</code>, and <code>String.getBytes</code> silently changes any unknown character to a question mark. Now silent corruption may make things easier, but is normally unwanted. Especially when building an event store!</p>
<p>Let&#8217;s try again. This time we explicitly use the UTF-8 encoding:</p>
<p>[scala]<br />
// try2.scala<br />
def serialize(string: String) = string.getBytes(&#8220;UTF-8&#8243;)<br />
def deserialize(bytes: Array[Byte]) = new String(bytes, &#8220;UTF-8&#8243;)</p>
<p>// [... test code unchanged ...]<br />
[/scala]</p>
<p>Running this example succeeds, even with the default encoding set to <code>MacRoman</code>. But these little interactions showed us that serializing a string to an array of bytes may not be as easy as originally expected. Are there any other strings that fail to serialize and deserialize? And how can we find these?</p>
<p>Fortunately, there is a powerful tool available for this: <a href="http://code.google.com/p/scalacheck/">ScalaCheck</a>. ScalaCheck generates random test examples and uses these to test programmer specified <em>propositions</em>. This sounds more complicated than it is in practice. So let&#8217;s try an example:</p>
<p>[scala]<br />
// try3.scala<br />
import org.scalacheck._</p>
<p>def serialize(string: String) = string.getBytes(&#8220;UTF-8&#8243;)<br />
def deserialize(bytes: Array[Byte]) = new String(bytes, &#8220;UTF-8&#8243;)</p>
<p>val prop_serializes_all_strings = Prop.forAll { s: String =><br />
  s == deserialize(serialize(s))<br />
}</p>
<p>prop_serializes_all_strings.check<br />
[/scala]</p>
<p>Here we reuse the same string serialization code from the previous example, but instead of manually thinking of examples to test we use ScalaCheck&#8217;s <code>Prop.forAll</code> method to create a proposition. You can basically read lines 7 to 9 as: &#8220;For all strings <em>s</em>, <em>s</em> must be equal to the result of serializing and deserializing <em>s</em>&#8220;. On the last line we tell ScalaCheck to <em>check</em> this proposition. ScalaCheck does so by generating random strings and passing these to our proposition. Download the ScalaCheck <a href="http://code.google.com/p/scalacheck/downloads/detail?name=scalacheck_2.8.1-1.8.jar&amp;can=2&amp;q=">jar</a> and try it:</p>
<p>[bash]<br />
$ scala -cp scalacheck_2.8.1-1.8.jar try3.scala<br />
! Falsified after 15 passed tests.<br />
> ARG_0: ?<br />
[/bash]</p>
<p>Not good. It only took 15 tries for ScalaCheck to find a counter example, which ScalaCheck prints on line 3 above. Unfortunately, due to the limits of current font technology unknown characters are not clearly printed. So we know there is at least one counter example, but we do not know yet what it is.</p>
<p>To help us with this, ScalaCheck allows us to label a test case. Labeling our proposition with the integral values of the string contents should provide us with more information:</p>
<p>[scala]<br />
// try4.scala<br />
import org.scalacheck._, Prop._</p>
<p>def serialize(string: String) = string.getBytes(&#8220;UTF-8&#8243;)<br />
def deserialize(bytes: Array[Byte]) = new String(bytes, &#8220;UTF-8&#8243;)</p>
<p>def decode(string: String) = &#8220;characters = &#8221; + string.map(_.toInt).mkString(&#8220;,&#8221;)</p>
<p>val prop_serializes_all_strings = Prop.forAll { s: String =><br />
  decode(s) |: s == deserialize(serialize(s))<br />
}</p>
<p>prop_serializes_all_strings.check<br />
[/scala]</p>
<p>Here an invocation to the new function <code>decode</code> (line 7) is added as a label to the <code>prop_serializes_all_strings</code> proposition using the ScalaCheck provided <code>|:</code> operator (line 10).</p>
<p>Running this version a couple of times gives us some ideas about what is going wrong:</p>
<p>[bash]<br />
$ scala -cp scalacheck_2.8.1-1.8.jar deser4.scala<br />
! Falsified after 11 passed tests.<br />
> Labels of failing property:<br />
characters = 56465<br />
> ARG_0: ?<br />
[/bash]</p>
<p>It turns out our proposition fails for strings containing characters in the range \uD800 \uDFFF. Looking at the <a href="http://www.unicode.org/charts/">Unicode reference</a> it turns out these are the leading- and trailing-surrogate ranges defined for UTF-16 encoding. And Java Strings use UTF-16 encoding internally. So it looks like ScalaCheck generates Strings that are not valid UTF-16 Unicode strings, and java.lang.String happily accepts them. [NOTE: ScalaCheck 1.9 no longer generates strings containing leading- and trailing-surrogates. So Strings will never contain characters from the Supplementary Planes, but at least all generated strings are valid UTF-16.]</p>
<p>In our case, we&#8217;re only interested in serializing valid Unicode strings. But since we should never silently corrupt data, it would be better to fail with an exception when an illegal string is passed to our serialize implementation. The Java String class does not provide a method for this, so we have to use a <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html">CharsetEncoder</a> instead.</p>
<p>Unfortunately, this requires digging into some of the lower-level APIs provided by Java NIO. Here&#8217;s the end result:</p>
<p>[scala]<br />
import java.nio.{ByteBuffer, CharBuffer}<br />
import java.nio.charset.Charset<br />
import org.scalacheck._, Prop._</p>
<p>def encoder = Charset.forName(&#8220;UTF-8&#8243;).newEncoder<br />
def decoder = Charset.forName(&#8220;UTF-8&#8243;).newDecoder</p>
<p>def serialize(string: String) = {<br />
  val bytes = encoder.encode(CharBuffer.wrap(string))<br />
  bytes.array.slice(bytes.position, bytes.limit)<br />
}<br />
def deserialize(bytes: Array[Byte]) = decoder.decode(ByteBuffer.wrap(bytes)).toString</p>
<p>def decode(string: String) = &#8220;characters = &#8221; + string.map(_.toInt).mkString(&#8220;,&#8221;)</p>
<p>val prop_serializes_all_strings = Prop.forAll { s: String =><br />
  encoder.canEncode(s) ==> (decode(s) |: s == deserialize(serialize(s)))<br />
}</p>
<p>prop_serializes_all_strings.check<br />
[/scala]</p>
<p>The serialization code has been changed to directly use the Charset encoder and decoder and the proposition is changed to include a <em>guard condition</em> using the ScalaCheck <code>==></code> operator: the proposition only holds for strings that can be encoded. Let&#8217;s run this:</p>
<p>[bash]<br />
$ scala -cp scalacheck_2.8.1-1.8.jar try5.scala<br />
+ OK, passed 100 tests.<br />
[/bash]</p>
<p>Finally, success! Well, mostly. Occassionally ScalaCheck will fail:</p>
<p>[bash]<br />
$ scala -Dfile.encoding=UTF-8 -cp scalacheck_2.8.1-1.8.jar try5.scala<br />
! Gave up after only 98 passed tests. 500 tests were discarded.<br />
[/bash]</p>
<p>This happens because our guard condition discards strings which cannot be encoded. By default, ScalaCheck will try to generated 100 passing examples, but will not discard more than 500 examples when trying to achieve this. One way to fix this is to add some parameters to the <code>check</code> invocation:</p>
<p>[scala]<br />
prop_serializes_all_strings.check(Test.Params(minSuccessfulTests = 50, maxDiscardedTests = 1000))<br />
[/scala]</p>
<p>Now it becomes very unlikely that ScalaCheck fails to find enough successful tests.</p>
<p>Another approach is to define a custom <a href="http://code.google.com/p/scalacheck/wiki/UserGuide#Generators">generator</a> that only generates valid Unicode strings. Generating valid UTF-16 Unicode strings is a little tricky, so the code is a bit long:</p>
<p>[scala]<br />
// [... imports same as before ...]</p>
<p>val UnicodeLeadingSurrogate = &#8216;\uD800&#8242; to &#8216;\uDBFF&#8217;<br />
val UnicodeTrailingSurrogate = &#8216;\uDC00&#8242; to &#8216;\uDFFF&#8217;<br />
val UnicodeBasicMultilingualPlane = (&#8216;\u0000&#8242; to &#8216;\uFFFF&#8217;).diff(UnicodeLeadingSurrogate).diff(UnicodeTrailingSurrogate)</p>
<p>val unicodeCharacterBasicMultilingualPlane: Gen[String] = Gen.oneOf(UnicodeBasicMultilingualPlane).map(_.toString)<br />
val unicodeCharacterSupplementaryPlane: Gen[String] = for {<br />
  c1 <- Gen.oneOf(UnicodeLeadingSurrogate)<br />
  c2 <- Gen.oneOf(UnicodeTrailingSurrogate)<br />
} yield {<br />
  c1.toString + c2.toString<br />
}</p>
<p>val unicodeCharacter = Gen.frequency(<br />
  9 -> unicodeCharacterBasicMultilingualPlane,<br />
  1 -> unicodeCharacterSupplementaryPlane)</p>
<p>val unicodeString = Gen.listOf(unicodeCharacter).map(_.mkString)</p>
<p>// [... serialization code same as before ...]</p>
<p>val prop_serializes_all_strings = Prop.forAll(unicodeString) { s: String =><br />
  decode(s) |: s == deserialize(serialize(s))<br />
}</p>
<p>prop_serializes_all_strings.check<br />
[/scala]</p>
<p>On lines 3-5 we define three character collections that will be used to construct correct Unicode data.</p>
<p>On line 7 we define a generator for generating a single Unicode character from the <a href="http://en.wikipedia.org/wiki/Plane_(Unicode)">Basic Multilingual Plane</a> (BMP). It basically picks a random element from the <code>UnicodeBasicMultilingualPlane</code> collection and converts it into a (single character) String.</p>
<p>Lines 8-12 define a generator for Unicode characters from the supplementary planes. It generates a two character string with the first character taken from the leading surrogate range and the second character taken from the trailing surrogate range. The code uses a <a href="http://stackoverflow.com/questions/1385931/scalas-for-comprehensions-vital-feature-or-syntactic-sugar">for-comprehension</a> since generators are allowed to fail (but in our case will never do so).</p>
<p>Lines 14-16 combines these two generators to produce a new generator that generates a BMP character 9 times out of 10, and a supplementary plane character otherwise.</p>
<p>Finally, line 18 uses the previous generator to create a list of random but valid Unicode characters and concatenates this list into a single string. This is the generator we want to use in our proposition. This is shown on lines 22 to 24. Instead of guarding our proposition we now explicitly pass in the generator to use in our call to <code>Prop.forAll</code>. Our proposition now passes without needing to discard any examples, so we can remove the <code>check</code> parameters.</p>
<h2>Conclusion</h2>
<p>With traditional unit tests it is hard to come up with good data that actually exposes bugs, especially the unexpected kind of bugs that only seem to creep up in production. Using ScalaCheck we can let the computer come up with random data to test our code. ScalaCheck includes standard generators for the usual suspects such as Int, String, etc. It&#8217;s also easy to add and use custom generators for existing or new data types.</p>
<p>ScalaCheck is not a replacement for traditional tests. Explicit examples are still useful as documentation and we should also add a test to the above code to ensure an exception is thrown when we try to serialize a String that is not valid Unicode, as our proposition only tests the behavior for valid Strings. But ScalaCheck based testing can help us find those unexpected bugs (really, the most common kind) before they get into production code. Trying to find the silent corruption bug of the first few serialization attempts would be a lot harder in a production environment.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2011%2F04%2F07%2Fserializing-strings-unicode-and-randomized-testing-using-scalacheck%2F&amp;title=Serializing%20strings%2C%20Unicode%2C%20and%20randomized%20testing%20using%20ScalaCheck" id="wpa2a_14"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2011/04/07/serializing-strings-unicode-and-randomized-testing-using-scalacheck/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting started with Ruby on Rails</title>
		<link>http://blog.zilverline.com/2011/03/28/getting-started-with-ruby-on-rails/</link>
		<comments>http://blog.zilverline.com/2011/03/28/getting-started-with-ruby-on-rails/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 13:54:29 +0000</pubDate>
		<dc:creator>Sander Nieuwenhuizen</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=503</guid>
		<description><![CDATA[I&#8217;ve been coding in Ruby on Rails for the past couple of months. It was a fun and sometimes tough journey (and still is sometimes) learning a new language and platform. My main background is Java, but last year I was fed up with that. It was too hard to do simple stuff. I reckoned <a href='http://blog.zilverline.com/2011/03/28/getting-started-with-ruby-on-rails/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been coding in Ruby on Rails for the past couple of months. It was a fun and sometimes tough journey (and still is sometimes) learning a new language and platform. My main background is Java, but last year I was fed up with that. It was too hard to do simple stuff. I reckoned that there should be an easier way. Plus, learning a new language broadens your vision and it helped me to improve my programming skills. This blog post is the first of a series (probably, if there&#8217;s enough interest) towards implementing a Rails application. I&#8217;d like to give you a heads up of what I discovered head first.<br />
<span id="more-503"></span></p>
<p>In this first post I&#8217;ll introduce you how to setup your machine to be able to rock some Rails code.</p>
<h2>1. Rubies please</h2>
<p>Instructions how to get Ruby for your environment you can find <a href="http://www.ruby-lang.org/en/downloads/">here</a>. On a Mac it is installed by default. You can easily find it out by executing the &#8216;ruby&#8217; command in your shell and see what happens.</p>
<p><img class="aligncenter size-full wp-image-509" title="ruby -v" src="http://blog.zilverline.com/wp-content/uploads/2011/03/ruby-version.png" alt="" width="554" height="46" /></p>
<p style="text-align: center;">&nbsp;</p>
<p>No worries if this isn&#8217;t the latest version available. We will only use it to get you bootstrapped.</p>
<h2>2. RVM</h2>
<p><a href="http://rvm.beginrescueend.com/">RVM</a> (Ruby Version Manager) is a tool to help you to be able to use multiple Ruby environments on one machine. If you have multiple Ruby projects on your machine it is quite handy to be able to let them run in their own (sort of) sandbox. Simply put: if you don&#8217;t use RVM all dependencies (gems) will be installed system-wide. You just don&#8217;t want that as things will get messy. Given you have successfully installed Ruby, you will now install RVM. This short installation step summary requires you having git installed. If not you can view the full installation guide <a href="http://rvm.beginrescueend.com/rvm/install/">here</a>.</p>
<pre>$ bash &lt; &lt;(curl -s https://rvm.beginrescueend.com/install/rvm)</pre>
<p>Edit your ~/.bash_profile to contain the following:</p>
<pre>[[ -s "$HOME/.rvm/scripts/rvm" ]] &amp;&amp; . "$HOME/.rvm/scripts/rvm"</pre>
<p>Now start a new shell and you should be able to perform something like</p>
<pre>$ type rvm | head -1</pre>
<p>This should give you</p>
<pre>rvm is a function</pre>
<p>Next, and last step, execute</p>
<pre>rvm notes</pre>
<p>This gives you an overview of what to do next for your environment. On a Mac, be sure to have the right XCode version installed as said in the output.</p>
<p><strong>Now what did this do?</strong><br />
You got the version manager tool installed, but what about the bash_profile stuff? What this small line does is making the rvm command available on your PATH. Handy, you can now run it anywhere you go. Also, it helps you to switch environments easily when navigating through different Ruby projects. We&#8217;ll get into that later. Moving along to the next step&#8230;</p>
<h2>3. Install Ruby within RVM &#8211; creating your first RVM environment</h2>
<p>Let&#8217;s install the latest Ruby version within RVM:</p>
<pre>$ rvm install 1.9.2-p180</pre>
<p>This is the latest version at the time of writing. You can go <a href="http://www.ruby-lang.org/en/downloads/" target="_blank">here</a> to verify if there exists a newer version.<br />
If you run</p>
<pre>$ rvm use 1.9.2</pre>
<pre>$ which ruby</pre>
<p>you should get something similar to the following output:<br />
<img src="http://blog.zilverline.com/wp-content/uploads/2011/03/rvm-use-1.9.2-which.png" alt="" title="rvm-use-1.9.2-which" width="405" height="78" class="aligncenter size-full wp-image-537" /></p>
<p><strong>So&#8230;</strong></p>
<p>From now on, all the dependencies or Ruby versions you will install will be placed in the RVM folder that&#8217;s located in your home folder. If you install stand alone gems (equivalent of JARs) or upgrade dependencies this will only affect the currently used Ruby installation stored in your home folder. If you mess up, there&#8217;s nothing to worry about <img src='http://blog.zilverline.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>Almost there. Going well so far. You&#8217;ve got the latest and greatest Ruby version within RVM. You&#8217;re almost ready to rock&#8230;</p>
<h2>4. Install Rails and create your first application</h2>
<p>Rails is a web framework for Ruby. Install it by running</p>
<pre>$ gem install rails</pre>
<p><strong>Create a new application</strong></p>
<pre>$ rails new example</pre>
<p>This will create a new folder containing your first Rails application. Plus it has created a lot of stuff for you. It&#8217;s out of scope of this post to cover fully what happened. Just remember this generated a skeleton and a kick start for your first application.</p>
<h2>5. Bundler (Maven for Ruby)</h2>
<p>Bundler helps you to maintain dependencies similar as what Maven does for Java. You cannot start the example application without retrieving the required dependencies. Retrieve the dependencies by:</p>
<pre>
  $ cd example
  $ bundle install
</pre>
<h2>6. Rock and roll</h2>
<p>Your first application is there! It might have been a boring road with nothing much to see. But&#8230; you&#8217;ve got an application that is ready to start. Give it a kick by</p>
<pre>$ rails server</pre>
<p>Now open a browser pointing to <a href="http://localhost:3000" target="_blank">http://localhost:3000</a>. You should see this screen:<br />
<a href="http://blog.zilverline.com/wp-content/uploads/2011/03/rails-server.png"><img src="http://blog.zilverline.com/wp-content/uploads/2011/03/rails-server-300x216.png" alt="" title="rails-server" width="300" height="216" class="aligncenter size-medium wp-image-540" /></a></p>
<h2>Wrapup</h2>
<p>Setting up development environments isn&#8217;t the most fun you can have. But doing the above gives you enormous flexibility. By using RVM instead of installing everything system wide makes it easy to switch Ruby versions, be flexible with the dependencies &#8211; and not be surprised by versioning issues over different projects. There&#8217;s more to RVM than described above, but this is enough to give you a heads up.</p>
<p>If you like this to be the first of a series, please let me know!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2011%2F03%2F28%2Fgetting-started-with-ruby-on-rails%2F&amp;title=Getting%20started%20with%20Ruby%20on%20Rails" id="wpa2a_16"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2011/03/28/getting-started-with-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lightweight code review reports</title>
		<link>http://blog.zilverline.com/2011/03/22/lightweight-code-review-reports/</link>
		<comments>http://blog.zilverline.com/2011/03/22/lightweight-code-review-reports/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 20:43:13 +0000</pubDate>
		<dc:creator>Lars Vonk</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Scrum]]></category>
		<category><![CDATA[a3]]></category>
		<category><![CDATA[code review]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=456</guid>
		<description><![CDATA[Recently I conducted a code review for one of our customers. They already are using A3 reports internally as problem solving and report tool. I really like A3, so I thought why not try if a code review fits in a A3 report. A lot of code reviews I come across are wordy documents basically <a href='http://blog.zilverline.com/2011/03/22/lightweight-code-review-reports/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Recently I conducted a code review for one of our customers. They already are using <a href="http://www.coe.montana.edu/ie/faculty/sobek/a3/report.htm">A3</a> reports internally as problem solving and report tool. I really like A3, so I thought why not try if a code review fits in a A3 report.<br />
<span id="more-456"></span><br />
A lot of code reviews I come across are wordy documents basically copy-pasting the reports of what tools like sonar provide to you for free. In all the teams I know or coached such tools are already available so there is really now need anymore to put that kind of information in a code review report (providing a link should be sufficient).</p>
<p>I think a code review report should be concise, clear and with concrete actions on how to improve. Since these are also characteristics of an A3, let&#8217;s see how they fit together.</p>
<p>A typical A3 consists of the following steps<sup>1</sup>:</p>
<p>1. Identify problem<br />
2. Research<br />
3. Root cause analysis<br />
4. Propose counter measures<br />
5. Develop target state<br />
6. Create implementation plan<br />
7. Develop follow-up plan with predicted outcome</p>
<p>Since A3 is a problem solving tool it doesn&#8217;t map 1-to-1 to a code review. The nature of a code review is different then a problem solving process (the code review could be <i>input</i> for a real A3 though).<br />
Some parts can be used, so I mapped this to a code review as follows:</p>
<p><img src="/wp-content/uploads/2011/03/code-review.jpg" width="650px" height="488px"></p>
<p>This will give you the report in a nice and concise format.</p>
<p>Then starts the next and probably important part of the code review: <u>The follow up</u>. This means discuss the review with your client and the team members. Come up with an <b>implementation and follow-up plan</b> together with the team.</p>
<p>Happy code reviewing! </p>
<blockquote><p>
1. http://www.coe.montana.edu/ie/faculty/sobek/a3/steps.htm
</p></blockquote>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2011%2F03%2F22%2Flightweight-code-review-reports%2F&amp;title=Lightweight%20code%20review%20reports" id="wpa2a_18"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2011/03/22/lightweight-code-review-reports/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Towards an immutable domain model &#8211; monads (part 5)</title>
		<link>http://blog.zilverline.com/2011/02/10/towards-an-immutable-domain-model-monads-part-5/</link>
		<comments>http://blog.zilverline.com/2011/02/10/towards-an-immutable-domain-model-monads-part-5/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 08:23:19 +0000</pubDate>
		<dc:creator>Erik Rozendaal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[domain driven design]]></category>
		<category><![CDATA[event sourcing]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[immutability]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.zilverline.com/?p=348</guid>
		<description><![CDATA[This is the fifth and final part of this series. The previous parts consist of: a not totally trivial example implemented using JPA and Scala an event sourced implementation using explicit state changes a straightforward translation of the mutable event sourced implementation into an immutable implementation encoding domain knowledge into the type system to make <a href='http://blog.zilverline.com/2011/02/10/towards-an-immutable-domain-model-monads-part-5/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>This is the fifth and final part of this series. The previous parts consist of:</p>
<ol>
<li>a not totally trivial <a href="http://blog.zilverline.com/2011/02/01/towards-an-immutable-domain-model-introduction-part-1/">example implemented using JPA and Scala</a></li>
<li>an <a href="http://blog.zilverline.com/2011/02/02/towards-an-immutable-domain-model-–-immutable-change-part-2/">event sourced implementation</a> using explicit state changes</li>
<li><a href="http://blog.zilverline.com/2011/02/05/towards-an-immutable-domain-model-immutability-achieved-part-3/">a straightforward translation</a> of the mutable event sourced implementation into an immutable implementation</li>
<li><a href="http://blog.zilverline.com/2011/02/07/towards-an-immutable-domain-model-–-believe-the-type-part-4/">encoding domain knowledge into the type system</a> to make the domain easier to understand and reduce the number of runtime error checks</li>
</ol>
<p>In this last part we&#8217;ll reduce the boilerplate code related to handling events and as a bonus we&#8217;ll also make handling validation a bit nicer. But before we take a deep dive into the code, let&#8217;s consider the design of the last three Invoice implementations.<br />
<span id="more-348"></span></p>
<h2>Design comparison</h2>
<p>Since this part is mostly about reducing boilerplate from the typed implemention of invoice without significantly affecting the design of our domain classes, it makes sense to take a quick look at the design of the three event sourced implementations so far: mutable (part 2), immutable (part 3), and typed/monadic (part 4/5). Which one, if any, is the &#8220;best&#8221;? Let&#8217;s compare them based on <a href="http://c2.com/cgi/wiki?XpSimplicityRules">XP&#8217;s rules of simple design</a>.</p>
<table>
<thead>
<tr>
<th>Rule</th>
<th>Mutable</th>
<th>Immutable</th>
<th>Typed / Monadic</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pass all tests</td>
<td>++</td>
<td>++</td>
<td>++</td>
</tr>
<tr>
<td>Clear, expressive, &amp; consistent</td>
<td>+</td>
<td>+</td>
<td>++</td>
</tr>
<tr>
<td>No duplication</td>
<td>-</td>
<td>-</td>
<td>+</td>
</tr>
<tr>
<td>Minimal methods, classes</td>
<td>+</td>
<td>+</td>
<td>-/+</td>
</tr>
</tbody>
</table>
<p>So all implementations pass the tests and therefore satisfy the requirements. Splitting the invoice class into three subclasses improved expressiveness and reduced duplication (no need for some runtime checks), at the cost of adding some new methods and classes.</p>
<p>But the main highlight is that we were able to <em>radically redesign and reimplement</em> our domain code with <em>minimal</em> impact on our clients or infrastructure. We still generate exactly the same events as in the first mutable event sourced implementation and only the calling syntax was slightly changed (which usually is contained in a controller or service layer anyway). The reporting side of the application, any views, integration with external systems, etc. are unaffected! </p>
<p>So by having our events as a <a href="http://www.objectmentor.com/resources/articles/stability.pdf">stable abstraction</a> we have greatly decoupled the components of our application while making each component <em>more cohesive</em>. This gives us confidence that as requirements change we can keep our domain clean and simple, without needing to compromise our implementation with respect to durability or reporting needs.</p>
<p>So now that we have this out of the way, let&#8217;s get back into the code.</p>
<h2>Composing event handlers</h2>
<p>Let&#8217;s take a look at the <code>applyEvent</code> method in the <code>DraftInvoice</code> class from part 4:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">def</span> <span class="n">applyEvent</span> <span class="k">=</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">case</span> <span class="n">event</span><span class="k">:</span> <span class="kt">InvoiceRecipientChanged</span> <span class="o">=&gt;</span> <span class="n">applyRecipientChanged</span><span class="o">(</span><span class="n">event</span><span class="o">)</span></div><div class='line' id='LC3'>&nbsp;&nbsp;<span class="k">case</span> <span class="n">event</span><span class="k">:</span> <span class="kt">InvoiceItemAdded</span> <span class="o">=&gt;</span> <span class="n">applyItemAdded</span><span class="o">(</span><span class="n">event</span><span class="o">)</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="k">case</span> <span class="n">event</span><span class="k">:</span> <span class="kt">InvoiceItemRemoved</span> <span class="o">=&gt;</span> <span class="n">applyItemRemoved</span><span class="o">(</span><span class="n">event</span><span class="o">)</span></div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="k">case</span> <span class="n">event</span><span class="k">:</span> <span class="kt">InvoiceSent</span> <span class="o">=&gt;</span> <span class="n">applySent</span><span class="o">(</span><span class="n">event</span><span class="o">)</span></div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="k">case</span> <span class="n">event</span> <span class="k">=&gt;</span> <span class="n">unhandled</span><span class="o">(</span><span class="n">event</span><span class="o">)</span></div><div class='line' id='LC7'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/fb2bada0980ccc973b36d2b83fed15d6d14c7f4d/DraftInvoiceApplyEvent1.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_draft_invoice_apply_event1.scala" style="float:right;margin-right:10px;color:#666">DraftInvoiceApplyEvent1.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>It&#8217;s basically checking the type of the event and then dispatching to the correct event handler using a case-block. Each event handler is simply a function that takes an event of the correct type and returns the appropriate response. We could try to use some reflection magic to remove the need for this method, but that feels like cheating. Let&#8217;s try to if we can <em>compose</em> our typed event handlers into the generic <code>applyEvent</code> method instead.</p>
<p>Fortunately, Scala has a built-in trait called <a href="http://www.scala-lang.org/api/current/scala/PartialFunction.html"><code>PartialFunction</code></a> that has the useful method <code>orElse</code> that does exactly what we need. We just need to turn our event handling functions into partial functions to make this work.</p>
<p>We do this by making the type of our handlers explicit using a new class <code>EventHandler</code> and adding an <em>implicit</em> conversion from our handler type to partial functions. The partial function checks the event&#8217;s type and invoke the handler if the type is correct:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">protected</span> <span class="k">class</span> <span class="nc">EventHandler</span><span class="o">[</span><span class="kt">Event</span>, <span class="kt">+Result</span><span class="o">](</span><span class="n">callback</span><span class="k">:</span> <span class="kt">Event</span> <span class="o">=&gt;</span> <span class="nc">Result</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">event</span><span class="k">:</span> <span class="kt">Event</span><span class="o">)</span> <span class="k">=</span> <span class="c1">// [... code omitted ...]</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">applyFromHistory</span><span class="o">(</span><span class="n">event</span><span class="k">:</span> <span class="kt">Event</span><span class="o">)</span> <span class="k">=</span> <span class="n">callback</span><span class="o">(</span><span class="n">event</span><span class="o">)</span></div><div class='line' id='LC5'><span class="o">}</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="k">protected</span> <span class="k">def</span> <span class="n">handler</span><span class="o">[</span><span class="kt">A</span>, <span class="kt">B</span><span class="o">](</span><span class="n">callback</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="n">B</span><span class="o">)</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">EventHandler</span><span class="o">(</span><span class="n">callback</span><span class="o">)</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="k">implicit</span> <span class="k">protected</span> <span class="k">def</span> <span class="n">handlerToPartialFunction</span><span class="o">[</span><span class="kt">A</span>, <span class="kt">B</span><span class="o">](</span><span class="n">handler</span><span class="k">:</span> <span class="kt">EventHandler</span><span class="o">[</span><span class="kt">A</span>, <span class="kt">B</span><span class="o">])(</span><span class="k">implicit</span> <span class="n">m</span><span class="k">:</span> <span class="kt">Manifest</span><span class="o">[</span><span class="kt">A</span><span class="o">])</span> <span class="k">=</span></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="k">new</span> <span class="nc">PartialFunction</span><span class="o">[</span><span class="kt">AnyRef</span>, <span class="kt">B</span><span class="o">]</span> <span class="o">{</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">def</span> <span class="n">isDefinedAt</span><span class="o">(</span><span class="n">event</span><span class="k">:</span> <span class="kt">AnyRef</span><span class="o">)</span> <span class="k">=</span> <span class="n">m</span><span class="o">.</span><span class="n">erasure</span><span class="o">.</span><span class="n">isInstance</span><span class="o">(</span><span class="n">event</span><span class="o">)</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">event</span><span class="k">:</span> <span class="kt">AnyRef</span><span class="o">)</span> <span class="k">=</span> <span class="n">handler</span><span class="o">.</span><span class="n">applyFromHistory</span><span class="o">(</span><span class="n">event</span><span class="o">.</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">A</span><span class="o">])</span></div><div class='line' id='LC14'>&nbsp;&nbsp;<span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/84f690477caf9d2efb5c66bbe03fbfee853588dc/HandlerPF1.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_handler_pf1.scala" style="float:right;margin-right:10px;color:#666">HandlerPF1.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Here an instance of <code>EventHandler</code> can be created using the <code>handler</code> method. The <code>EventHandler</code> class has a <code>applyFromHistory</code> method which simply passes the event to the provided callback.</p>
<p>The <code>handlerToPartialFunction</code> takes an <code>EventHandler</code> and an implicit <a href="http://stackoverflow.com/questions/3587286/how-does-scalas-2-8-manifest-work#3588191">Manifest</a> and turns it into a partial function that takes an event of type <code>AnyRef</code> (Scala&#8217;s equivalent of Java&#8217;s <code>Object</code> class). When the partial function is invoked it downcasts the event and delegates to the <code>EventHandler</code>&#8216;s <code>applyFromHistory</code> method. But the partial function is only defined when the provided event&#8217;s type matches the type expected by the event handler!</p>
<p>Using these definitions we can now update our typed event handlers and easily compose them for use with <code>applyEvent</code>, using the standard <code>PartialFunction.orElse</code> method:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">def</span> <span class="n">applyEvent</span> <span class="k">=</span> <span class="n">applyRecipientChanged</span> <span class="n">orElse</span> <span class="n">applyItemAdded</span> <span class="n">orElse</span> <span class="n">applyItemRemoved</span> <span class="n">orElse</span> <span class="n">applySent</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="k">private</span> <span class="k">def</span> <span class="n">applyRecipientChanged</span> <span class="k">=</span> <span class="n">handler</span> <span class="o">{</span><span class="n">event</span><span class="k">:</span> <span class="kt">InvoiceRecipientChanged</span> <span class="o">=&gt;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="n">copy</span><span class="o">(</span><span class="n">event</span> <span class="o">::</span> <span class="n">uncommittedEvents</span><span class="o">,</span> <span class="n">recipient_?</span> <span class="k">=</span> <span class="n">event</span><span class="o">.</span><span class="n">recipient</span><span class="o">.</span><span class="n">isDefined</span><span class="o">)</span></div><div class='line' id='LC5'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/cebc5c252b595666757a3f495aeaa6184313213f/DraftInvoiceApplyEvent2.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_draft_invoice_apply_event2.scala" style="float:right;margin-right:10px;color:#666">DraftInvoiceApplyEvent2.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Now the <code>applyEvent</code> method is just a single line listing all the applicable event handlers, without all the boilerplate. The typed event handlers are slightly changed to include the call to the <code>handler</code> factory method.</p>
<h2>Extracting uncommitted events</h2>
<p>The other part of boilerplate code was related to storing and managing the list of uncommitted events. Each aggregate root subclass needed to provide an accessor for the <code>uncommittedEvent</code> field and implement the <code>markCommitted</code> method. Each event handler then had to ensure the new event was prepended to the list of uncommitted event, which is somewhat error-prone. </p>
<p>The first step to fixing this is to remove the list of uncommitted events from the aggregate root and to start explicitly passing it into our methods, which then returns the updated list together with the updated invoice. This will certainly clean up the invoice subclasses, such as the <code>PaidInvoice</code> listed below. </p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">class</span> <span class="nc">PaidInvoice</span> <span class="k">extends</span> <span class="nc">Invoice</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">applyEvent</span> <span class="k">=</span> <span class="n">unhandled</span></div><div class='line' id='LC3'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/5a0ae6b42f4976bd53430834bcee2516e28306c7/PaidInvoice.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_paid_invoice.scala" style="float:right;margin-right:10px;color:#666">PaidInvoice.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Unfortunately it makes methods like <code>pay</code> and <code>applyPaymentReceived</code> rather ugly, and we&#8217;re not even talking yet about the client code which now needs to manually manage the list of uncommitted events:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">def</span> <span class="n">pay</span><span class="o">(</span><span class="n">uncommittedEvents</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">Any</span><span class="o">])</span> <span class="k">=</span> </div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="n">applyPaymentReceived</span><span class="o">(</span><span class="nc">InvoicePaymentReceived</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="k">new</span> <span class="nc">LocalDate</span><span class="o">),</span> <span class="n">uncommittedEvents</span><span class="o">)</span></div><div class='line' id='LC3'>&nbsp;&nbsp;</div><div class='line' id='LC4'><span class="k">private</span> <span class="k">def</span> <span class="n">applyPaymentReceived</span><span class="o">(</span><span class="n">event</span><span class="k">:</span> <span class="kt">InvoicePaymentReceived</span><span class="o">,</span> <span class="n">uncommittedEvents</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">Any</span><span class="o">])</span> <span class="k">=</span></div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="o">(</span><span class="n">event</span> <span class="o">::</span> <span class="n">uncommittedEvents</span><span class="o">,</span> <span class="k">new</span> <span class="nc">PaidInvoice</span><span class="o">)</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/6ebc5b28067420b9c1e55b1abf9dabbeecf9f32f/ExplicitPassing.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_explicit_passing.scala" style="float:right;margin-right:10px;color:#666">ExplicitPassing.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Fortunately, <a href="http://www.codecommit.com/blog/ruby/monads-are-not-metaphors">monads</a> can help us with that. But first we&#8217;ll make our types explicit (a recurring theme of this series).</p>
<p>Let&#8217;s look at the types we have now. The <code>pay</code> method above has the type <code>List[Any] =&gt; (List[Any], PaidInvoice)</code>. Let&#8217;s call the type of <code>pay</code> a <code>Behavior</code> which returns a <code>Reaction</code> when triggered by passing it a list of events. A reaction can either be <code>Accepted</code> for success or <code>Rejected</code> when failed:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">trait</span> <span class="nc">Reaction</span><span class="o">[</span><span class="kt">+T</span><span class="o">]</span></div><div class='line' id='LC2'><span class="nc">case</span> <span class="k">class</span> <span class="nc">Accepted</span><span class="o">[</span><span class="kt">+T</span><span class="o">](</span><span class="n">events</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">Any</span><span class="o">],</span> <span class="n">result</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Reaction</span><span class="o">[</span><span class="kt">T</span><span class="o">]</span></div><div class='line' id='LC3'><span class="k">case</span> <span class="k">class</span> <span class="nc">Rejected</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Reaction</span><span class="o">[</span><span class="kt">Nothing</span><span class="o">]</span></div><div class='line' id='LC4'><br/></div><div class='line' id='LC5'><span class="k">trait</span> <span class="nc">Behavior</span><span class="o">[</span><span class="kt">+A</span><span class="o">]</span> <span class="o">{</span></div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="k">protected</span> <span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">events</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">Any</span><span class="o">])</span><span class="k">:</span> <span class="kt">Reaction</span><span class="o">[</span><span class="kt">A</span><span class="o">]</span></div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="c1">// [... code omitted ...]</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">reaction</span> <span class="k">=</span> <span class="n">apply</span><span class="o">(</span><span class="nc">Nil</span><span class="o">)</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">changes</span> <span class="k">=</span> <span class="n">reaction</span><span class="o">.</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Accepted</span><span class="o">[</span><span class="k">_</span><span class="o">]].</span><span class="n">events</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">rejected</span> <span class="k">=</span> <span class="n">reaction</span><span class="o">.</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Rejected</span><span class="o">].</span><span class="n">message</span></div><div class='line' id='LC15'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/7fcb4967a304f0550bffd0747c17244c812475e5/BehaviorReaction.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_behavior_reaction.scala" style="float:right;margin-right:10px;color:#666">BehaviorReaction.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The <code>Behavior</code> class defines an abstract method <code>apply</code> that takes the current list of uncommitted events as argument and should implement the specific behavior we want. It also adds a <code>reaction</code> method that invokes the behavior with the empty list. The <code>changes</code> and <code>rejected</code> methods are just there for convenience.</p>
<p>We&#8217;ll also define a few additional methods to create some useful behaviors:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">object</span> <span class="nc">Behaviors</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">behavior</span><span class="o">[</span><span class="kt">T</span><span class="o">](</span><span class="n">callback</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">Any</span><span class="o">]</span> <span class="k">=&gt;</span> <span class="nc">Reaction</span><span class="o">[</span><span class="kt">T</span><span class="o">])</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Behavior</span><span class="o">[</span><span class="kt">T</span><span class="o">]</span> <span class="o">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">protected</span> <span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">events</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">Any</span><span class="o">])</span> <span class="k">=</span> <span class="n">callback</span><span class="o">(</span><span class="n">events</span><span class="o">)</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">accept</span><span class="o">[</span><span class="kt">T</span><span class="o">](</span><span class="n">result</span><span class="k">:</span> <span class="kt">T</span><span class="o">)</span> <span class="k">=</span> <span class="n">behavior</span><span class="o">(</span><span class="n">events</span> <span class="k">=&gt;</span> <span class="nc">Accepted</span><span class="o">(</span><span class="n">events</span><span class="o">,</span> <span class="n">result</span><span class="o">))</span></div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">reject</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">=</span> <span class="n">behavior</span><span class="o">(</span><span class="k">_</span> <span class="k">=&gt;</span> <span class="nc">Rejected</span><span class="o">(</span><span class="n">message</span><span class="o">))</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">record</span><span class="o">(</span><span class="n">event</span><span class="k">:</span> <span class="kt">Any</span><span class="o">)</span> <span class="k">=</span> <span class="n">behavior</span><span class="o">(</span><span class="n">events</span> <span class="k">=&gt;</span> <span class="nc">Accepted</span><span class="o">(</span><span class="n">event</span> <span class="o">::</span> <span class="n">events</span><span class="o">,</span> <span class="o">()))</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">guard</span><span class="o">(</span><span class="n">condition</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">,</span> <span class="n">message</span><span class="k">:</span> <span class="o">=&gt;</span> <span class="nc">String</span><span class="o">)</span> <span class="k">=</span> <span class="k">if</span> <span class="o">(</span><span class="n">condition</span><span class="o">)</span> <span class="n">accept</span><span class="o">()</span> <span class="k">else</span> <span class="n">reject</span><span class="o">(</span><span class="n">message</span><span class="o">)</span></div><div class='line' id='LC13'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/1f9d09391bd544ac45b8a5852359d77a3f8707d4/Behaviors.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_behaviors.scala" style="float:right;margin-right:10px;color:#666">Behaviors.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The <code>behavior</code> method lets us easily create a new behavior by providing a callback, instead of having to define a new anonymous subclass implementation every time. </p>
<p><code>Accept</code> doesn&#8217;t modify the list of uncommitted events but simple returns a specific result, <code>reject</code> forgets about any uncommitted events and returns an error message, <code>record</code> records the provided event and returns an uninteresting value, and <code>guard</code> rejects when the condition does not hold and returns an uninteresting value otherwise.</p>
<p>Now we&#8217;ll just need two more pieces to complete the puzzle. The first thing we need to be able to do is to compose two behaviors into a single new behavior. We do this by first triggering the first behavior, and if successful, passing the result from the first behavior into the second behavior. This is the monad <code>bind</code> operation, which is called <code>flatMap</code> in Scala and we make it part of our <code>Behavior</code> trait:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">trait</span> <span class="nc">Behavior</span><span class="o">[</span><span class="kt">+A</span><span class="o">]</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">protected</span> <span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">events</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">Any</span><span class="o">])</span><span class="k">:</span> <span class="kt">Reaction</span><span class="o">[</span><span class="kt">A</span><span class="o">]</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">flatMap</span><span class="o">[</span><span class="kt">B</span><span class="o">](</span><span class="n">next</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="nc">Behavior</span><span class="o">[</span><span class="kt">B</span><span class="o">])</span> <span class="k">=</span> <span class="n">behavior</span> <span class="o">{</span><span class="n">events</span> <span class="k">=&gt;</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">(</span><span class="n">events</span><span class="o">)</span> <span class="k">match</span> <span class="o">{</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">case</span> <span class="nc">Accepted</span><span class="o">(</span><span class="n">updatedEvents</span><span class="o">,</span> <span class="n">result</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">next</span><span class="o">(</span><span class="n">result</span><span class="o">)(</span><span class="n">updatedEvents</span><span class="o">)</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">case</span> <span class="nc">Rejected</span><span class="o">(</span><span class="n">message</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nc">Rejected</span><span class="o">(</span><span class="n">message</span><span class="o">)</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC9'>&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC10'>&nbsp;&nbsp;</div><div class='line' id='LC11'>&nbsp;&nbsp;<span class="c1">// [... code omitted ...]</span></div><div class='line' id='LC12'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/4a344e080be090170a08354ae56d9c4002ddd783/FlatMap.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_flat_map.scala" style="float:right;margin-right:10px;color:#666">FlatMap.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>With all of this in place, we can define the <code>EventHandler.apply</code> method which is used by our invoice implementation to call event handlers when not reloading from history:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">protected</span> <span class="k">class</span> <span class="nc">EventHandler</span><span class="o">[</span><span class="kt">Event</span>, <span class="kt">+Result</span><span class="o">](</span><span class="n">callback</span><span class="k">:</span> <span class="kt">Event</span> <span class="o">=&gt;</span> <span class="nc">Result</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">event</span><span class="k">:</span> <span class="kt">Event</span><span class="o">)</span> <span class="k">=</span> <span class="n">record</span><span class="o">(</span><span class="n">event</span><span class="o">)</span> <span class="n">flatMap</span> <span class="o">(</span><span class="k">_</span> <span class="k">=&gt;</span> <span class="n">accept</span><span class="o">(</span><span class="n">callback</span><span class="o">(</span><span class="n">event</span><span class="o">)))</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="c1">// [... code omitted ...]</span></div><div class='line' id='LC5'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/b1f67ef03f142647b61298d42b3abee003f6bab0/EventHandlerApply.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_event_handler_apply.scala" style="float:right;margin-right:10px;color:#666">EventHandlerApply.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The <code>apply</code> method simply <em>records</em> the event and then <em>accepts</em> whatever the result of the event handler&#8217;s callback is. The return value of <code>record</code> is ignored, since it is of type <code>Unit</code> and not interesting.</p>
<p>So let&#8217;s take a look at the <code>DraftInvoice.send</code> method of our new <a href="https://github.com/erikrozendaal/immutable-domain-example/blob/master/src/main/scala/com/zilverline/examples/immutabledomain/typedmonadic/Invoice.scala">Invoice.scala</a>:</p>
<div id="gist-817221" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">def</span> <span class="n">send</span><span class="k">:</span> <span class="kt">Behavior</span><span class="o">[</span><span class="kt">SentInvoice</span><span class="o">]</span> <span class="k">=</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="n">guard</span><span class="o">(</span><span class="n">readyToSend_?</span><span class="o">,</span> <span class="s">&quot;recipient and items must be specified before sending&quot;</span><span class="o">)</span> <span class="n">flatMap</span> <span class="o">{</span><span class="k">_</span> <span class="k">=&gt;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">val</span> <span class="n">now</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">LocalDate</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">applySent</span><span class="o">(</span><span class="nc">InvoiceSent</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="n">sentDate</span> <span class="k">=</span> <span class="n">now</span><span class="o">,</span> <span class="n">dueDate</span> <span class="k">=</span> <span class="n">now</span><span class="o">.</span><span class="n">plusDays</span><span class="o">(</span><span class="mi">14</span><span class="o">)))</span></div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="c1">// [... code omitted ...]</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="k">private</span> <span class="k">def</span> <span class="n">applySent</span> <span class="k">=</span> <span class="n">handler</span> <span class="o">{</span><span class="n">event</span><span class="k">:</span> <span class="kt">InvoiceSent</span> <span class="o">=&gt;</span> <span class="k">new</span> <span class="nc">SentInvoice</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="n">event</span><span class="o">.</span><span class="n">dueDate</span><span class="o">)}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/817221/77e07ad76b93769ab7494f783119db57162c5846/DraftInvoiceSend.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/817221#file_draft_invoice_send.scala" style="float:right;margin-right:10px;color:#666">DraftInvoiceSend.scala</a>
            <a href="https://gist.github.com/817221">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>This <code>send</code> method&#8217;s only changes are the return type (<code>Behavior[SentInvoice]</code>) and the use of the <code>guard</code> method to perform validation. Again <code>flatMap</code> is used to sequence the behavior. So if the guard fails the <code>applySent</code> is never performed. The implementation of <code>applySent</code> is now also cleaned up and no longer has to worry about recording the event as this is taken care of by <code>EventHandler.apply</code>.</p>
<p>Client code is now unfortunately a bit more complicated, since it needs to deal with the monad:</p>
<div id="gist-819082" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="s">&quot;draft invoice&quot;</span> <span class="n">should</span> <span class="o">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">val</span> <span class="n">invoice</span><span class="k">:</span> <span class="kt">DraftInvoice</span> <span class="o">=</span> <span class="nc">Invoice</span><span class="o">.</span><span class="n">loadFromHistory</span><span class="o">(</span><span class="nc">Seq</span><span class="o">(</span><span class="nc">InvoiceCreated</span><span class="o">(</span><span class="mi">1</span><span class="o">)))</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="s">&quot;support adding invoice items&quot;</span> <span class="n">in</span> <span class="o">{</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">val</span> <span class="n">updated</span> <span class="k">=</span> <span class="n">invoice</span><span class="o">.</span><span class="n">addItem</span><span class="o">(</span><span class="s">&quot;Food&quot;</span><span class="o">,</span> <span class="s">&quot;2.95&quot;</span><span class="o">)</span> <span class="n">flatMap</span> <span class="o">(</span><span class="k">_</span><span class="o">.</span><span class="n">addItem</span><span class="o">(</span><span class="s">&quot;Water&quot;</span><span class="o">,</span> <span class="s">&quot;1.95&quot;</span><span class="o">))</span> <span class="n">flatMap</span> <span class="o">(</span><span class="k">_</span><span class="o">.</span><span class="n">removeItem</span><span class="o">(</span><span class="mi">1</span><span class="o">))</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">updated</span><span class="o">.</span><span class="n">changes</span> <span class="n">must</span> <span class="n">contain</span><span class="o">(</span><span class="nc">InvoiceItemAdded</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="nc">InvoiceItem</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="s">&quot;Food&quot;</span><span class="o">,</span> <span class="s">&quot;2.95&quot;</span><span class="o">),</span> <span class="s">&quot;2.95&quot;</span><span class="o">))</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">updated</span><span class="o">.</span><span class="n">changes</span> <span class="n">must</span> <span class="n">contain</span><span class="o">(</span><span class="nc">InvoiceItemAdded</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="nc">InvoiceItem</span><span class="o">(</span><span class="mi">2</span><span class="o">,</span> <span class="s">&quot;Water&quot;</span><span class="o">,</span> <span class="s">&quot;1.95&quot;</span><span class="o">),</span> <span class="s">&quot;4.90&quot;</span><span class="o">))</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">updated</span><span class="o">.</span><span class="n">changes</span> <span class="n">must</span> <span class="n">contain</span><span class="o">(</span><span class="nc">InvoiceItemRemoved</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="nc">InvoiceItem</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="s">&quot;Food&quot;</span><span class="o">,</span> <span class="s">&quot;2.95&quot;</span><span class="o">),</span> <span class="s">&quot;1.95&quot;</span><span class="o">))</span></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>&nbsp;&nbsp;<span class="s">&quot;not be ready to send&quot;</span> <span class="n">in</span> <span class="o">{</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">invoice</span><span class="o">.</span><span class="n">send</span><span class="o">.</span><span class="n">rejected</span> <span class="n">must</span> <span class="n">beEqualTo</span><span class="o">(</span><span class="s">&quot;recipient and items must be specified before sending&quot;</span><span class="o">)</span></div><div class='line' id='LC14'>&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC15'><span class="o">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/819082/c76ac0d3223a5e2cd1d79805f6e13f9eaec90509/InvoiceSpec.scala" style="float:right;">view raw</a>
            <a href="https://gist.github.com/819082#file_invoice_spec.scala" style="float:right;margin-right:10px;color:#666">InvoiceSpec.scala</a>
            <a href="https://gist.github.com/819082">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Here the need to sequence the different behaviors using <code>flatMap</code> is ugly. Fortunately, this can be improved by using a more convenient name (<code>bind</code> or <code>&gt;&gt;=</code>) and in many cases, a service will only invoke a single method on an aggregate at a time, so the need for sequencing behaviors may be rare. Validation checking has improved, since there is no longer a need to catch exceptions, improving readability and making it easier to combine multiple validation results into one.</p>
<h2>Conclusion</h2>
<p>This series of blog posts has taken us through a whirlwind tour of modeling a simple invoice example. Starting out with a straightforward JPA implemention we quickly moved to event sourcing that made it possible to implement an <em>immutable domain model</em>. This allowed us to raise the level of abstraction of our code, increase clarity, and increase type safety. Finally we used some functional programming techniques to reduce boilerplate. Even with the additional classes and event handling methods, the monadic version of <code>Invoice</code> is only slightly larger than the mutable event sourced invoice. The test code is significantly smaller, since it no longer needs to test for various run-time checks, as the compiler takes care of that.</p>
<p>But the most significant advantage of event sourcing is the ability to change the implementation of the domain in radical ways, making it possible to keep up with changing business requirements and allowing us to keep improving the domain as our knowledge and understanding improves. All this with very little impact on the rest of the system and no need to perform database migrations. </p>
<p>Furthermore, our reporting and querying needs are also decoupled from the domain. Now we can easily use an RDBMS, document store, lucene index, graph database, and/or anything else that is most appropriate for our specific querying and reporting needs, without any impact on our domain model.</p>
<p>Finally, critical business data has become much more durable, as we only <em>add</em> events, and never update or delete. Full historical data is maintained, which potentially holds a great amount of business value. We now also have access to full audit logs for regulatory or debugging purposes, etc. This is incredibly valuable!</p>
<p>The design space for CQRS, event sourcing, and immutable domain models is still wide open. It will be very interesting to see how this evolves, and when and where these techniques are applicable. Certainly it makes it possible to apply standard functional programming techniques to &#8220;inherently&#8221; mutable business domains, with all the goodness that entails.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.zilverline.com%2F2011%2F02%2F10%2Ftowards-an-immutable-domain-model-monads-part-5%2F&amp;title=Towards%20an%20immutable%20domain%20model%20%26%238211%3B%20monads%20%28part%205%29" id="wpa2a_20"><img src="http://blog.zilverline.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.zilverline.com/2011/02/10/towards-an-immutable-domain-model-monads-part-5/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

