<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Thomas Moerman</title>
	<atom:link href="http://thomasmoerman.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://thomasmoerman.wordpress.com</link>
	<description>In pursuit of beautiful code, fluffy snow, and purple cows.</description>
	<lastBuildDate>Sun, 11 Dec 2011 09:58:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='thomasmoerman.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/fc1ebc058b385bf0f1d7103c3414728b?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Thomas Moerman</title>
		<link>http://thomasmoerman.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://thomasmoerman.wordpress.com/osd.xml" title="Thomas Moerman" />
	<atom:link rel='hub' href='http://thomasmoerman.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Functional fun with fibonacci and friends</title>
		<link>http://thomasmoerman.wordpress.com/2011/12/10/fun-with-fibonacci/</link>
		<comments>http://thomasmoerman.wordpress.com/2011/12/10/fun-with-fibonacci/#comments</comments>
		<pubDate>Sat, 10 Dec 2011 18:53:14 +0000</pubDate>
		<dc:creator>Thomas</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://thomasmoerman.wordpress.com/?p=685</guid>
		<description><![CDATA[Arguably the quintessential recursive function is the fibonacci function. fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) In Scala it looks like this. def fib(n: BigInt): BigInt = if (n &#60; 2) 1 else fib(n-2) + fib(n-1) We assume of course that input n is always a positive integer number. From a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=685&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Arguably the quintessential recursive function is the <em>fibonacci</em> function.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
fib(0) = 1
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2)
</pre>
<p></p>
<p>In Scala it looks like this.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def fib(n: BigInt): BigInt = if (n &lt; 2) 1 else fib(n-2) + fib(n-1)
</pre>
<p></p>
<p>We assume of course that input n is always a positive integer number. From a mathematical perspective this is a beautiful implementation, concise and elegant. However, something is very wrong with this implementation. Can you spot it?</p>
<p>Exactly: it&#8217;s inefficient. Just think about it for a while, without formal proof we can intuitively guess the complexity of this algorithm. It&#8217;s equal to the very number it computes!</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
O(fib(n)) = fib(n)
</pre>
<p></p>
<p>Simply measure some executions and see for yourself.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
import java.lang.System._

def main(args: Array[String]): Unit =
  for (n &lt;- 1 to 38) {
    val t1 = currentTimeMillis
    fib(n)
    val t2 = currentTimeMillis
    println(n, t2 - t1)
  }
</pre>
<p></p>
<p>Lovely to see how the execution times follow one another in true fibonacci style.</p>
<p><img src="http://thomasmoerman.files.wordpress.com/2011/12/fib-chart1.png?w=700" alt="" style="border-width:0;" title="fib chart"   class="aligncenter size-full wp-image-719" /></p>
<p>The problem is that intermediate values are computed over and over again in every recursive branch of the algorithm. It would be nice if for a given number x, we could cache fib(x) and re-use that pre-calculated result when we need it calculating y where y &gt; x. This technique is called <a href="http://en.wikipedia.org/wiki/Memoization">function memoization</a>.</p>
<p>Function memoization boils down to a higher-order function that takes the original function as input, and returns another function with the caching mechanism built in.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def memoize[A, B](f: A =&gt; B) = new (A =&gt; B) {

  val cache = scala.collection.mutable.Map[A, B]()

  def apply(x: A): B = cache.getOrElseUpdate(x, f(x))

}
</pre>
<p></p>
<p>The Scala implementation is remarkably simple. We accept a generic function f, and return an anonymous function with the same generic types. The cache is a simple HashMap. The function application method consults the cache and returns it if present, else it computes the desired result, stores it in the cache and returns that result. All this is cleverly implemented by the mutable.Map getOrElseUpdate method:</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def getOrElseUpdate(key: A, op: =&gt; B): B
</pre>
<p></p>
<p>Note that the second parameter is <em>lazy</em>, the passed function is only evaluated when necessary. In Java this is very awkward to implement because parameter passing always has <a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value">call-by-value</a> semantics.</p>
<p>So, are we done? Can we speed up our fibonacci function by memoizing it? Let&#8217;s find out&#8230;</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def main(args: Array[String]): Unit = {
  val fib_memoized = memoize(fib)

  val t1 = currentTimeMillis
  val r  = fib_memoized(38)
  val t2 = currentTimeMillis

  println("result %s calculated in %s milliseconds".format(r, t2-t1))
}
</pre>
<p></p>
<p>result 39088169 calculated in 8480 milliseconds</p>
<p>&amp;%#@!! Curses and profanity! It turns out the cache is only consulted once. Why is that? What is wrong? Is it because there is something special about our fibonacci implementation?</p>
<p>Ah, yes&#8230;</p>
<p>It&#8217;s recursive. </p>
<p><img src="http://thomasmoerman.files.wordpress.com/2011/12/haskellbcurry.jpg?w=244&#038;h=300" alt="" style="border-width:0;" title="HaskellBCurry" width="244" height="300" class="alignright size-medium wp-image-726" /><br />
Our problem turns out to be more tricky than initially expected. We somehow need to weave the memoization down the recursive calls of the function. Let&#8217;s call a knowledgeable gentleman on stage to help us out here. Please welcome&#8230; <a href="http://en.wikipedia.org/wiki/Haskell_Curry">Haskell Curry</a>!</p>
<p>Haskell Curry, a pioneer in the field of combinatory logic, discovered a fascinating function called the Y combinator. If you&#8217;ve got a red pill handy and want to know more about it, the rabbit hole is <a href="http://mvanier.livejournal.com/2897.html">this way</a>. Pretty mind blowing stuff!</p>
<p>In a nutshell, what is it and how can we use it? The Y combinator is a higher-order function that takes a non-recursive function and returns a version of that function that <em>is</em> recursive.</p>
<p>Hey! Wait a minute! But our fibonacci function is recursive, so we can&#8217;t feed it into the Y combinator, right?</p>
<p>Correct. The trick goes as follows: if we could somehow turn our fibonacci function in a non-recursive function, we could use the Y combinator to transform it into a recursive one <em>with memoization built in</em>, we&#8217;re done!</p>
<p>Let&#8217;s begin with the first step. We need to pull the recursion out of our beloved fibonacci function. This means eliminating the two recursive calls to itself.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def fib(n: BigInt): BigInt = if (n &lt; 2) 1 else <font color="#FF3300"><strong><em>fib</em></strong></font>(n-2) + <font color="#FF3300"><strong><em>fib</em></strong></font>(n-1)
</pre>
<p></p>
<p>We substitute the recursive call by a new function <em>g: BigInt =&gt; BigInt</em>, that we pass to the fib function as an extra argument.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def fib<font color="#FF3300"><strong><em>(g: BigInt =&gt; BigInt)</em></strong></font>(n: BigInt): BigInt = if (n &lt; 2) 1 else <font color="#FF3300"><strong><em>g</em></strong></font>(n-2) + <font color="#FF3300"><strong><em>g</em></strong></font>(n-1)
</pre>
<p></p>
<p>We redefine the memoize function as follows:</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def memoize[A, B](f: (A =&gt; B) =&gt; A =&gt; B): (A =&gt; B) = {

  val cache = scala.collection.mutable.Map[A, B]()

  def y(f: (A =&gt; B) =&gt; A =&gt; B): (A =&gt; B) =
    a =&gt; cache.getOrElseUpdate(a, f(y(f)(_))(a))

  y(f)

}
</pre>
<p></p>
<p>The memoize function defines the nested Y combinator function <em>y</em>, which implements the caching strategy. The result of the memoization is again a function equal to the Y combinator applied to our non-recursive function <em>f</em>.</p>
<p>Let&#8217;s find out if it does work faster now!</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
def main(args: Array[String]): Unit = {
  val fib_memoized = memoize(fib)

  val t1 = currentTimeMillis
  val r  = fib_memoized(1000)
  val t2 = currentTimeMillis

  println("result %s calculated in %s milliseconds".format(r, t2-t1))
}
</pre>
<p></p>
<p>result<br />
7033036771142281582183525487718354977018126983635873274260490508715453711819693357974<br />
2249494562611733487750449241765991088186363265450223647106012053374121273867339111198<br />
139373125598767690091902245245323403501 calculated in 73 milliseconds</p>
<p><img src="http://thomasmoerman.files.wordpress.com/2011/12/logical_awesome.jpg?w=700&#038;h=560" style="border-width:0;" alt="" title="logical_awesome" width="700" height="560" class="aligncenter size-full wp-image-767" /></p>
<p>Err&#8230; nope, mr. Spock. Your codes aren&#8217;t perfect. Depending on your JVM configuration, this implementation will sooner or later result in a <a href="http://en.wikipedia.org/wiki/Stack_overflow">stack overflow</a>. This problem plagues every recursive function that is not <a href="http://en.wikipedia.org/wiki/Tail_call">tail recursive</a> and therefore cannot be subject to tail call optimization. </p>
<p>In a real-world situation, an imperative implementation with a loop instead of recursion (or almost-recursion with the Y combinator) is obviously the better choice.</p>
<p>Nonetheless, functional programming is powerful and a lot of fun!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/thomasmoerman.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/thomasmoerman.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/thomasmoerman.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/thomasmoerman.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/thomasmoerman.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/thomasmoerman.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/thomasmoerman.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/thomasmoerman.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/thomasmoerman.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/thomasmoerman.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/thomasmoerman.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/thomasmoerman.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/thomasmoerman.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/thomasmoerman.wordpress.com/685/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=685&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://thomasmoerman.wordpress.com/2011/12/10/fun-with-fibonacci/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d897498c4d077e10ae686c84169c0898?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Thomas</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2011/12/fib-chart1.png" medium="image">
			<media:title type="html">fib chart</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2011/12/haskellbcurry.jpg?w=244" medium="image">
			<media:title type="html">HaskellBCurry</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2011/12/logical_awesome.jpg" medium="image">
			<media:title type="html">logical_awesome</media:title>
		</media:content>
	</item>
		<item>
		<title>Steve Yegge you&#8217;re a fucking legend</title>
		<link>http://thomasmoerman.wordpress.com/2011/09/28/steve-yegge-youre-a-fucking-legend/</link>
		<comments>http://thomasmoerman.wordpress.com/2011/09/28/steve-yegge-youre-a-fucking-legend/#comments</comments>
		<pubDate>Wed, 28 Sep 2011 19:27:38 +0000</pubDate>
		<dc:creator>Thomas</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://thomasmoerman.wordpress.com/?p=610</guid>
		<description><![CDATA[Regarding the challenge, consider it accepted!<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=610&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Regarding the challenge, consider it accepted!</p>
<span style="text-align:center; display: block;"><a href="http://thomasmoerman.wordpress.com/2011/09/28/steve-yegge-youre-a-fucking-legend/"><img src="http://img.youtube.com/vi/vKmQW_Nkfk8/2.jpg" alt="" /></a></span>
<p></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/thomasmoerman.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/thomasmoerman.wordpress.com/610/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/thomasmoerman.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/thomasmoerman.wordpress.com/610/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/thomasmoerman.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/thomasmoerman.wordpress.com/610/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/thomasmoerman.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/thomasmoerman.wordpress.com/610/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/thomasmoerman.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/thomasmoerman.wordpress.com/610/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/thomasmoerman.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/thomasmoerman.wordpress.com/610/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/thomasmoerman.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/thomasmoerman.wordpress.com/610/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=610&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://thomasmoerman.wordpress.com/2011/09/28/steve-yegge-youre-a-fucking-legend/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d897498c4d077e10ae686c84169c0898?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Thomas</media:title>
		</media:content>
	</item>
		<item>
		<title>I love f.lux</title>
		<link>http://thomasmoerman.wordpress.com/2011/09/17/i-love-f-lux/</link>
		<comments>http://thomasmoerman.wordpress.com/2011/09/17/i-love-f-lux/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 22:07:40 +0000</pubDate>
		<dc:creator>Thomas</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://thomasmoerman.wordpress.com/?p=588</guid>
		<description><![CDATA[I recently stumbled on this post on Hacker News. It&#8217;s about a little tool called f.lux that allows you to adjust your computer monitor&#8217;s brightness. Hold on, brightness is not exactly the correct term here, f.lux allows you to adjust the screen&#8217;s color temperature, not just its intensity. Researchers believe the blueish light of a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=588&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://thomasmoerman.files.wordpress.com/2011/09/flux.png"><img src="http://thomasmoerman.files.wordpress.com/2011/09/flux.png?w=700" alt="" title="flux"   style="border-width:0;" class="alignleft size-full wp-image-590" /></a>I recently stumbled on <a href="http://news.ycombinator.com/item?id=2369788">this</a> <a href="http://news.ycombinator.com/item?id=2369788">post</a> on <a href="http://news.ycombinator.com/">Hacker News</a>. It&#8217;s about a little tool called <a href="http://stereopsis.com/flux/">f.lux</a> that allows you to adjust your computer monitor&#8217;s brightness. </p>
<p>Hold on, brightness is not exactly the correct term here, f.lux allows you to adjust the screen&#8217;s <a href="http://news.ycombinator.com/item?id=2369788">color temperature</a>, not just its intensity. Researchers believe the blueish light of a computer screen tricks your brain into thinking it is still day time. Shifting the color temperature to a more reddish hue is not only softer on your eyes, it can actually improve your sleep quality. This is especially helpful for nocturnal people like myself who often use the computer before going to sleep. And it&#8217;s quite cosy! </p>
<p><a href="http://thomasmoerman.files.wordpress.com/2011/09/flux-interior.jpg"><img src="http://thomasmoerman.files.wordpress.com/2011/09/flux-interior.jpg?w=700&#038;h=392" alt="" title="flux interior" width="700" style="border-width:0;" height="392" class="aligncenter size-full wp-image-596" /></a></p>
<p>In fact it reminds of how much I hate these <a href="http://en.wikipedia.org/wiki/Compact_fluorescent_lamp">energy-saving light bulbs</a>, especially the cheaper ones you can buy at Ikea. The old-fashioned <a href="http://en.wikipedia.org/wiki/Incandescent_light_bulb">incandescent</a> light bulbs are banned from stores in Belgium for ecological reasons (not taking into account nasty chemicals like mercury <a href="http://environment.about.com/od/greenlivinginyourhome/a/cfl_mercury.htm">involved</a> in making energy-saving fluorescent lamps). I liked those so much better. Still have some spare ones, hee hee :p</p>
<p>As an experiment, install f.lux and do something useful like working on your latest code project for let&#8217;s say 10 minutes with the color temperature set to &#8216;halogen&#8217; (3400K). Then switch it back to the default daylight setting (6500K). Holy toledo Batman, my eyes! Aaarghl! </p>
<p>I&#8217;ve started using f.lux during my daytime work as well, just slightly adjusting the temperature from the default 6500K to a slightly more mellow 5800K. Much nicer. </p>
<p>Highly recommended, <a href="http://stereopsis.com/flux/">check it out</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/thomasmoerman.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/thomasmoerman.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/thomasmoerman.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/thomasmoerman.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/thomasmoerman.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/thomasmoerman.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/thomasmoerman.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/thomasmoerman.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/thomasmoerman.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/thomasmoerman.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/thomasmoerman.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/thomasmoerman.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/thomasmoerman.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/thomasmoerman.wordpress.com/588/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=588&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://thomasmoerman.wordpress.com/2011/09/17/i-love-f-lux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d897498c4d077e10ae686c84169c0898?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Thomas</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2011/09/flux.png" medium="image">
			<media:title type="html">flux</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2011/09/flux-interior.jpg" medium="image">
			<media:title type="html">flux interior</media:title>
		</media:content>
	</item>
		<item>
		<title>Java vs. Clojure</title>
		<link>http://thomasmoerman.wordpress.com/2011/09/02/java-vs-clojure/</link>
		<comments>http://thomasmoerman.wordpress.com/2011/09/02/java-vs-clojure/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 13:57:13 +0000</pubDate>
		<dc:creator>Thomas</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://thomasmoerman.wordpress.com/?p=558</guid>
		<description><![CDATA[Couldn&#8217;t resist sharing this little Java vs. Clojure episode. Consider following interview question (stolen from a blog post): given a string such as &#8220;AABAB&#8221;, return the string with all consecutive duplicate letters removed, ergo: &#8220;ABAB&#8221; I&#8217;m a professional Java guy with a few years of experience, this should be a piece of cake, right? Following [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=558&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://thomasmoerman.files.wordpress.com/2011/09/david-vs-goliath.jpg"><img src="http://thomasmoerman.files.wordpress.com/2011/09/david-vs-goliath.jpg?w=700" alt="" title="david-vs-goliath"   class="aligncenter size-full wp-image-565" style="border-width:0;" /></a></p>
<p>Couldn&#8217;t resist sharing this little Java vs. <a href="http://clojure.org/">Clojure</a> episode. Consider following interview question (stolen from <a href="http://blog.nyaruka.com/learning-to-swim-by-reading-a-book">a blog post</a>):</p>
<blockquote><p>given a string such as &#8220;AABAB&#8221;, return the string with all consecutive duplicate letters removed, ergo: &#8220;ABAB&#8221;</p></blockquote>
<p>I&#8217;m a professional Java guy with a few years of experience, this should be a piece of cake, right? Following code is what I vomited onto my IDE in about 5 minutes. It&#8217;s not optimal, nor very beautiful, but it works. Consider it a brain dump, I&#8217;d polish it up in real project.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
public class RemoveDuplicatesTest {

    @Test
    public void test() {
	assertEquals("", removeDuplicates(""));
	assertEquals("A", removeDuplicates("A"));
	assertEquals("AB", removeDuplicates("ABBBBBBBB"));
	assertEquals("ABAB", removeDuplicates("AAAABBAAB"));
    }

    private String removeDuplicates(String string) {
	if (string == null) {
    	    throw new IllegalArgumentException();
	}

	if (string.length() == 0) {
	    return "";
	}

	final char[] chars = string.toCharArray();

	char current = chars[0];

	final List acc = new ArrayList();

	for (char c : chars) {
	    if (c != current) {
	        acc.add(current);

	 	current = c;
            }
 	}

	if (acc.isEmpty() || acc.get(acc.size() - 1) != current) {
	    acc.add(current);
	}

	final StringBuilder result = new StringBuilder();

	for (Character c : acc) {
	    result.append(c);
	}

	return result.toString();
    }

}
</pre>
<p></p>
<p>Now, I&#8217;ve been reading up on Clojure since last week, so I gave it go as well. About half an hour of messing around in the <a href="http://plugins.intellij.net/plugin/?id=4050">La Clojure</a> REPL, not too bad for a Clojure newbie. Lost some time looking up how to turn a vector into a String.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
(defn removeDuplicates [arg]
  (loop [chars arg, acc []]
    (if (empty? chars) acc
      (recur (rest chars) (if (= (first chars) (last acc)) acc (conj acc (first chars)))))))

(defn to-string [s]
  (apply str s))

(= "AB" (to-string (removeDuplicates "AAABBB")))
</pre>
<p></p>
<p>I&#8217;m not entirely sure this qualifies as idiomatic Clojure but it looks pretty tight, would you agree? Also note that the assignment kind of pushed me to think in terms of removing duplicates from a String. The Clojure version is more generic out of the box and removes duplicates from a seq instead, but works for a String as well because a String is also a seq of characters. </p>
<p>I think it&#8217;s rather scary that my supposedly well-developed Java brain produces that ugly pile of code, and my embryonical Clojure brain spits out a solution that just beats the crap out the Java implementation. I&#8217;m a strong believer in the <a href="http://en.wikipedia.org/wiki/Sapir-Whorf_hypothesis">Sapir-Whorf hypothesis</a> in the context of programming languages, this example adds yet more proof to it.</p>
<blockquote><p>The principle of linguistic relativity holds that the structure of a language affects the ways in which its speakers are able to conceptualize their world[..]</p></blockquote>
<p>Clojure is awesome.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/thomasmoerman.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/thomasmoerman.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/thomasmoerman.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/thomasmoerman.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/thomasmoerman.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/thomasmoerman.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/thomasmoerman.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/thomasmoerman.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/thomasmoerman.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/thomasmoerman.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/thomasmoerman.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/thomasmoerman.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/thomasmoerman.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/thomasmoerman.wordpress.com/558/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=558&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://thomasmoerman.wordpress.com/2011/09/02/java-vs-clojure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d897498c4d077e10ae686c84169c0898?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Thomas</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2011/09/david-vs-goliath.jpg" medium="image">
			<media:title type="html">david-vs-goliath</media:title>
		</media:content>
	</item>
		<item>
		<title>Pay your bills with DCI</title>
		<link>http://thomasmoerman.wordpress.com/2010/07/21/pay-your-bills-with-dci/</link>
		<comments>http://thomasmoerman.wordpress.com/2010/07/21/pay-your-bills-with-dci/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 21:11:35 +0000</pubDate>
		<dc:creator>Thomas</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[DCI]]></category>

		<guid isPermaLink="false">http://thomasmoerman.wordpress.com/?p=439</guid>
		<description><![CDATA[Another &#8220;transfer money&#8221; implementation i&#8217;m afraid, but I think it is a good one. In this post I address two difficulties I encountered when coding up a DCI style use case in Scala. The first is nested contexts. It is not uncommon that during execution of a certain context, one or more other contexts are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=439&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Another &#8220;transfer money&#8221; implementation i&#8217;m afraid, but I think it is a good one. In this post I address two difficulties I encountered when coding up a DCI style use case in Scala. The first is nested contexts. It is not uncommon that during execution of a certain context, one or more other contexts are instantiated and executed. We&#8217;ll have a glance at what this looks like in my approach. Second is the problem of injecting roles in objects that already exist. This issue arises when doing DCI in a statically typed language like Scala. I reckon it isn&#8217;t that much of a problem in Ruby, for instance. I remember James Coplien mentioning Scala in one of his talks, saying that Scala looks as it was made for DCI. I&#8217;m not sure, I found myself struggling quite a lot with injecting roles in existent objects. Scala does not allow to mix in traits in existing objects at runtime, only statically or at object instantiation. Fortunately Scala has a trick up its sleeve that approximates dynamic mixins, we&#8217;ll get to that in a moment.</p>
<p>As I mentioned in my previous post on DCI, the key technique I use to glue the different parts of the code together is the <a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html">Cake Pattern</a>, a technique for doing dependency injection in Scala. Although it is suitable for that, I think it is capable of more. Having a Java background, I regard dependency injection as a way to piece together object graphs, where the different components are objects instances. The result of this is usually a static object graph where the different objects are some sort of stateless containers for logically related methods. I am maybe stereotyping here, but this is what a lot of Spring applications look like. The Cake Pattern is actually a lot more powerful than traditional dependency injection. Instead of piecing together object graphs, you can actually weld a pile of traits together into very precisely synthesized objects. Or in other words, it is not an object <em>graph</em> that is built from object instances, it is a single object that is built from traits. When learning about that, it struck me that the Cake Pattern could potentially be a very suitable technique for doing DCI in scala. DCI is all about putting together exactly the needed functionality into a small object graph, launching an interaction, and then letting the created objects be garbage collected again. I think DCI is an excellent theory for guiding developers in deciding <em>which</em> components to create. The Cake Pattern can then be used to piece those components together into a working software system.</p>
<h3>A scenario</h3>
<p>Before diving into the code, let&#8217;s briefly have a look at the scenario we&#8217;re going to implement. Image being the user of a banking application. The system has a button which allows you to pay all your unpaid bills with only one click. However, the entire transaction fails if you don&#8217;t have enough money in your bank account to pay them all. We&#8217;ll translate this to DCI artifacts. The user of the system plays a role in our case. He is a <em>person</em> that has bills to pay, which makes him a <em>debtor</em>. Or in other words, a user is represented by the Person class, and Debtor is the role that is mixed in into the Person object, in the PayBillsContext. Let&#8217;s clarify with a not-so-UML-compliant graphical representation.</p>
<p><a href="http://thomasmoerman.files.wordpress.com/2010/07/pbc2.png"><img style="border-width:0;" title="click to enlarge" src="http://thomasmoerman.files.wordpress.com/2010/07/pbc2.png?w=700" alt="" /></a></p>
<p>Notice the blue balloons, these are the nested contexts I mentioned earlier. It is the methodful role implementation TransactionalDebtor of the methodless role Debtor that instantiates and executes TransferMoneyContext objects. Conceptually this is easy to grasp, but don&#8217;t forget that the TransferMoneyContext object is a configured &#8220;business&#8221; component that is capable of working with a transactional resource like a database. So how can the methodful role instantiate such an object? Doesn&#8217;t this remind of the <a href="http://martinfowler.com/bliki/AnemicDomainModel.html">anemic domain model</a> debate? Or the question whether it is a good idea to <a href="http://hendryluk.wordpress.com/2008/05/10/should-domain-entity-be-managed-by-ioc/">inject business objects into domain entities</a>? Now we&#8217;re cooking. Enter the almighty Cake Pattern.</p>
<h3>Salt, pepper, Scala&#8230; check!</h3>
<p><img class="aligncenter size-full wp-image-468" style="border-width:0;" title="Yum!" src="http://thomasmoerman.files.wordpress.com/2010/07/cake.jpg?w=700" alt=""   /></p>
<p>The Cake Pattern is something very particular of Scala. Based on Martin Odersky and Matthias Zenger&#8217;s paper called <a href="http://lamp.epfl.ch/~odersky/papers/ScalableComponent.pdf">Scalable Component Abstractions</a>, it was later baptised under its common name by Jon Pretty in a <a href="http://www.nabble.com/Inheriting-static-members-td10106162.html">discussion thread</a>. Quoting Jon:</p>
<blockquote><p>(&#8230;) beyond my appreciation of cake, [a] cake is made of a number of layers (separated by jam), and can be sliced. The layers represent the different levels of inner class nesting. It is conceivable that you would reach the bottom layer by working your way down from the top.</p></blockquote>
<p>It is a very weird pattern, I&#8217;ll happily admit that. The best way to get your head around it is to code up something yourself. It honestly took me quite a while before my penny really dropped. Anyhow, the beauty of this pattern is that because of its nested traits, the line between entities and business components becomes very blurred. An entity instantiated in a Cake Pattern-y business component al of a sudden has access to the dependencies of that business component, defined by self-type annotations. It becomes even weirder when, in a certain business component, you implicitly convert an existing entity into a role, where the implicit conversion is defined in a trait on which that business component depends, where that trait has dependencies of its own, also defined by self-type annotations. The modest domain entity all of a sudden gains business component superpowers! Yikes! Everybody still with me? Let me illustrate with some code, starting with the Debtor role and the PayBillsContext.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">trait Debtor {
  def payBills
}

trait Context {
  def execute
}

trait PayBillsContextFactory {
  this: DebtorProvider =&gt;

  class PayBillsContext(val person: Person) extends Context {
    def execute = person.payBills  // implicit conversion from Person to Debtor
  }

}</pre>
<p></p>
<p>The Debtor trait, a methodless role, is pretty straightforward, it has only one method. (Rereading this sentence it struck me how contradictory that sounds, a &#8220;methodless role with one method&#8221;. With methodless roles DCI refers to methods without <em>implementations</em>, just to clarify) The PayBillsContext class is also very simple, it has a Person variable and an execute method. But look, in that execute method, we call the payBills method on a Person instance! Somehow that Person must have secretly been turned into a Debtor, otherwise this wouldn&#8217;t compile. How can this be?</p>
<h3>I know kung fu</h3>
<p>Notice that the PayBillsContext class is an inner class defined in an outer trait PayBillsContextFactory. The outer trait is pretty empty, apart from its self-type annotation DebtorProvider.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">trait DebtorProvider {
  implicit def asDebtor(person: Person): Debtor
}</pre>
<p></p>
<p>An abstract <a href="http://www.codecommit.com/blog/ruby/implicit-conversions-more-powerful-than-dynamic-typing">implicit conversion</a> method. How does this work? When the Scala compiler sees some method being called on something that doesn&#8217;t have that method, it looks for implicit conversions in scope that could solve this conflict. In this case, the compiler finds that abstract implicit conversion method in the self-type of the PayBillsContextFactory trait, namely the DebtorProvider trait. This is a compatible conversion, so the compiler is happy and doesn&#8217;t complain. This is wicked! In the context of paying bills, the Person object is provided with all the intelligence he needs in his role as Debtor. Doesn&#8217;t that <a href="http://www.youtube.com/watch?v=6vMO3XmNXe4&amp;feature=related">remind you of something</a>?</p>
<p><img class="aligncenter size-full wp-image-509" style="border-width:0;" title="I know kung fu!" src="http://thomasmoerman.files.wordpress.com/2010/07/iknowkungfu.jpg?w=700" alt="" /></p>
<p>Indeed Mr. Anderson, you know kung fu. Let&#8217;s have a look at what kind of kung-fu you know.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">trait TransactionalDebtorProvider extends DebtorProvider {
  this: Transactional with PayBillsQueries with TransferMoneyContextFactory =&gt;

  implicit def asDebtor(person: Person): Debtor = new TransactionalDebtor(person)

  class TransactionalDebtor(self: Person) extends Debtor {

    def payBills = inTransaction {
      findUnpaidBills(self.id) foreach {case (bill, creditor) =&gt;
        new TransferMoneyContext(self.accountId, creditor.accountId, bill.amount).execute
        markAsPaid(bill.id)
      }
    }

  }

}</pre>
<p></p>
<p>In the TransactionalDebtorProvider trait, the abstract implicit conversion method is implemented. It returns an instance of the TransactionalDebtor class, which wraps a Person instance and implements the Debtor trait. You all know what this is called right? It&#8217;s an <a href="http://en.wikipedia.org/wiki/Adapter_pattern">adapter</a>. Actually I would have liked to implement the TransactionalDebtor as a trait, with Person as a self-type annotation, but I haven&#8217;t found a way to glue such a trait onto an existing object. I don&#8217;t think it is possible at all in Scala (if it is, please tell me how). You can only mix in such a trait at object instantiation, that&#8217;s as close to dynamic traits as you get, i&#8217;m afraid. Still, the implementation is quite clean. The fact that the DCI methodful role is implemented as a class instead of a trait is only a minor aesthetical flaw.</p>
<p>Let&#8217;s zoom in on what is going on in the payBills implementation. In a transaction, a query is launched to retrieve the Person&#8217;s unpaid Bills, and each bill is paid by executing a TransferMoneyContext. Lastly, the Bill is marked as paid. The implicit conversion from Person to Debtor provides that Person with this functionality. The TransactionalDebtor is able to launch transactions, execute queries and create TransferMoneyContext instances because its outer trait, the TransactionalDebtorProvider, has the necessary dependencies, defined as self-types: Transactional, PayBillsQueries and TransferMoneyContextFactory. Remember me saying that the Cake Pattern somehow blurs the line between domain entities and business components? No need for implementing hooks in an ORM framework so that it interacts with a dependency injection container in order to inject business components into entities. (For more information about the TransferMoneyContext, see my <a href="http://thomasmoerman.wordpress.com/2010/03/11/dci-in-a-different-style/">previous post</a>)</p>
<p>In summary, every outer trait sits on top of its self-types, which in turn sit on top of their self-types. The only thing we still need to do is do the actual welding together of all the traits.</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait LayerCake
  extends PayBillsContextFactory
     with TransactionalDebtorProvider
     with PayBillsQueriesSqueryl
     with TransferMoneyContextFactory
     with TransactionalMoneySourceProvider
     with TransactionalMoneySinkProvider
     with UpdatableAccountAspect
     with CalculatedBalanceAspect
     with MoneyTransferQueriesSqueryl
     with TransactionalWithSqueryl
     with Tables
     with MyDataSource</pre>
<p></p>
<p>What does this look like to you? It&#8217;s a layer cake! A stack of traits, summarized in a trait, which can then be mixed into other traits or objects. </p>
<h3>Conclusion</h3>
<p>Using the Cake Pattern, working with nested DCI Contexts is absolutely trivial. As is injection of all kinds of logic that is untypical of domain entities. Injecting roles into existing objects can be done rather elegantly with implicit conversions. The beauty of it all is that I don&#8217;t need any frameworks to do all this. It&#8217;s just Scala.</p>
<p>That&#8217;s it! I hope that I&#8217;ve somehow been able to convey the train of thought that led to this implementation. Don&#8217;t be shy and comment away! </p>
<p>The code is available on <a href="http://code.google.com/p/thomasmoerman/source/browse/#svn/trunk/blog02/src/com/thomasmoerman/dci2">Google Code</a>.</p>
<p>It compiles with the final Scala 2.8 release and has a few dependencies:</p>
<ul>
<li><a href="http://max-l.github.com/Squeryl/downloads.html">squeryl_2.8.0-0.9.4beta8.jar</a> &#8211; an impressive Scala DSL for SQL queries, recommended!</li>
<li><a href="http://sourceforge.net/projects/cglib/files/">cglib-2.2.jar</a></li>
<li><a href="http://forge.ow2.org/projects/asm/">asm-3.2.jar</a></li>
<li><a href="http://sourceforge.net/projects/c3p0/">c3p0-0.9.1.2.jar</a></li>
<li><a href="http://www.mysql.com/downloads/connector/j/">mysql-connector-java-5.1.10</a></li>
</ul>
<p>Peace.</p>
<p><img class="aligncenter size-full wp-image-477" style="border-width:0;" title="I wish my train of thought was this fast" src="http://thomasmoerman.files.wordpress.com/2010/07/jet_train1.jpg?w=700" alt=""   /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/thomasmoerman.wordpress.com/439/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/thomasmoerman.wordpress.com/439/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/thomasmoerman.wordpress.com/439/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/thomasmoerman.wordpress.com/439/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/thomasmoerman.wordpress.com/439/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/thomasmoerman.wordpress.com/439/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/thomasmoerman.wordpress.com/439/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/thomasmoerman.wordpress.com/439/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/thomasmoerman.wordpress.com/439/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/thomasmoerman.wordpress.com/439/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/thomasmoerman.wordpress.com/439/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/thomasmoerman.wordpress.com/439/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/thomasmoerman.wordpress.com/439/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/thomasmoerman.wordpress.com/439/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=439&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://thomasmoerman.wordpress.com/2010/07/21/pay-your-bills-with-dci/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d897498c4d077e10ae686c84169c0898?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Thomas</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2010/07/pbc2.png" medium="image">
			<media:title type="html">click to enlarge</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2010/07/cake.jpg" medium="image">
			<media:title type="html">Yum!</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2010/07/iknowkungfu.jpg" medium="image">
			<media:title type="html">I know kung fu!</media:title>
		</media:content>

		<media:content url="http://thomasmoerman.files.wordpress.com/2010/07/jet_train1.jpg" medium="image">
			<media:title type="html">I wish my train of thought was this fast</media:title>
		</media:content>
	</item>
		<item>
		<title>DCI in a different style</title>
		<link>http://thomasmoerman.wordpress.com/2010/03/11/dci-in-a-different-style/</link>
		<comments>http://thomasmoerman.wordpress.com/2010/03/11/dci-in-a-different-style/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 00:37:13 +0000</pubDate>
		<dc:creator>Thomas</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[DCI]]></category>
		<category><![CDATA[dependency injection]]></category>

		<guid isPermaLink="false">http://thomasmoerman.wordpress.com/?p=149</guid>
		<description><![CDATA[After reading Bill Venners&#8216; implementation of the money transfer use case in the upcoming DCI book, I was wondering how this example could be implemented in a more enterprise-y style with dependency injection. Scala has this wonderful technique of doing dependency injection called the Cake Pattern. So I tried to code up a fully working [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=149&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>After reading <a href="http://www.java.net/blogs/bv/">Bill Venners</a>&#8216; implementation of the money transfer use case in the upcoming <a href="http://www.artima.com/articles/dci_vision.html">DCI</a> <a href="http://www.amazon.com/Lean-Architecture-Agile-Software-Development/dp/0470684208">book</a>, I was wondering how this example could be implemented in a more enterprise-y style with <a href="http://martinfowler.com/articles/injection.html">dependency injection</a>. Scala has this wonderful technique of doing dependency injection called the <a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html">Cake Pattern</a>. So I tried to code up a fully working implementation of the example in Scala that talks to a MySQL database and wields a transaction manager, <a href="http://www.atomikos.com/Main/TransactionsEssentials">Atomikos</a> in this case, where all the bits and pieces are welded together with the Cake Pattern.<br />
</p>
<p>
For those who are not familiar with the Cake Pattern, it might be a bit confusing. However, there is an excellent <a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html">post</a> on Jonas Bonér&#8217;s blog that explains it in detail. It could be useful to read up on that first before continuing.
</p>
<p>
The use case I will try to implement in this exercise is a simple one. Imagine a user of a banking system wishes to transfer $20 from her account to that of a particular creditor. In DCI lingo, this means instantiating a context object and calling an &#8216;execute&#8217; method.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
object TestApp extends Application with Registry {
  val sourceAccountId = 1
  val destinationAccountId = 2
  val amount = 20.0
  val context = createTransferMoneyContext(sourceAccountId, destinationAccountId, amount)

  context.execute
}
</pre>
<p></p>
<p>
The TestApp object has access to the createTransferMoneyContext method because it mixes in the Registry trait. This trait is responsible for actually glueing together all necessary components. The registry could be compared to a <a href="http://www.springsource.org/">Spring</a> application context or a <a href="http://code.google.com/p/google-guice/">Guice</a> module. The difference is that instead of piecing together an object graph, we weld all traits together in a single object, in this case, the TestApp. More on this later. Let&#8217;s continue with the TransferMoneyContext class and how it is created.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait TransferMoneyContextFactory {
  this: TransactionalMoneySourceProvider with MoneySinkProvider =&gt;

  def createTransferMoneyContext(sourceAccountId: Long, destinationAccountId: Long, amount: Double) =
    new TransferMoneyContext(sourceAccountId, destinationAccountId, amount)

  class TransferMoneyContext(val sourceAccountId: Long, val destinationAccountId: Long, val amount: Double) {
    def execute = {
      val source = getTransactionalMoneySource(sourceAccountId)
      val destination = getMoneySink(destinationAccountId)
      source.transferMoney(amount, destination)
    }
  }

}
</pre>
<p></p>
<p>
Ok, those not familiar with the Cake Pattern might scratch their heads now. I know I did when I first saw this strange nested trait business. The inner class is the DCI context class. It&#8217;s very simple, having only an execute method. The context class does nothing but bringing the actors to the stage (the money source and the money sink) and triggering the interaction. The context class receives its capabilities from the outer trait and the self-type annotations of the outer trait. In the Cake Pattern, self-types are used to define dependencies, in this case a provider for the money source and a provider of the money sink.
</p>
<p>
The MoneySource and MoneySink traits are the so-called <em>methodless</em> roles as per the DCI paradigm. Very simple, they only expose the methods necessary for the interaction.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait MoneySink {
  def deposit(amount: Double)
  def updateLog(msg: String, amount: Double)
}

trait MoneySource {
  def transferMoney(amount: Double, moneySink: MoneySink)
}
</pre>
<p></p>
<p>
I factored out the logic for bringing instances of these traits in what I call respectively the MoneySinkProvider and the TransactionalMoneySourceProvider. Let&#8217;s take a look at the MoneySinkProvider first.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait MoneySinkProvider {
  this: UpdatableAccountAspect =&gt;

  def getMoneySink(accountId: Long) = new Account(accountId) with UpdatableAccount with MoneySink

}
</pre>
<p></p>
<p>
Aha, here we first encounter the Account class. Those who have seen Jim Coplien&#8217;s <a href="http://vimeo.com/8235574">presentations</a> know that in the financial world, there is no such thing as an Account object. An account is a <em>computation</em>, not a record with a balance stored in a database (this is actually a good example of <a href="http://martinfowler.com/eaaDev/EventSourcing.html">Event Sourcing</a>). But here we do see an Account object, what the devil is going on?
</p>
<p>
What I did is create an <em>illusion</em> of an Account object. It looks like a JPA-style Account entity that has methods to manipulate the balance field, but all we have is just an abstract class.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
abstract class Account(val id: Long) extends Identified {
  def deposit(amount: Double)
  def withdraw(amount: Double)
  def updateLog(msg: String, amount: Double) = println("Account " + id + " " + msg + " " + amount)
}
</pre>
<p></p>
<p>
In the financial world, updating the balance of an account boils down to persisting a record with the transferred amount of money. Something that looks like the following class.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
class MoneyTransfer(val accountId: Long, val amount: Double)
  extends KeyedEntity[Long] with Identified {
  val id: Long = 0
}

object Deposit {
  def apply(accountId: Long, amount: Double) = new MoneyTransfer(accountId, amount)
}

object Withdrawal {
  def apply(accountId: Long, amount: Double) = new MoneyTransfer(accountId, -amount)
}
</pre>
<p></p>
<p>
It has a number that represents the account number and the transferred amount (and a technical id). The two other object provide factory methods, nothing more than programming esthetics really. So what we want to do in an Account instance is persist another of those MoneyTransfer records behind the scenes of the deposit and withdraw methods. That&#8217;s where the UpdatableAccountAspect comes in. Note that the MoneySinkProvider trait has a self-type annotation specifying that it depends on the UpdatableAccountAspect.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait UpdatableAccountAspect {
  this: MoneyTransferQueries =&gt;

  trait UpdatableAccount {
    this: Account =&gt;

    def deposit(amount: Double) = persist(Deposit(id, amount))
    def withdraw(amount: Double) = persist(Withdrawal(id, amount))
  }

}
</pre>
<p></p>
<p>
The inner trait encapsulates the capabilities that can be mixed into an Account object, giving that object the power to persist a MoneyTransfer instance in the case of a deposit or withdrawal. Summarized, when the MoneySinkProvider creates an Account instance, it mixes in the capability for updating the balance, and wraps it up under the guise of a MoneySink. As you see, there is no methodful role for a MoneySink, because there is no need for it. There is no interaction code for a MoneySink. Note that this object has no idea whatsoever of what its balance actually is! It does not have to know. It does not play a <em>role</em> that has to know. I&#8217;m a money sink, I receive money! Nothing more.
</p>
<p>
The MoneySource provider is a different animal.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait TransactionalMoneySourceProvider {
  this: Transactional with UpdatableAccountAspect with CalculatedBalanceAspect =&gt;

  def getTransactionalMoneySource(accountId: Long) =
    new Account(accountId)
      with UpdatableAccount
      with CalculatedBalance
      with TransactionalMoneySource 

  class InsufficientFundsException extends RuntimeException

  trait TransactionalMoneySource extends MoneySource {
    this: Account with HasBalance =&gt;

    def transferMoney(amount: Double, recipient: MoneySink) = {
      transactionally {
        if (amount &gt; balance) throw new InsufficientFundsException
        withdraw(amount)
        recipient.deposit(amount)
        updateLog("balance decreased with $", amount)
        recipient.updateLog("balance increased with $", amount)
      }
    }
  }

}
</pre>
<p></p>
<p>
The TransactionalMoneySource is the methodful role corresponding to the MoneySource methodless role. This is where the interaction logic resides. Within the boundaries of a transaction, the MoneySource checks whether it has sufficient funds, decreases its balance, increases the balance of the recipient and updates the logs of both Accounts. Aha, so a MoneySource must be aware of its balance! How does it know that? This capability is mixed in with the CalculatedBalanceAspect.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait CalculatedBalanceAspect {
  this: MoneyTransferQueries =&gt;

  trait CalculatedBalance extends HasBalance {
    this: Account =&gt;

    lazy val balance = calculateBalance(id)
  }

}
</pre>
<p></p>
<p>
Again the familiar nested trait structure. The CalculatedBalance trait is able to compute the current balance of the account by executing a query (in this case the computation is done in the database). Summarized, the TransactionalMoneySourceProvider creates an object that pretends it is an account, is able to calculate and update its balance and knows the necessary steps to perform a money transfer. Nice. So these are the components relevant to DCI. The other components are more of a technical nature.
</p>
<p>
Lastly, let&#8217;s revisit the Registry trait.
</p>
<pre style="font-size:8pt;padding-left:1em;border-left:1px solid silver;">
trait Registry
  extends TransferMoneyContextFactory
  with TransactionalMoneySourceProvider
  with MoneySinkProvider
  with UpdatableAccountAspect
  with CalculatedBalanceAspect
  with MoneyTransferQueries
  with Database
  with Transactional
  with TransactionManagerComponent
  with SessionFactory
  with DataSourceComponent {

  val dataSource = {
    val ds = new AtomikosNonXADataSourceBean

    ds.setUniqueResourceName("MyDatabase")
    ds.setUser("root")
    ds.setPassword("admin")
    ds.setUrl("jdbc:mysql://localhost:3306/TMC")
    ds.setDriverClassName("com.mysql.jdbc.Driver")
    ds.setPoolSize(1)

    ds
  }

  val userTransaction = new UserTransactionImp

}
</pre>
<p></p>
<p>
This is the trait that welds everything together. It&#8217;s a concatenation of the outer traits we saw earlier. It is also the place where the actual DataSource and UserTransaction objects are instantiated. Mix in this trait in a client object and it is able to request and execute a new TransferMoneyContext instance.
</p>
<p>
That&#8217;s about it! Hope it all makes sense somehow.
</p>
<p>
The code is available on <a href="http://code.google.com/p/thomasmoerman/source/browse/#svn/trunk/blog01/src/com/thomasmoerman/dci/tmc">Google Code</a>.
</p>
<p>
The dependencies:</p>
<ul>
<li><a href="http://max-l.github.com/Squeryl/downloads.html">squeryl_2.8.0.Beta1-RC8-0.9.2.jar</a> &#8211; an impressive Scala DSL for SQL queries, recommended!</li>
<li><a href="http://sourceforge.net/projects/cglib/files/">cglib-2.2.jar</a></li>
<li><a href="http://forge.ow2.org/projects/asm/">asm-3.2.jar</a></li>
<li><a href="http://www.mysql.com/downloads/connector/j/">mysql-connector-java-5.1.10</a></li>
<li>Atomikos <a href="http://www.atomikos.com/Main/TransactionsEssentials">transactions-essentials-all.jar</a></li>
<li>jta.jar &#8211; the Java Transaction Api</li>
</ul>
<p>
You will need <a href="http://www.scala-lang.org/downloads">Scala 2.8.1</a> to compile it, SQueryl doesn&#8217;t work with Scala 2.7.x. There&#8217;s a schema generation script for creating the database. If you create the schema by hand, make sure to use the InnoDB database engine. The default one, MyIsam, does not support transactions (had me banging my head against the wall for a few hours, puzzled as to why my transactions wouldn&#8217;t work).
</p>
<p>
Feedback and suggestions are most welcome, don&#8217;t hesitate to drop me a line!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/thomasmoerman.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/thomasmoerman.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/thomasmoerman.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/thomasmoerman.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/thomasmoerman.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/thomasmoerman.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/thomasmoerman.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/thomasmoerman.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/thomasmoerman.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/thomasmoerman.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/thomasmoerman.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/thomasmoerman.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/thomasmoerman.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/thomasmoerman.wordpress.com/149/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=thomasmoerman.wordpress.com&amp;blog=5086294&amp;post=149&amp;subd=thomasmoerman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://thomasmoerman.wordpress.com/2010/03/11/dci-in-a-different-style/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d897498c4d077e10ae686c84169c0898?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Thomas</media:title>
		</media:content>
	</item>
	</channel>
</rss>
