<?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>The point is missed</title>
	<atom:link href="http://johlrogge.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://johlrogge.wordpress.com</link>
	<description>Museum of public mistakes and unfinished projects</description>
	<lastBuildDate>Fri, 26 Apr 2013 16:33:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='johlrogge.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>The point is missed</title>
		<link>http://johlrogge.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://johlrogge.wordpress.com/osd.xml" title="The point is missed" />
	<atom:link rel='hub' href='http://johlrogge.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Poju4s &#8211; an attempt to make JUnit a bit more Scala friendly</title>
		<link>http://johlrogge.wordpress.com/2011/03/11/poju4s-an-attempt-to-make-junit-a-bit-more-scala-friendly/</link>
		<comments>http://johlrogge.wordpress.com/2011/03/11/poju4s-an-attempt-to-make-junit-a-bit-more-scala-friendly/#comments</comments>
		<pubDate>Fri, 11 Mar 2011 16:52:04 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[junit]]></category>
		<category><![CDATA[poju4s]]></category>
		<category><![CDATA[repl]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=252</guid>
		<description><![CDATA[Recently I felt like going back to basics of testing in Scala. There are some fine testing frameworks for Scala that I recommend that you use. Never the less I started thinking about what it would be like to make JUnit more Scala-friendly rather than rolling an entire new framework. Since I came down with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=252&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Recently I felt like going back to basics of testing in Scala. There are some fine testing frameworks for Scala that I recommend that you use. Never the less I started thinking about what it would be like to make JUnit more Scala-friendly rather than rolling an entire new framework. Since I came down with the flu anyway I had some time when I was neither unconscious nor watching movies when I could toy with the idea. Long story short: I started the poju4s project on github <a href="https://github.com/johlrogge/poju4s" target="_blank">here</a>.</p>
<p>Poju4s obviously stands for &#8220;Plain old JUnit for Scala&#8221;</p>
<p>It is not much yet and it has some distance to go before being really useful but I think a few sparks of elegance have found their way into the code (or that is just the fever talking). Anyway, before I understand better than to make this stuff public. Without further due&#8230; here it is for what its worth:</p>
<h2><span id="more-252"></span>A quick tour</h2>
<p>At the moment I&#8217;m focusing on how to interact with JUnit from the REPL. Lets get a quick feel for what poju4s can do in this department. First of all fire up a REPL (I use SBT for this purpose):</p>
<p><a href="https://github.com/johlrogge/poju4s/wiki/start-repl.png"><img src="https://github.com/johlrogge/poju4s/wiki/start-repl.png" alt="start up a repl" width="640" height="66" /></a></p>
<p>Next import poju4s:</p>
<p><a href="https://github.com/johlrogge/poju4s/wiki/import-poju4s.png"><img src="https://github.com/johlrogge/poju4s/wiki/import-poju4s.png" alt="import poju4s._" width="640" height="52" /></a></p>
<p>Now we&#8217;re ready to run tests from the REPL. Lets start by running an invdividual test. This consists of two steps:</p>
<ol>
<li>Mix in an interaction point for poju4s</li>
<li>Run and render the output</li>
</ol>
<p>Here we use InteractionSpec that is a spec in poju4s itself:</p>
<p><a href="https://github.com/johlrogge/poju4s/wiki/run-single-test.png"><img src="https://github.com/johlrogge/poju4s/wiki/run-single-test.png" alt="val spec" width="640" height="104" /></a></p>
<p>What happened here? By mixing in Basics into our plain old JUnit test it is runnable from the REPL. Basics just contains default choices for poju4s such as outputting information to standard out, adding methods for finding and running tests. The next question is what <code>brief</code> is? Brief runs the tests one by one and outputs a green dot for each passing test and ends the run with a summary of the tests run. To make things a bit more interesting. Lets use an example spec with some tests that don&#8217;t succeed:</p>
<p><a href="https://github.com/johlrogge/poju4s/wiki/run-failing-tests.png"><img src="https://github.com/johlrogge/poju4s/wiki/run-failing-tests.png" alt="val ex" width="640" height="102" /></a></p>
<p>How pretty! :) Ok, as you see, since this is an experiment I can do whatever I want so adding silly colors came higher up on my list than things like being able to find and run all tests on the class path for instance :). For those poor bastards on some crippled terminal incapable of displaying such state of the art stuff like tty colors there is of course a way to avoid the tty control-codes to be sent:<a href="https://github.com/johlrogge/poju4s/wiki/run-with-and-without-colors.png"><img src="https://github.com/johlrogge/poju4s/wiki/run-with-and-without-colors.png" alt="val bw" width="640" height="194" /></a></p>
<p>As you can see <code>brief</code> is just a shortcut for <code>new BriefReport with Color</code></p>
<p>I could show how pending and fixed works but that requires a bit of a scenario, perhaps a video so I&#8217;ll save it for later. Feel free to browse the source.</p>
<p>The obvious missing feature now is to be able to glob or grep for tests to run. It&#8217;s being worked on.</p>
<p>Please tell me what you think so far. Should I even bother with making the binaries available as maven dependencies?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/252/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/252/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=252&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2011/03/11/poju4s-an-attempt-to-make-junit-a-bit-more-scala-friendly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>

		<media:content url="https://github.com/johlrogge/poju4s/wiki/start-repl.png" medium="image">
			<media:title type="html">start up a repl</media:title>
		</media:content>

		<media:content url="https://github.com/johlrogge/poju4s/wiki/import-poju4s.png" medium="image">
			<media:title type="html">import poju4s._</media:title>
		</media:content>

		<media:content url="https://github.com/johlrogge/poju4s/wiki/run-single-test.png" medium="image">
			<media:title type="html">val spec</media:title>
		</media:content>

		<media:content url="https://github.com/johlrogge/poju4s/wiki/run-failing-tests.png" medium="image">
			<media:title type="html">val ex</media:title>
		</media:content>

		<media:content url="https://github.com/johlrogge/poju4s/wiki/run-with-and-without-colors.png" medium="image">
			<media:title type="html">val bw</media:title>
		</media:content>
	</item>
		<item>
		<title>Why I don&#8217;t like Maven</title>
		<link>http://johlrogge.wordpress.com/2010/12/14/why-i-dont-like-maven/</link>
		<comments>http://johlrogge.wordpress.com/2010/12/14/why-i-dont-like-maven/#comments</comments>
		<pubDate>Tue, 14 Dec 2010 19:22:17 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[build tools]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[PMS]]></category>
		<category><![CDATA[build tool]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=210</guid>
		<description><![CDATA[More than two months ago I tweeted something like &#8220;As if this day didn&#8217;t already suck Maven 3 was released&#8221;. I got a reply from @kirean73 &#8220;Mind sharing your experiences with Maven?&#8221;. Fair question. As it takes more than 140 characters I decided to write a blog-post about it. And since I did not have [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=210&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>More than two months ago I tweeted something like &#8220;As if this day didn&#8217;t already suck Maven 3 was released&#8221;. I got a reply from @kirean73 &#8220;Mind sharing your experiences with Maven?&#8221;. Fair question. As it takes more than 140 characters I decided to write a blog-post about it. And since I did not have time to do it there and then I asked @kirean73 to remind me after a month had passed. A month ago I got the reminder but this post turned out to be really hard to write. Mostly because there is nothing seriously wrong with Maven&#8230;</p>
<p>I&#8217;ve been looking forward to write this post for some time. I really don&#8217;t like Maven but I realized that I don&#8217;t exactly know why. It will be useful to explore that. I don&#8217;t want this to be just another of the many maven rants out there. I&#8217;ll try to be fair but I also reserve the right not to think that some things are good  even if I can&#8217;t present a better alternative :) This is a subjective post.</p>
<p><span id="more-210"></span>I have yet to try Maven 3 though so things may have improved in that version.</p>
<p>When it comes to my experience with maven: My first experience with Maven must have been in 2004 or so. We investigated if we could use maven for a project we were starting. A few of us looked into it and found Maven to be a bit opaque &#8220;what does this thing actually do?&#8221;. Since then I have that part figured out of course but back then we stuck with our ant-script. That was probably the wrong choice. The feeling of an untransparent build-system still sticks somehow. I find that Maven is sometimes a bit hard to penetrate. I find that my maven usage is a bit google intensive and that maven is a little bit of a black box at times. I don&#8217;t know if it&#8217;s just me or if the Maven philososphy is a bit like &#8220;don&#8217;t you worry about your build, we take care of it. Just write mvn clean install and you&#8217;re good to go&#8221;. I&#8217;m outsourcing the details of my build to strangers.</p>
<p>I have used maven on and of through the years. Maven does a decent job most of the time. Can&#8217;t complain. Above all Maven gets you started quickly; just arrange a project so that Maven finds it&#8217;s way and your&#8217;re all set. Maven has also made wonders for the Java community when it comes to how to distribute your binaries. Before Maven there weren&#8217;t really any good options. In fact Maven is pretty decent over all so what&#8217;s the problem really? Maven stands in the way of innovation, Maven is not excellent, Maven assumes there is one right way to build for everyone, Maven does too much and sometimes bites off more than it can chew, Maven is hard to extend, Maven is a bit of a black box, Maven is slow, Maven is unreliable.</p>
<p>Ok, that was a lot of unfounded opionons. They all deserve to be motivated. I will explain what I mean with each of them one by one in reverse order:</p>
<h3>Maven is unreliable</h3>
<p>Ever deployed something you just built and found that for some reason your last change did not make it to the build? No? Good for you! An experience I know I share with many is that I build clean quite often with Maven. It happened a few times too many that I deployed something after a dreadfully long build-cycle just to find that everything was not in there in mysterious ways. Build clean, wait again.</p>
<p>I especially find Maven unreliable in combination with eclipse. The Maven plugin for eclipse can really mess up eclipse&#8217;s build-cycle. Infinite loops, persistent errormarkers that are never removed etc. You often get different results from the prompt and from within eclipse. It happened a few times that we had infinite loops of rebuilds in Eclipse (ok, I can&#8217;t prove that the loops were infinite since we did not wait for an infinity but we did see the same projects being rebuilt over and over again). The incremental build is about the only truly excellent feature of Eclipse and with Maven that pretty much goes down the drain. If there is one area where Maven really does suck it&#8217;s the eclipse integration. As usual though Maven gives you enough to make you think it&#8217;s worth the hassle. I&#8217;m not sure if it is.</p>
<h3>Maven is slow</h3>
<p>I heard that Maven 3 is more snappy. Good thing. Maven 2 is prettty awful performancewise. Why is that a problem? Slower builds, slower feedback. Slower feedback, worse quiality. Simple as that. Hardly anyone that use Maven does not know how to disable tests in a build just to make the build times bearable. While it&#8217;s fair to point out that most developers could learn a thing or two about how to make their tests run faster maven still has a pretty long ramp up time when it does not output any useful feedback to the developer.</p>
<h3>Maven is a bit of a black box</h3>
<p>This is one of my key issues with Maven. Partly the black boxyness is due to java as the language of choice for creating plug ins. In Buildr for example, if I want to know how something works I can just find the source and look at it (Buildr is made in ruby). If I get a stacktrace I can do the same. If there is a bug in the plugin I can fix it by editing the plugin source. If I feel like it, I can generate a patch and submit it so I won&#8217;t have to fix it again when upgrading.</p>
<p>While I can download the source for a maven plugin and do the same I also have to think about how to distribute my plugin to others after I figured out how to get the source and compile it. If I want to know how things work I will at the very least have to find the documentation for the plugin (if there is any good documentation to be found). Due to the maven strategy of plug-ins the documentation is fragmented and scattered.</p>
<p>Maven could compensate for this better. For instance when I run mvn &#8211;help it would be nice if I could somehow see what the build-cycle will look like. What will happen when. It would also be nice to get a listing of all pugins I have in my Repo and their options, heck, it would be cool if I could see a listing of all plugins available in any listed online repository. I bet there are plugins that can provide this information but then I would have to know about them. I could google but I think I should also be able to find out via mvn &#8211;help.</p>
<p>If I supply an option to maven like -Dmaven.test.skipp it would be pretty nice if Maven told me that maven.test.skipp is not a valid option. Why not tell me which options are available whenever I supply an unrecognized option? Sure, Maven can&#8217;t know which options plugins accept&#8230; or could it? At least maven could have been designed to be able to do this if it was considered important. But obviously it wasn&#8217;t&#8230; consiered important. Maven doesn&#8217;t even tell me about my alternatives when I run jetty:start. It would indeed be helpful to know my alternatives then and that one of them is jetty:run. In all projects that used maven I have heard a lot of questions among teammembers: &#8220;Do you remember how you do X in maven&#8230;&#8221;. We&#8217;re not talking about hard stuff. Just basics like how to run the integration tests. Symptomatic of an opaque system.</p>
<h3>Maven is hard to extend</h3>
<p>When it comes to plugins maven could do what SBT does. Just supply the source in the correct directory and they will be compiled when needed. It would simplify distribution, versioning of your whole build in one place etc. Of course with an interpreted language it all becomes even simpler and perhaps build tools should be done in interpreted languages (as is the case with Buildr and Gradle for instance). Given that the source is always available it&#8217;s much easier to learn those inner details that so easily get lost otherwise.</p>
<h3>Maven does too much and sometimes bites off more than it can chew</h3>
<p>I often feel that Maven is not satisfied with being my buildtool. It wants to be my whole development process. Maven dictates how I should do my versioning, packaging, deploying, directory structures you name it. There are very few areas of development where maven does not meddle. In this Maven sort of becomes a jack of many trades, master at none.  I think the maven plugin is what will kill Eclipse (ok, Eclipse wont die easily but the maven plugin totally takes over eclipse&#8217;s build and turns it into an average IDE from the early 2000s buildwise&#8230;). I often feel that Maven&#8217;s approach sort of works but is a bit dated and far too rigorous for the simple case&#8230; but hey&#8230; it sort of works so why complain?</p>
<h3>Maven assumes there is one right way to build for everyone</h3>
<p>I have to conform to Maven to a large degree and the compromise is always on my side. This is not by necessity a bad thing. The maven folks are right that all builds do essentially the same thing so why shouldn&#8217;t we standardize the process and solve it once and for all? To be honest, if Maven hadn&#8217;t beaten me to it I would probably have started (and if I know myself not finished) a project to create something like Maven. Maven&#8217;s idea makes total sense. The bad news is that there is no one true model for every problem. Even if it sounds totally crazy, the way you do your builds can be a competitive advantage. How you build is a key component to how you get your feedback and how often you can deploy. Your build tool is a strategic tool!</p>
<p>There are also ways in which Maven punishes totally valid choices. For instance in multi site it&#8217;s hard to get an aggregated view. If I chose to rely mostly on acceptance tests and not unit tests I can&#8217;t see how well every module in my system is covered by those tests. The test coverage reports with cobertura for instance are generated per module from the tests in each module. I cannot see how well module B is covered from module A. You may argue that this way of testing a system is not pure, good, cocher or whatever you call it but that would just be you imposing your opinion on everyone else. Maven should not make that choice for developers.</p>
<p>You may make the point now that it&#8217;s not Maven&#8217;s fault that the cobertura plugin works how it works. Fair, and it would be ok too if it would be a simple thing for me to adapt to my needs but as far as I&#8217;m aware there is no way I can express my needs in XML so that the cobertura plugin understands me. If it would be a simple thing to fix given that I have downloaded the source for the cobertura plugin I don&#8217;t know. Perhaps it&#8217;s in Mavens nature?</p>
<p>Another point is this thing with versions. What if I release every 10 minutes? I can really get a versioning nightmare in Maven. If I use snapshots for everything it can become a performance nightmare (so that I in efect can&#8217;t release every 10 minutes).</p>
<p>Couldn&#8217;t agree more that each build is not as unique as a snowflake. They all look pretty much the same from a long enough distance but so does snowflakes. Mavens build process works ok for everyone. Mavens process is optimized to suit average needs (and succeded quite well). On average Mavens model works well but it will just be average :)</p>
<p>All builds do essentially the same thing but the focus can make a world of difference.</p>
<h3>Maven is not excellent</h3>
<p>If Maven was the end of the road when it comes to builds; the ultimate one and only answer to how builds should be done then that would indeed be excellent. Unfortunately I doubt that there will ever be a one and only ultimate build solution out there. I have no doubt that Maven is a perfect match for some but I know it&#8217;s not a perfect match for everyone. It is all fine if Maven would recognize this but it doesn&#8217;t. Maven really tries to be the ultimate build solution and is bound to fail like every other tool that attempts this.</p>
<p>There are so many dimensions that you could optimize for and it&#8217;s highly unlikely that one tool would excel in all of them.</p>
<h3>Maven stands in the way of innovation</h3>
<p>Maven does a good enough job for most problems to have become popular. When a tool becomes as popular as Maven most people don&#8217;t even look at another tool. There are other initiatives out there that deserves more attention but teams play safe and choose the tool that everyone knows (though most people I have met know little more than how to type mvn clean install).</p>
<p>Maven is now an established tool. As such there is not much innovation happening at Maven&#8217;s initiative. Most new cool things like shells etc are created in other tools first.</p>
<p>I really can&#8217;t say why but I also have this strong feeling that the Maven team does not share my values when it comes to how I want to build my software. I have specific needs when it comes to testing, deploying etc. I don&#8217;t really believe in the one tool to rule them all idea.</p>
<p>If I&#8217;m going to outsource something as important as my whole build process to a team of people I don&#8217;t know I better feel that I trust that team to look after my needs. I don&#8217;t. Especially since the Maven team has already failed twice to create an excellent build tool. Why would they succeed a 3rd time? What indications are there that the Maven team learned any important lessons from Maven 1 and Maven 2 that will make Maven 3 the final one tool to rule them all?</p>
<p>So pardon me for not jumping up and sown with glee when I heard that Maven 3 was released. I&#8217;m sure I will find out soon enough just how excellent Maven 3 really is (wether I want to or not). As for my curiousity and learning that comes from it it is currently aimed at gradle and SBT.</p>
<p>I think Maven works fine but in the past some logical choices have been made that do no longer make sense (XML, a compiled language for plugins etc). Other tools have fixed those and it will be hard for Maven to change in fundamental ways (and Maven shouln&#8217;t, it does what it does). When I will have to use Maven I wont bitch about it but I will sure keep my options open. Will you?</p>
<p>Cheers!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/210/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/210/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=210&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2010/12/14/why-i-dont-like-maven/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
		<item>
		<title>There are no best practices</title>
		<link>http://johlrogge.wordpress.com/2010/07/22/there-are-no-best-practices/</link>
		<comments>http://johlrogge.wordpress.com/2010/07/22/there-are-no-best-practices/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 18:28:11 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[methods]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=200</guid>
		<description><![CDATA[Last week I had a good retweet day. As always when that happens, I said something cocky and over-simplified. I blame 140 characters; the perfect excuse to simplify things to become more edgy. This time the tweet was: I hate best practice. If you follow best practice you will end up with Maven, SVN and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=200&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="font-family:arial, helvetica, sans-serif;">Last week I had a good retweet day. As always when that happens, I said something cocky and over-simplified. I blame 140 characters; the perfect excuse to simplify things to become more edgy. This time the tweet was:</span></p>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">I hate best practice. If you follow best practice you will end up with Maven, SVN and programming in java (the language) #rest_my_case</span></p></blockquote>
<p><span style="font-family:arial, helvetica, sans-serif;">I was promptly corrected by @jchyip (Jason Yip):</span></p>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">@johlrogge That&#8217;s equating &#8220;common practice&#8221; to &#8220;best practice&#8221; which is a very common failure mode. Popularity != best option.</span></p></blockquote>
<p><span style="font-family:arial, helvetica, sans-serif;">He couldn&#8217;t be more right. In fact, I have often felt that what is marketed as best practice is often common practice with a more attractive label. The two are confused a lot. It sort of makes sense too, I mean &#8211; if everyone is doing it, it must work. Right? If it wasn&#8217;t the best then why would everyone do it? Granted it will probably work just fine, but will probably not be the best, so don&#8217;t call it that. Assuming that excellent software development is rare, then best practices should also be pretty uncommon. Given this, you probably shouldn&#8217;t be doing what everyone else is doing, if you are going for &#8220;best&#8221;.</span></p>
<h2><span style="font-family:arial, helvetica, sans-serif;"><span id="more-200"></span>So what is a best practice, really?</span></h2>
<p><span style="font-family:arial, helvetica, sans-serif;">First some definitions from googling define:&#8221;best practice&#8221;</span></p>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">A process, technique or innovative use of resources that has a proven record of success in providing significant improvement in cost, schedule, quality, performance, safety, environment or other measurable factors that impact the health of an organization &#8211; </span><a href="http://www.google.com/url?q=http://www.reliableplant.com/Glossary&amp;sa=X&amp;ei=q1JITJGUIYWUjAerlrW7Dg&amp;ved=0CBMQpAMoAw&amp;usg=AFQjCNHdfI94cSa2nvJhoAJMXtLRRbPwjw" target="_blank"><span style="font-family:arial, helvetica, sans-serif;">www.reliableplant.com/Glossary</span></a></p></blockquote>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">The optimal solution to a business problem. &#8211; </span><a href="http://www.google.com/url?q=http://campuspol.chance.berkeley.edu/GlossaryofTerms.doc&amp;sa=X&amp;ei=q1JITJGUIYWUjAerlrW7Dg&amp;ved=0CBIQpAMoAg&amp;usg=AFQjCNF0owXML15vwLKuMYUQcXo5wGPN6A" target="_blank"><span style="font-family:arial, helvetica, sans-serif;">campuspol.chance.berkeley.edu/GlossaryofTerms.doc</span></a></p></blockquote>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">A way or method of accomplishing a business function or process that is considered to be superior to all other known methods. -</span><a href="http://www.google.com/url?q=http://www.qaproject.org/methods/resglossary.html&amp;sa=X&amp;ei=q1JITJGUIYWUjAerlrW7Dg&amp;ved=0CBQQpAMoBA&amp;usg=AFQjCNEpBFakjhDSRIcci9y5e2-16VnEhw" target="_blank"><span style="font-family:arial, helvetica, sans-serif;">www.qaproject.org/methods/resglossary.html</span></a></p></blockquote>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">A best practice is a , method, process, activity, incentive, or reward that is believed to be more effective at delivering a particular outcome than any other technique, method, process, etc. when applied to a particular condition or circumstance. &#8211; </span><a href="http://www.google.com/url?q=http://en.wikipedia.org/wiki/Best_practice&amp;sa=X&amp;ei=q1JITJGUIYWUjAerlrW7Dg&amp;ved=0CBAQpAMoAA&amp;usg=AFQjCNFOedjiHxNZ67kLYyVFrDiqLF38fQ" target="_blank"><span style="font-family:arial, helvetica, sans-serif;">en.wikipedia.org/wiki/Best_practice</span></a></p></blockquote>
<p><span style="font-family:arial, helvetica, sans-serif;">Those quotes do not all say exactly the same thing. Some of them appear to be narrowed down to a context such as business processes or organization issues. Others are just plain naive like &#8220;the optimal solution to a business problem&#8221;. It is important to realize that a best practice is context bound. I got a reply to one of my tweets about that from Viktor Klang</span></p>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">@johlrogge &#8220;Best&#8221; implies that all use-cases are equal in both resources and restrictions, which never is the case. What is being measured?</span></p></blockquote>
<p><span style="font-family:arial, helvetica, sans-serif;">As we have all experienced over and over, what may work brilliantly for someone else may not work so well for you. As Viktor points out, we must be aware of the context in which a practice is supposedly &#8220;best&#8221;. All things considered, the number of contexts for software development is a very large number. That makes it hard to provide any useful general advice at all. The context must always be considered and measuring the correct things is a science of it&#8217;s own (I&#8217;d even say that for software it&#8217;s an unsolved problem so some of those definitions cannot apply to software, in my humble opinion).</span></p>
<p><span style="font-family:arial, helvetica, sans-serif;">But that is not the only problem with best practices; &#8220;best&#8221; implies there is nothing better. Isn&#8217;t there? I&#8217;d say that if we look at what we are doing today and find that it&#8217;s exactly what we were doing 2 years ago, it probably means that we don&#8217;t spend enough time looking for </span><span style="font-family:arial, helvetica, sans-serif;">better practices</span><span style="font-family:arial, helvetica, sans-serif;">.</span></p>
<h2><span style="font-family:arial, helvetica, sans-serif;">Looking for better practices</span></h2>
<p><span style="font-family:arial, helvetica, sans-serif;"><span style="font-weight:normal;">&#8220;Best&#8221; implies &#8220;ultimate&#8221;. Way too often the term &#8216;best practice&#8217; is associated with something someone is trying to sell you: &#8220;my method is founded solely on best practices&#8221; (like ITIL). I think that is why we don&#8217;t call our best practices &#8220;currently accepted theories&#8221; which would be more science-like in the sense that they invite better theories to replace them. To illustrate, try this sentence: &#8220;we use best practice until a better best practice replaces it&#8221;. Sounds kind of silly, doesn&#8217;t it? (That is right: good, better, best; only a hobbit would add &#8220;bestestest&#8221; to that)</span></span></p>
<p><span style="font-family:arial, helvetica, sans-serif;">I found </span><a href="http://www.humantruth.info/science.html" target="_blank"><span style="font-family:arial, helvetica, sans-serif;">this page</span></a><span style="font-family:arial, helvetica, sans-serif;"> that describes the scientific method. It goes on and on about how good theories &#8220;invite replacement&#8221; like in this quote from the conclusion:</span></p>
<blockquote><p><span style="font-family:arial, helvetica, sans-serif;">Any system of thought that proclaims itself to be &#8220;ultimate&#8221; or beyond correction is dogmatic and wrong: The best theories are the ones that happily give way to better theories.</span></p>
<p><span style="font-family:arial, helvetica, sans-serif;">The worst are the ones that do not budge and refuse to admit new evidence that disputes them. They become stagnant and outdated.</span></p>
<p><span style="font-family:arial, helvetica, sans-serif;">Science is revolutionary because it accepts new facts, new evidence and new thought. New knowledge acquired from the scientific method frequently changes society with technology and ideas. It is refreshing, challenging and above all the scientific method continues to dynamically improve its description of the world.</span></p></blockquote>
<p><span style="font-family:arial, helvetica, sans-serif;">I currently subscribe to many theories of software development. Like &#8211; the theory of continuos refactoring, the theory of continuos integration, the theory of release early and often, the theory of self-verifying specs  and so on. I use, support and promote them because they, among other theories, are the best I know of when it comes to developing software. But even such fine theories cannot be prescribed without a context. Releasing early and often may not be a good idea, if what you get payed for is upgrades to new versions of your software. It may not be a good idea if you are unable to verify the quality of your system as fast as you can deploy new versions of it. Also, no matter how good a theory seems to be &#8211; compared to what you were doing yesterday, always assume there is a better way (that may even be the complete opposite of what you&#8217;re currently doing).</span></p>
<p><span style="font-family:arial, helvetica, sans-serif;">I&#8217;ll sum up my point here in a tweetable way: </span><span style="font-family:arial, helvetica, sans-serif;"><em>Don&#8217;t settle for best, always look for better.</em></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/200/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=200&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2010/07/22/there-are-no-best-practices/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
		<item>
		<title>Loggingtools in Scala</title>
		<link>http://johlrogge.wordpress.com/2009/06/27/loggingtools-in-scala/</link>
		<comments>http://johlrogge.wordpress.com/2009/06/27/loggingtools-in-scala/#comments</comments>
		<pubDate>Sat, 27 Jun 2009 17:20:51 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[timing]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=178</guid>
		<description><![CDATA[UPDATE: As John pointed out in the comments the trait did not really work as expected. I updated it with the code I actually have in my project. How I ended up posting a different thing on my blog I don&#8217;t know but it sort of has to be me :). This code is tested [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=178&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><em>UPDATE: As John pointed out in the comments the trait did not really work as expected. I updated it with the code I actually have in my project. How I ended up posting a different thing on my blog I don&#8217;t know but it sort of has to be me :). This code is tested with slf4j-api-1.5.0. I think some newer version makes it possible to do this without the temporary objects involved in the form of arrays. I will look into that later.</em></p>
<p>My pet-project is becoming more and more <em>Scalafied</em> and I&#8217;m starting to wonder why I ever thought it was important that I should be able to use it from java-applications. Given my detachment from Java some mental barriers are falling and I am adding new strategies to my <em>active </em>toolbox. Today I created some simple traits that I thought would be worth exploring in a blog.</p>
<p>Here we go, logging with <a href="http://www.slf4j.org/">slf4j</a> is something I&#8217;ve done a lot. I found myself sprinkling a lot of this around in my code:</p>
<pre class="brush: java; title: ; notranslate">
import org.slf4j.{Logger, LoggerFactory}
...
class SomeClass {
   private val log = LoggerFactory.getLogger(getClass)
   def aMethodThatLogs  {
      log.debug(&quot;This is a value: {}&quot;, 4711)
   }
}
</pre>
<p>Nothing new (unless you never saw slf4j before in which case you should check it out now wether you program in Scala or Java. The code so far is not dependent on scala other than syntax-wise.)</p>
<h2>What I keep forgetting about</h2>
<p>Scala has traits, it&#8217;s easy to forget that traits are more than just interfaces. Over the years I&#8217;ve gotten pretty used to not being able to add any generic functionality other than via composition or inheritance.</p>
<p>Thinking out of the java-box I created this little trait:</p>
<pre class="brush: java; title: ; notranslate">
import org.slf4j.{Logger, LoggerFactory}

trait Log {
 private val log = LoggerFactory.getLogger(getClass)

 def trace(message:String, values:Any*) = 
     log.trace(message, values.map(_.asInstanceOf[Object]).toArray)
 def trace(message:String, error:Throwable) = log.trace(message, error)
 def trace(message:String, error:Throwable, values:Any*) = 
     log.trace(message, error, values.map(_.asInstanceOf[Object]).toArray)

 def debug(message:String, values:Any*) = 
     log.debug(message, values.map(_.asInstanceOf[Object]).toArray)
 def debug(message:String, error:Throwable) = log.debug(message, error)
 def debug(message:String, error:Throwable, values:Any*) = 
     log.debug(message, error, values.map(_.asInstanceOf[Object]).toArray)

 def info(message:String, values:Any*) = 
     log.info(message, values.map(_.asInstanceOf[Object]).toArray)
 def info(message:String, error:Throwable) = log.info(message, error)
 def info(message:String, error:Throwable, values:Any*) = 
     log.info(message, error, values.map(_.asInstanceOf[Object]).toArray)

 def warn(message:String, values:Any*) = 
     log.warn(message, values.map(_.asInstanceOf[Object]).toArray)
 def warn(message:String, error:Throwable) = log.warn(message, error)
 def warn(message:String, error:Throwable, values:Any*) = 
     log.warn(message, error, values.map(_.asInstanceOf[Object]).toArray)

 def error(message:String, values:Any*) = 
     log.error(message, values.map(_.asInstanceOf[Object]).toArray)
 def error(message:String, error:Throwable) = log.error(message, error)
 def error(message:String, error:Throwable, values:Any*) = 
     log.error(message, error, values.map(_.asInstanceOf[Object]).toArray)
}
</pre>
<p>Using it is now a matter of:</p>
<pre class="brush: java; title: ; notranslate">
import johlrogge.Logging
...
class SomeClass extends Object with Logging {
   def aMethodThatLogs  {
      debug(&quot;This is a value: {}&quot;, 4711)
   }
}
</pre>
<p>It&#8217;s not a huge difference but I kind of like the <em>with Logging</em> and the lack of boilerplate code in the class-body.<br />
I also like that I can drop the <em>log.</em> part of the logging.</p>
<h2>Traits are on the menu</h2>
<p>Of course this my wetted my appetite for traits. And it didn&#8217;t take long before an opportunity arose. How often have you written code like this in java:</p>
<pre class="brush: java; title: ; notranslate">
long startTime = System.currentTimeMillis();
AValue value = doSomethingTimeConsuming(parameter);
log.debug(&quot;SomethingTimeConsuming took {}ms to complete&quot;, System.currentTimeMillis()-startTime);
return value;
</pre>
<p>I was about to repeat the process in Scala when I thought: function&#8230; pass by name&#8230; and then&#8230; <strong>TRAIT</strong>!</p>
<p>To make a long story short: Enter Timing:</p>
<pre class="brush: java; title: ; notranslate">
trait Timing {
  def time[T, R](f: =&gt; T, res:(T, Long) =&gt; R):R = {
    val startTime = System.currentTimeMillis
    res(f, System.currentTimeMillis - startTime)
  }
}
</pre>
<p>How this beast came to be:</p>
<ol>
<li>I realized that the timing-code in the java-example could measure anything given that anything given that anything was executable. And thats what pass by name is for.</li>
<li>I realized that sometimes you want to have the timed value, sometimes you want to log it as a side effect. So, a second pass by name function made sense. The res-function that takes the timing-value and does whatever it likes with it.</li>
<li>You may want to return the timervalue, the result of the timed function, both or something completely different. So I made the result type generic and different from the result-type of the timed function.</li>
</ol>
<p>How to use it:</p>
<pre class="brush: java; title: ; notranslate">
import johlrogge.Logging
...
class SomeClass extends Object with Logging
                               with Timing {
   def aMethodThatTimesAndReturns =  {
      time(timeConsumingMethod(4711),
              debugMs(&quot;The timeConsumingMethod generated {} in {}ms&quot;, _:SomeValue, _))
   }

   def debugMs[T](message:String, result:T, spent:Long):T = {
    debug(message, result, spent)
    result
  }

   def timeConsumingMethod(interval:Int):SomeValue =  {
       Thread.sleep(interval);
       new SomeValue
   }
}
</pre>
<p>Pretty neat. Of course you can compose all kinds of pre-packaged res-methods. The point is that time becomes reusable and you don&#8217;t have to log. You could for instance update and return a data-set for a graph that you&#8217;re plotting somewhere else in your code. We have abstracted away timing.</p>
<h2>Just so you know</h2>
<p>If I would mind that anyone cut and pasted the code I wrote in this post and even make money from it (like thats going to happen) I wouldn&#8217;t post it on the net. I hope that the code is useful and/or inspires someone in some way. So use it however you want and have fun!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/178/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=178&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2009/06/27/loggingtools-in-scala/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
		<item>
		<title>Do you dampen or amplify?</title>
		<link>http://johlrogge.wordpress.com/2009/03/30/do-you-dampen-or-amplify/</link>
		<comments>http://johlrogge.wordpress.com/2009/03/30/do-you-dampen-or-amplify/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 21:45:40 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=173</guid>
		<description><![CDATA[Today I rediscovered a thought I had months ago and forgot about. I was talking to a team-member about software development in general and frameworks  and processes in particular. What I&#8217;m about to write is just a theory and a thought model that seems useful to me. If you are looking for hard facts then [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=173&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Today I rediscovered a thought I had months ago and forgot about. I was talking to a team-member about software development in general and frameworks  and processes in particular. What I&#8217;m about to write is just a theory and a thought model that seems useful to me. If you are looking for hard facts then this post is not for you (sorry).</p>
<p>I have this idea that all practices we apply are somewhere on a scale from dampening to amplifying. Did I hear a WTF? I&#8217;ll try to explain&#8230;</p>
<p><span id="more-173"></span></p>
<h2>Dampening and amplifying &#8211; some background</h2>
<p>I use the terms dampening and amplifying metaphorically. If you studied electronics you know that you often use a combination of dampening[attenuation] and amplifying to separate the desired signal from undesired noise. Think of a radio, you tune in to your favorite radio-show at 104.8 MHz FM. Part of what happens in your radio is that the receiver suppresses, dampens all frequencies except 104.8 (+- tolerance) MHz and amplifies the 104.8 signal so that it can be decoded into music or whatever you listen to.</p>
<p>You could get away with doing dampening exclusively, like when your signal is strong enough but you want to filter out undesired noise. The opposite is also true, if you have  a signal that has no noise, you could just amplify it. This is of course extremely simplified but works as an illustration.</p>
<p>Now imagine software development as a signal, the desired signal is continuous customer satisfaction being deployed regularly. Or to simplify things, delivering excellent software to our target group efficiently. You want to tune your team into that channel. How do you do it?</p>
<h2> Dampening bad behavior</h2>
<p>It seems to me that a lot of processes start close to the extreme assumption that people have a desire to do bad things and unless you prevent them from doing that&#8230; they will. Using our radio-metaphor this would be an environment with extreme static.</p>
<p>If your starting assumptions are close to this extreme it makes sense to look for dampening practices and introduction of control. Such dampening practices can be implemented as process, technically or both. An example would be a tollgate system where at each tollgate a select few, typically non team members,decide wether or not whatever is being built can pass to the next tollgate or be rejected.</p>
<p>Technical enforcements could be the use of various tools. I am a Java-programmer and I find that Java often has a dampening strategy. Remove things that people find difficult in order to keep the language easy to use; at least for the vast majority of programmers. The downside of course is that programmers that would be comfortable and more efficient with those advanced features are also deprived of them.</p>
<p><strong><em>Keywords:</em></strong><em> prevent, reject, suppress.</em></p>
<h2>Amplifying good behavior</h2>
<p>At the other extreme we assume that people have a desire to do good things and with freedom and opportunity that is what they will do. Again, using our radio-metaphor this would be an environment with no static.</p>
<p>If your starting assumptions are close to this extreme it makes sense to look for amplifying practices. The signal is clean, turn the volume up to ten. Amplifying practices tend to align views and remove obstacles. An example would be communicating a clear goal in terms of purpose and business value so that everyone knows what is developed for what purpose. Another example is removal of obstacles: the team says that the off the shelf product is not adequate for their needs, lose it! The team needs some infrastructure, get it! Some company internal process prevents the team from being effective, fix it! (either the process or the teams views)</p>
<p>As some of you may know I have been playing with Scala recently. The philosophy of Scala is very different from Java. Most programmers will find a lot of the things in Scala difficult, but hey, they can learn them and if they do they will be more effective so why <a href="http://james-iry.blogspot.com/2009/03/operator-overloading-ad-absurdum.html">should they be removed</a>? What about dynamic languages? What if you choose a more powerful language than Java and instead of removing all &#8220;difficult things&#8221;, even for the ones that know them, and instead educate as necessary? That would be amplifying.</p>
<p><strong><em>Keywords: <span style="font-weight:normal;">enable, accept, encourage</span></em></strong></p>
<h2>Remove interference</h2>
<p>A third option is to remove interference. Removing interference is deceptively similar to dampening but with the exception that you don&#8217;t suppress the unwanted noise, you find the source and remove it (or move away from it). In some hospitals there are still signs that you must keep your cell-phone switched off since it can interfere with sensitive medical equipment (at least that is the reason that is given on the signs). Interestingly enough the hospitals trust complete strangers with this great responsibility. Flight crews do too. You have to put your toothpaste in a plastic bag but something so lethal as a cell-phone they kindly ask you to switch off :)</p>
<p>Going back to our team, perhaps we don&#8217;t have to be so careful making everything harmful impossible to do. Perhaps sometimes we can assign some great power and freedom to each other and simply agree on how to and how not to use that power&#8230; then turn the volume up to ten&#8230;</p>
<p><strong><em>Keywords:</em></strong><em> eliminate.</em></p>
<p>I will probably have reason to revisit this subject with more concrete examples later but this post is already hideously long. Until I get around to that (with my regular posting frequency it will be sometime next year), please read about the party planning exercise <a href="http://ellnestam.wordpress.com/2009/03/17/what-about-scrumand/">here</a> and think about how it relates to the dampening/amplifying metaphor.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/173/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=173&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2009/03/30/do-you-dampen-or-amplify/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
		<item>
		<title>More Scala and SWT</title>
		<link>http://johlrogge.wordpress.com/2009/02/26/more-scala-and-swt/</link>
		<comments>http://johlrogge.wordpress.com/2009/02/26/more-scala-and-swt/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 22:13:08 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[SWT]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=163</guid>
		<description><![CDATA[In general when you have a good idea you&#8217;re not alone. I started getting traffic from another blog. Dave Orme has developed an interesting framework: XScalaWT. According to the acknowledgements in his blog he found some of my ideas useful to his framework. I haven&#8217;t tried it yet, it looks similar to my DSL but [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=163&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In general when you have a good idea you&#8217;re not alone. I started getting traffic from another blog. Dave Orme has developed an interesting framework:<a href="http://www.coconut-palm-software.com/the_new_visual_editor/doku.php?id=blog:simplifying_swt_with_scala" target="_blank"><span style="color:#000000;text-decoration:none;"> </span></a><a href="http://bitbucket.org/djo/xscalawt/" target="_blank">XScalaWT.</a> According to the acknowledgements in his blog he found some of my ideas useful to his framework. I haven&#8217;t tried it yet, it looks similar to my DSL but his framework is much more complete and he solved the interaction part too. Check it out, it looks very promising!</p>
<p>Also, to my great surprise someone uploaded my source to github <a href="http://wiki.github.com/mikegr/gsl-swt" target="_blank">here</a>. There is even a Maven pom now to build and run the thing.</p>
<p>I thought I&#8217;d share the links since the showed up in my statistics. Enjoy :)</p>
<p><em>Update: Randin pointed out that the link to xscalawt was broken so I changed the destination. Also Randin thought <a href="http://github.com/nafg/ScalaSWT/tree/master">this link</a> seemed interestong so I provide it here aswell.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/163/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=163&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2009/02/26/more-scala-and-swt/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
		<item>
		<title>Buy me a Beer :)</title>
		<link>http://johlrogge.wordpress.com/2009/01/28/buy-me-a-beer/</link>
		<comments>http://johlrogge.wordpress.com/2009/01/28/buy-me-a-beer/#comments</comments>
		<pubDate>Wed, 28 Jan 2009 22:29:23 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[SWT]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=158</guid>
		<description><![CDATA[/* * The file is licenced under Revision 42 of the Beerware Licence. * &#60;joakim.ohlrogge[at]agical.com&#62; wrote this file. As long as you retain this * notice you can do whatever you want with this stuff. If we meet some day, * and you think this stuff is worth it, you can buy me a beer [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=158&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<pre>/*
 * The file is licenced under Revision 42 of the Beerware Licence.
 * &lt;joakim.ohlrogge[at]agical.com&gt; wrote this file. As long as you retain this
 * notice you can do whatever you want with this stuff. If we meet some day,
 * and you think this stuff is worth it, you can buy me a beer in return.
 * -- Joakim Ohlrogge
 */</pre>
<p><span id="more-158"></span>I decided to make the source for my <a href="http://johlrogge.wordpress.com/2009/01/06/making-swt-shine-with-scala/" target="_blank">DSL</a> available under the <a href="http://en.wikipedia.org/wiki/Beerware" target="_blank">beerware</a> license. I choose beerware for several reasons:</p>
<ol>
<li>I don&#8217;t have the energy to turn his into a full blown traditional open source project.</li>
<li>I believe that libraries without restrictions would make making GUI&#8217;s in Scala more appealing if you only need to convince whoever you need to convince that using Scala is a good idea and not having to deal with additional licensing issues imposed by some guy on a power-trip (me)</li>
<li>I would need a hand if this should turn into something really useful and I invite any of you to without restrictions take this initiative further and perhaps even tweak it into your own library with or without my help.</li>
<li>This project has been about learning for me, I hope it can help others learn too from it.</li>
</ol>
<p>That I give it away like this does not mean that I&#8217;m not interested in what you do with it or use it for. I&#8217;m very curious so if you have the energy to do so, keep me posted! But you don&#8217;t have to.</p>
<p>I attach a zip with the code in it&#8217;s current state. It&#8217;s perhaps not pretty but it&#8217;s what I have so far. Enjoy <a href="http://agical.com/resources/code/gsl-swt.zip">the code</a>!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/158/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=158&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2009/01/28/buy-me-a-beer/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
		<item>
		<title>Drying up widget creation</title>
		<link>http://johlrogge.wordpress.com/2009/01/14/drying-up-widget-creation/</link>
		<comments>http://johlrogge.wordpress.com/2009/01/14/drying-up-widget-creation/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 01:12:27 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[learning]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Refactor]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=143</guid>
		<description><![CDATA[I continue to be amazed how Scala lets me keep my code DRY (if I care to do it the tools are there, I just need to look for them). One of the reasons that Scala allows this more than Java is that Scala supports functional programming. One thing that makes Scala interesting is that Scala [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=143&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I continue to be amazed how Scala lets me keep my code <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself" target="_blank">DRY</a> (if I care to do it the tools are there, I just need to look for them). One of the reasons that Scala allows this more than Java is that Scala supports <a href="http://en.wikipedia.org/wiki/Functional_programming" target="_blank">functional programming</a>. One thing that makes Scala interesting is that Scala blends Functional Programming and Object Oriented programming. This is often overwhelming but it really keeps the tools you need close at hand.</p>
<p>To start with I had to be torn kicking and screaming from my beloved object orientation. I was told I suffer from the <a href="http://en.wikipedia.org/wiki/Stockholm_syndrome">Stockholm syndrome</a> which was quite a hilarious way to put it. Especially since I live in Stockholm and was immediately comforted by the same person with the words &#8220;I suffer from it too, I still love C++&#8221;. So I thought maybe leaving my comfort zone is not so bad?</p>
<p>Yesterday it payed off and I experienced a kind of flow that was new to me in Scala. I thought I&#8217;d share that experience here step by step. Don&#8217;t expect to be blown away by my Scala-skills, If you want to be impressed in that way there are other blogs :) What follows is a real world example of  things coming together into a moment of productiveness. I guess another real world example of applying Scala to a problem could not harm?<span id="more-143"></span></p>
<p>In a <a href="http://johlrogge.wordpress.com/2009/01/06/making-swt-shine-with-scala/" target="_blank">previous post</a> I wrote about how to make a DSL for creating SWT-guis in Scala. My source of inspiration was Glimmer. One thing that is obviously lacking in that example is some interaction with other code (in any direction) so I set out to solve that. I have come up with a few different ways and one of the several ways, more on them in a different post, I would like to support is to observe one or several other objects from the GUI. That requires an update mechanism. Some way to tell the created GUI to update itself. I have that solved too but I want to zoom in on one interesting step in the solution. A refactoring. I have ended up with a lot of small snippets like this:</p>
<pre class="brush: java; title: ; notranslate">
trait Labels {
    def label(setups:(Label =&gt; Unit)*)(parent:Composite) = {
        val label = new Label(parent, SWT.NONE)
        setups.foreach(setup =&gt; setup(label))
    }
 

    def progressBar(setups:(ProgressBar =&gt; Unit)*)(parent:Composite) = {
        val progress = new ProgressBar(parent, SWT.NONE)
        setups.foreach(setup =&gt; setup(progress))
    }
}
</pre>
<p>Basically, I can create a progress bar, a label and both of them can be manipulated with 0 or more <em>setups</em>. Before we continue, let&#8217;s rewrite the first of the methods in a more verbose way so that even I would have understood that method 3 months ago:</p>
<pre class="brush: java; title: ; notranslate">
def label(setups:(Label =&gt; Unit)*):(Composite) =&gt; Unit = {
   def createWidget(parent:Composite):Unit = {
      val label = new Label(parent, SWT.NONE)
      setups.foreach(setup =&gt; setup(label))
   }
   createWidget
}
</pre>
<p>This is exactly the same as the first example but more verbose and explicit. The double parameter-lists is syntactic sugar in Scala to return a function. Once you get used to it&#8217;s easier to read IMO so I have adopted it. It should be pretty clear now that the evaluation will occur in two steps:</p>
<ol>
<li>provide a list of setups (functions that takes a label as their only argument). This step will return a function that takes a composite (the createWidget function).</li>
<li>Interestingly enough the returned function is &#8220;charged&#8221; with the setups and they will be invoked in the setups.foreach part when the composite, parent is provided. Not before, not after.</li>
</ol>
<p>Now to the problem I wanted to solve. There is obvious duplication between the two functions in the first code-listing. The most obvious duplication (as I saw it) was the setup part. Lets extract a function for setting up the label:</p>
<pre class="brush: java; title: ; notranslate">
    def label(setups:(Label =&gt; Unit)*)(parent:Composite) = {
        val label = new Label(parent, SWT.NONE)
        performSetup(label, setups)
    }
    def performSetup(target:Label, setups:Seq[Label =&gt;; Unit]) = { 
        setups.foreach(setup =&gt; setup(target)) 
    }
</pre>
<p>This step really did not gain us that much. One thing to notice is that we pass the variable argumet setups into a parameter of type <em>Seq. </em>So variable arguments are just sequences.<em> </em>There is not an awful lot less code and we can&#8217;t use the performSetup method for progress-bars. Lets fix that. If you look at the performSetup-function there is not anything specific to labels in that function. So what type should it be? It&#8217;s really not important as long as it&#8217;s the same type that the functions in setups take. You won&#8217;t get a more obvious case for generics, and a pretty basic flavour also. Lets change the label to a generic type:</p>
<pre class="brush: java; title: ; notranslate">
    def performSetup[T](target:T, setups:Seq[T =&gt; Unit]) = { 
      setups.foreach(setup =&gt; setup(target)) 
    }
</pre>
<p>That was easy, now we can use the performSetup method in both the label and progressBar functions:</p>
<pre class="brush: java; title: ; notranslate">
    def label(setups:(Label =&gt; Unit)*)(parent:Composite) = {
        val label = new Label(parent, SWT.NONE)
        performSetup(label, setups)
    }
    def progressBar(setups:(ProgressBar =&gt; Unit)*)(parent:Composite) = {
        val progress = new ProgressBar(parent, SWT.NONE)
        performSetup(progress, setups)
    }
    def performSetup[T](target:T, setups:Seq[T =&gt; Unit]) = { 
        setups.foreach(setup =&gt; setup(target)) 
    }
 </pre>
<p>Ok, slightly better than what we started with but we still have obvious duplication. The only thing that really differ between the two functions (besides the names)is the creation of different widgets. If we could parameterize the creation of widgets we would have a reusable template. Lets try by copying and changing the label function. I will rename it to createWidget and then try to remove the label-specifics:</p>
<pre class="brush: java; title: ; notranslate">
    def createWidget(setups:(Label =&gt;; Unit)*)(parent:Composite) = {
        val label = new Label(parent, SWT.NONE)
        performSetup(label, setups)
    }
    def performSetup[T](target:T, setups:Seq[T =&gt; Unit]) = { setups.foreach(setup =&gt; setup(target)) }
</pre>
<p>So, we obviously have to remove the creation of the label. As a first step lets make a factory-function and insert it in the parameterList:</p>
<pre class="brush: java; title: ; notranslate">
    def createWidget(factory:Composite =&gt;Label)(setups:(Label =&gt; Unit)*)(parent:Composite) = {
        val label = factory(parent)
        performSetup(label, setups)
    }
    def performSetup[T](target:T, setups:Seq[T =&gt; Unit]) = { setups.foreach(setup =&gt; setup(target)) }
</pre>
<p>By inserting an extra set of parameters we have created:</p>
<ol>
<li>A function that takes a factory that creates lables that&#8230;</li>
<li>returns a function that takes setups that&#8230; (note that at this point we have an equivalent function to our old label-function)</li>
<li>returns a function that takes a composite&#8230;</li>
</ol>
<p>We can now update our label function to step use 2 if we just have a factory. Time to bring out a new trick from the bag of tricks:</p>
<pre class="brush: java; title: ; notranslate">
    def label = createWidget(new Label(_, SWT.NONE))_
    def createWidget(factory:Composite=&gt;Label)(setups:(Label =&gt; Unit)*)(parent:Composite) = {
 val label = factory(parent)
 performSetup(label, setups)
 }
    def performSetup[T](target:T, setups:Seq[T =&gt; Unit]) = { setups.foreach(setup =&gt; setup(target)) }
 </pre>
<p>Ehhhh, what happened? Well, at first the underscores in Scala are a bit confusing and above we use them in two places.<br />
First there is an underscore in the Label&#8217;s constructor where we used to pass in parent. SWT.NONE is still where it used to be. What we have done is to leave the parent-parameter to be filled in later. If you think of it, a constructor is in essence a function that returns a new instance of some class. In the Label-case: (Composite, Int) =&gt; Label.</p>
<p>Pre fill the params part: <em>new Label(_, SWT.NONE)</em> and we have a <em>(Composite) =&gt; Label</em> which is exactly what we need for the first argument of our createWidget function.</p>
<p>The second _ is a placeholder for &#8220;the rest&#8221;, which is <em>(setups:(Label =&gt; Unit)*)(parent:Composite)</em>.<br />
That parameter-list should look familiar from our first version of the label-function.<br />
Now we want to use our createWidget function for our progressBar function aswell. Lets make it generic, we don&#8217;t want to create only labels:</p>
<pre class="brush: java; title: ; notranslate">
def createWidget[T](factory:Composite =&gt; T)(setups:T =&gt; Unit*)(parent:Composite) = {performSetup(factory(parent), setups)}
</pre>
<p>I took the liberty to also inline the val label &#8211; statement. Sweet, lets use it for progressbars as well:</p>
<pre class="brush: java; title: ; notranslate">
    def label = createWidget(new Label(_, SWT.NONE))_
    def progressBar = createWidget(new ProgressBar(_, SWT.NONE))_
    def createWidget(factory:Composite=&gt;Label)(setups:(Label =&gt; Unit)*)(parent:Composite) = {
 val label = factory(parent)
 performSetup(label, setups)
 }
    def performSetup[T](target:T, setups:Seq[T =&gt; Unit]) = { setups.foreach(setup =&gt; setup(target)) }
 </pre>
<p>Not too bad. Since we have other traits with widgets than just Labels we want to be able to reuse this pattern there as well. For that purpose we move the functions to a new object, Framework</p>
<pre class="brush: java; title: ; notranslate">
object Framework {
	def createWidget[T](factory:Composite =&gt; T)(setups:T =&gt; Unit*)(parent:Composite) = {
		performSetup(factory(parent), setups)
	}
	def performSetup[T](target:T, setups:Seq[T =&gt; Unit]) = {
		setups.foreach(setup =&gt; setup(target))
	}
}
</pre>
<p>That leaves us with the final result for our Labels trait looking like this:</p>
<pre class="brush: java; title: ; notranslate">
import Framework._  
trait Labels {     
   def label = createWidget(new Label(_, SWT.NONE))_     
   def progressBar = createWidget(new ProgressBar(_, SWT.NONE))_ 
}
</pre>
<p>Not too bad, definatly better than what I started with anyway :)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/143/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=143&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2009/01/14/drying-up-widget-creation/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
		<item>
		<title>Making SWT shine with Scala</title>
		<link>http://johlrogge.wordpress.com/2009/01/06/making-swt-shine-with-scala/</link>
		<comments>http://johlrogge.wordpress.com/2009/01/06/making-swt-shine-with-scala/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 20:48:48 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[SWT]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=131</guid>
		<description><![CDATA[At Agile 2008 I was calmly coding together with Daniel Brolund in the open space area. We were interrupted by a guy that asked us if we did any coding in Ruby and if we did he will hold a lightning-talk about a framework he had put together to create SWT-gui:s using JRuby. Interestingly enough [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=131&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>At Agile 2008 I was calmly coding together with <a href="http://danielbrolund.wordpress.com/" target="_blank">Daniel Brolund</a> in the open space area. We were interrupted by a guy that asked us if we did any coding in Ruby and if we did he will hold a lightning-talk about a framework he had put together to create SWT-gui:s using JRuby. Interestingly enough I had thought about how GUI-coding could probably be improved in a language such as Ruby so I reluctantly stopped what I was doing and watched the lightning talk. This was the first time I ever saw <a href="http://www.eclipse.org/glimmer/" target="_blank">Glimmer</a> and it totally blew me away!</p>
<p><span id="more-131"></span></p>
<h3>It must be possible to do in Scala!</h3>
<p>I had already started playing with Scala and I thought it would be a cool experiment to see if I could do something similar in Scala. After all, scala is a pretty expressive language.</p>
<p>I made the first attempt a few months ago and I think that qualifies as a failure. I got something to work but all the mutable state and redundant classes I had to create bothered me big time.</p>
<p>I showed what I did to colleague and I got some pointers on how to make my code more function-oriented and hence get rid of some redundancy and mutable state. But my lacking knowledge of Scala and FP prevented me from finishing the task back then.</p>
<h3>Success!</h3>
<p>Yesterday I gave it another shot and it took me only an evening to make this code:</p>
<pre class="brush: java; title: ; notranslate">
        shell(
            text(&quot;User Profile&quot;),
            composite (
                gridLayout(2, false),
                group (
                    text(&quot;Name&quot;),
                    gridLayout(2, false),
                    gridData(FILL, FILL, true, true),
                    label(text(&quot;First&quot;)), edit(text(&quot;Bullet&quot;)),
                    label(text(&quot;Last&quot;)), edit(text(&quot;Tooth&quot;))
                ),
                group (
                    gridData(FILL, FILL, true, true),
                    text(&quot;Gender&quot;),
                    radioButton (text (&quot;Male&quot;), selected),
                    radioButton (text (&quot;Female&quot;))
                ),
                group (
                    gridData(FILL, FILL, true, true),
                    text(&quot;Role&quot;),
                    checkBox (text(&quot;Student&quot;), selected),
                    checkBox (text(&quot;Employee&quot;), selected)
                ),
                group (
                    text(&quot;Experience&quot;),
                    rowLayout,
                    gridData(FILL, FILL, true, true),
                    spinner(selection(5)), label {text (&quot;years&quot;)}
                ),
                button (
                    text(&quot;save&quot;),
                    gridData(RIGHT, CENTER, true, true)
                ),
                button (
                    text(&quot;close&quot;),
                    gridData(LEFT, CENTER, true, true)
                )
           )
        )
</pre>
<p>Display this:</p>
<p><img class="alignnone size-full wp-image-138" title="SWT scala screenshot" src="http://johlrogge.files.wordpress.com/2009/01/scalascreenshot.png?w=700" alt="SWT scala screenshot"   /></p>
<p> </p>
<p>Pretty cool! I will admit that I have gracefully stolen most of the ideas from Glimmer. Even the example above is a slightly modified Glimmer-example. I will probably go over it a couple of times to see what I can improve from a Scala perspective. I particulary dislike the <em>gridData </em>functions. I think there is room for improvement there.</p>
<h3>How does it work?</h3>
<p>The general pattern is simple. Take a look a the group element in the code above. Group is implemented like this:</p>
<pre class="brush: java; title: ; notranslate">
def group(setups:(Group =&gt; Unit)*)(parent:Composite) = {
    val group = new Group(parent, SWT.NONE)
    rowLayout(group);
    setups.foreach(setup =&gt; setup(group))
}
</pre>
<p>If you, like me when I saw my first Scala examples, have some dificulty with the double parameterlist notation it is a shorthand in Scala for returning a function. So the above is a function that takes a variable number of functions that take a <em>Group</em> as the only parameter.<em> Unit </em>in Scala is equivalent to <em>void</em> in java. The group-function will return a function that takes a <em>Composite</em>, parent, as it&#8217;s only parameter.</p>
<p>The cool thing about this is that you can pass the first set of parameters (the variable number of functions that takes a Group and return Unit) and save the returned function for later evaluation. When the composite <em>parent</em> is later passed what will happen is the following:</p>
<ul>
<li>A new Group widget will be created with <em>parent</em> as parent</li>
<li>as a default the layout of the group will be set to <em>row layout</em>, this may be overridden in the next step.</li>
<li>Each function in setup will be applied to the newly created group.</li>
</ul>
<p>Remember, the setup-functions take a group as a parameter so they can perform whatever action on the Group. You have full freedom to do whatever can be done with a group in any of those functions.</p>
<p>The variable length argument is one of the missing pieces I needed to solve the puzzle, I failed to find information about variable arguments via google. Ok, I did not spend an awful lot of time trying&#8230;</p>
<h3>What does one of those setup-methods look like then?</h3>
<p>Let&#8217;s start with something simple, the label:</p>
<pre class="brush: java; title: ; notranslate">
 def label(setups:(Label =&gt; Unit)*)(parent:Composite) = {
    val label = new Label(parent, SWT.NONE)
    setups.foreach(setup =&gt; setup(label))
}
</pre>
<p>The pattern repeats itself, lazy creation of the label onto the parent composite (for instance a <em>Group</em>) and the posibility to furter customize the label. Now comes the next secret I had to learn in order to solve the puzzle. Take a look at the text-function:</p>
<pre class="brush: java; title: ; notranslate">
def text[T &lt;: {def setText(txt:String)}](txt:String)(subject:T) = {
    subject.setText(txt)
}
</pre>
<p>Pretty straight forward right? Look again at the generic type <em>T. </em>I don&#8217;t know what that construct is called, I call it declarative duck-typing, you know <em>if it walks like a duck and quacks like a duck it&#8217;s a duck!</em></p>
<p>Here I declare that T can be any type that has a function named <em>setText</em> that takes a <em>String</em> as an argument and returns nothing. If I did not declare this then the <em>subject.setText(txt) </em>line would not compile. But I&#8217;m getting ahead of myself. Why did I need to find this construct?</p>
<p>Several different widgets in SWT has a <em>setText-</em>method, for instance, shell has a setText, label has a setText etc but some controls do not. There is no common interface between all different widgets that has a setText-method. That makes things a bit tricky, my first attempt was to overload different setText-functions, one for label, one for shell etc&#8230; This was not only tedious, it didn&#8217;t work since the difference between all of those overloaded methods is in the parameterlist of the returned function. Luckily, this little inconvenience forced me to discover this NEAT feature of the Scala-type system. I&#8217;m happy I did.</p>
<h3>In conclusion</h3>
<p>I was able to make a DSL that is very comparable to glimmer which was my original goal. I was able to make the whole thing initialize lazily. Basically I just build a tree of constructing functions and then I sort of light the fuse by passing a shell to the root of that tree and the GUI is created. I did not have to introduce any mutable state other than what is already mutable in SWT. I have a feeling that this approach is very extendable. Maybe the GUI is a good place to introduce Scala in Java-projects? My feeling is that Scala would slowly eat it&#8217;s way in to other parts of the system from there :)</p>
<p>Perhaps this is a good candidate for an open source project? Would you want to use it?</p>
<a class="DiggThisButton DiggMedium" href="http://digg.com/submit?url=http%3A%2F%2Fjohlrogge.wordpress.com%2F2009%2F01%2F06%2Fmaking-swt-shine-with-scala%2F&amp;title=Making+SWT+shine+with%26nbsp%3BScala"></a>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/131/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=131&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2009/01/06/making-swt-shine-with-scala/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>

		<media:content url="http://johlrogge.files.wordpress.com/2009/01/scalascreenshot.png" medium="image">
			<media:title type="html">SWT scala screenshot</media:title>
		</media:content>
	</item>
		<item>
		<title>Scala Nugget &#8211; Pattern matching and Lists</title>
		<link>http://johlrogge.wordpress.com/2008/10/06/scala-nugget-pattern-matching-and-lists/</link>
		<comments>http://johlrogge.wordpress.com/2008/10/06/scala-nugget-pattern-matching-and-lists/#comments</comments>
		<pubDate>Mon, 06 Oct 2008 22:27:19 +0000</pubDate>
		<dc:creator>johlrogge</dc:creator>
				<category><![CDATA[scala]]></category>
		<category><![CDATA[Case]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Nugget]]></category>
		<category><![CDATA[pattern matching]]></category>
		<category><![CDATA[Refactor]]></category>

		<guid isPermaLink="false">http://johlrogge.wordpress.com/?p=109</guid>
		<description><![CDATA[I was whining recently about how my scala-code is java in poor disguise. I started reading the scala by example pdf that also comes with the scala installation. I just read some interesting things about lists and pattern-matching that gave me an idea how to &#8220;scalafy&#8221; the following scjava-code: def importResource(name:String, resource:Resource):Unit = { log.debug("importing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=109&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I was whining recently about how my scala-code is java in poor disguise. I started reading the <a href="http://www.scala-lang.org/sites/default/files/linuxsoft_archives/docu/files/ScalaByExample.pdf">scala by example pdf</a> that also comes with the scala installation. I just read some interesting things about lists and pattern-matching that gave me an idea how to &#8220;scalafy&#8221; the following <em>scjava</em>-code:</p>
<p><span id="more-109"></span></p>
<pre>  def importResource(name:String, resource:Resource):Unit = {
    log.debug("importing " + name + " into " + root)
    val path = pathOf(name)
    createResource(path.toList)(resource)
  }

  private def createResource(nodes:List[String])(resource:Resource) =  {
    val directory = nodes.dropRight(1).foldLeft(root)((directory, name) =&gt; {
      if(name.equals("")) {
        directory
      }
      else {
        val directoryOption:Option[AbstractDirectory] = directory.getDirectory(name)
        directoryOption.getOrElse({
          val subDir = directory.createDirectory(name) match {
                         case result:AbstractDirectory =&gt; result
                       }
          directory.add(subDir)
          subDir
        })
      }
    })
    directory.createIfNewer(nodes.last, _:Resource)
  }</pre>
<p>If it&#8217;s not crystal clear to you what the code does. Here is an overview:</p>
<ul>
<li>The first method takes a name and a resource</li>
<li>The name is split up into it&#8217;s path-elements</li>
<li>The path is passed to the createResource method that will create all directories that does not yet exist on the way to the resource and finally return a function that takes a resource as input and creates it in the already given directory.</li>
</ul>
<p>A big issue I have with the code is the createResource-method. It simply is very hard to name it. createAllDirectoriesAndReturnResourceCreatingMethod would illustrate better how smelly that method really is. I have an idea on how to refactor this with scalas pattern matching. This is the new version (after some red/green bar cycles):</p>
<pre>  def importResource(name:String, resource:Resource):Unit = {
    log.debug("importing " + name + " into " + root)
    val path = pathOf(name)
    createResource(path.toList, root, resource)
  }

  private def createResource(nodes:List[String],
                             directory:AbstractDirectory,
                             resource:Resource) {
    nodes match {
      case head :: Nil =&gt; directory.createIfNewer(head, resource)
      case "" :: tail =&gt; createResource(tail, directory, resource)
      case head :: tail =&gt; {
        val subDir = directory.getDirectory(head).getOrElse {
          val result = directory.createDirectory(head) match {
                                   case dir:AbstractDirectory =&gt; dir
                                 }
          directory.add(result)
          result}
        createResource(tail, subDir, resource)
      }
      case nil =&gt;
    }
  }</pre>
<p>The first thing that strikes me about the second version is the unbalance between the different cases. The <em>head :: tail</em> case is not exactly a one-liner&#8230; but it should be. This smells like feature envy. We could ask the directory to getOrCreateDirectory and it would read much better. But that is another refactoring. First let&#8217;s go through this one:<br />
One thing I did not first get in scala is how you can iterate through lists using pattern-matching. In order to get how that works it is important to realise one thing about scalas lists:</p>
<p><em>List(&#8220;a&#8221;, &#8220;b&#8221;, &#8220;c&#8221;, &#8220;d&#8221;)</em></p>
<p>is equivalent to</p>
<p><em>&#8220;a&#8221; ::(&#8220;b&#8221; ::(&#8220;c&#8221; ::(&#8220;d&#8221; ::(Nil))))</em></p>
<p>which due to the right associativityness  of :: is equivalent to:</p>
<p><em>&#8220;a&#8221; :: &#8220;b&#8221; :: &#8220;c&#8221; :: &#8220;d&#8221; :: Nil</em></p>
<p>Or plain english: Lists are not flat structures, lists are recursive structures. What that means in practical terms is that given any element in the list it is very easy to split the list at that element into <em>head</em> (the current element) and <em>tail</em> (the rest of the elements.</p>
<p>For instance, given the element <em>&#8220;b&#8221;</em> above, <em>head</em> will be <em>&#8220;b&#8221;</em> and <em>tail</em> will be <em>&#8220;c&#8221; :: &#8220;d&#8221; :: Nil</em>.</p>
<p>Ok, not that hard. Now to the cool part: The :: <em>operator </em>is a <em>case class</em> which in short means that it can be used in pattern matching:</p>
<p><em>&#8220;a&#8221; :: &#8220;b&#8221; :: &#8220;c&#8221; :: Nil match { case h :: t =&gt; println(head +&#8221; -&gt; &#8221; +tail); &#8230;}</em></p>
<p>will assign &#8220;a&#8221; to the variable h and <em>&#8220;b&#8221; :: &#8220;c&#8221; :: nil</em> to the variable <em>t</em></p>
<p>We can now understand the cases above. In pseudocode:</p>
<pre>  private def createResource(nodes:List[String],
                             directory:AbstractDirectory,
                             resource:Resource) {
    nodes match {
      case head :: Nil =&gt;  <em>//the last element of the list, create the resource using head as a name</em>
      case ""   :: tail =&gt; <em>// special case, an empty directory name. Skip to the next name:
                           // createResource(tail, directory, resource)
      </em>case head :: tail =&gt; <em>//head will be a directory-name that we use to get or create the 
                           //nextDirectory that is used with tail to call ourselves recursively:
                           // </em>createResource<em>(tail, </em><em><em>nextDirectory</em></em><em>, resource)
    </em>  case nil =&gt; <em>//no more elements to traverse
</em>    }
  }<em>
</em></pre>
<p>I&#8217;m far from done with the refactoring. I want to get rid of the special case of &#8220;&#8221; to begin with and as mentioned above remove some feature-envy but I think that the cases are more readable than the original code. At least in terms of where the problems lie in terms of special cases and bloated cases. Of course, it&#8217;s just an opinion and I reserve the right to change my mind tomorrow :)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/johlrogge.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/johlrogge.wordpress.com/109/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=johlrogge.wordpress.com&#038;blog=708994&#038;post=109&#038;subd=johlrogge&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://johlrogge.wordpress.com/2008/10/06/scala-nugget-pattern-matching-and-lists/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd08bc92b02d3c676e67cb818ce19e05?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">johlrogge</media:title>
		</media:content>
	</item>
	</channel>
</rss>
