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

<channel>
	<title>Schauderhaft &#187; scala</title>
	<atom:link href="http://blog.schauderhaft.de/tag/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.schauderhaft.de</link>
	<description>Softwaredevelopment, Projectmanagement, Qualitymanagement and all things &#34;schauderhaft&#34;</description>
	<lastBuildDate>Sun, 05 Feb 2012 20:46:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to write your own Matchers with ScalaTest</title>
		<link>http://blog.schauderhaft.de/2011/10/02/how-to-write-your-own-matchers-with-scalatest/</link>
		<comments>http://blog.schauderhaft.de/2011/10/02/how-to-write-your-own-matchers-with-scalatest/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 19:06:38 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[matcher]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[scalatest]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=936</guid>
		<description><![CDATA[I just love the assertion syntax of ScalaTest. It&#8217;s easy to read and easy to write and looks like this: 23 should be &#62;= (12) Even if you know nothing about ScalaTest it should be easy to understand whats this assertion is about. But what when your assertions get more complex? Like this: new Frog().color.getGreen() [...]]]></description>
			<content:encoded><![CDATA[<p>I just love the assertion syntax of ScalaTest. It&#8217;s easy to read and easy to write and looks like this:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">23 should be &gt;= (12)</div>
</li>
</ol>
</div>
<p>Even if you know nothing about ScalaTest it should be easy to understand whats this assertion is about. But what when your assertions get more complex? Like this:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">new Frog().color.getGreen() should be &gt;= (80)</div>
</li>
</ol>
</div>
<p>Although this assertion certainly isn&#8217;t rocket science, it is not so easy to see what is getting tested here. How about this?</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">new Frog() should &nbsp;be_Greenish</div>
</li>
</ol>
</div>
<p>Now that is nice and clean and perfectly possible with ScalaTest. Of course we have to implement <tt>be_Greenish</tt> since ScalaTest doesn&#8217;t care so much about Frogs being green. Luckily the implementation is simple:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">object be_Greenish extends Matcher[Frog]{
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def apply (left : Frog) : MatchResult =
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; MatchResult(left.color.getGreen &gt;= 80, &quot;The frog is not green enough&quot;, &quot;The frog contains to much green&quot; )
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p><tt>should</tt> expects a <tt>Matcher</tt> of what ever comes before should. So <tt>be_greenish</tt> must be a <tt>Matcher[Frog]</tt>. The <tt>Matcher</tt> has one method which we need to implement: <tt>apply</tt> and it takes a <tt>Frog</tt> as an argument and returns a <tt>MatchResult</tt> which we can construct using boolean signifying if the frog passed the test represented by the matcher or not, and the messages to use when the test failed and when the test succeed but actually was supposed fail. This makes it possible to negate assertions using <tt>not</tt>. There is also a variation of <tt>MessageResult</tt> which takes two more messages as arguments. Those are used when assertions get combined using <tt>and</tt> or <tt>or</tt>. In these cases the failure message of a Matcher are only part of a longer sentence and therefore probably shouldn&#8217;t start with a capital letter. </p>
<p>This approach would works really nice if we were testing some behavior of our frog. Like its ability to jump. We could create matcher that allow us to write things like:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">new Frog() should &nbsp;jump (far)</div>
</li>
</ol>
</div>
<p><tt>jump</tt> would be a method taking a <tt>Distance</tt> as an argument and returning a <tt>Matcher[Frog]</tt>. <tt>far</tt> would be an instance of <tt>Distance</tt>.</p>
<p>But we really just want to test a property. This causes the weird name &#8216;be_Greenish&#8217; with the odd underscore. There is a easier and therefore better way to write these matchers: <tt>BePropertyMatcher</tt>:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">object greenish extends BePropertyMatcher[Frog]{
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def apply(left : Frog) = BePropertyMatchResult(left.color.getGreen &gt;= 80, &quot;greenish&quot;)
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>This allows us to write test like: </p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">new Frog(Color.blue) &nbsp;should not &nbsp;be(greenish)</div>
</li>
</ol>
</div>
<p>So whenever you write tests where the assertions are not trivial and possibly repeated in multiple tests consider to implement your own matchers. It&#8217;s easy and makes for way easier to read tests.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/10/02/how-to-write-your-own-matchers-with-scalatest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manipulating Test Execution with ScalaTest</title>
		<link>http://blog.schauderhaft.de/2011/08/28/manipulating-test-execution-with-scalatest/</link>
		<comments>http://blog.schauderhaft.de/2011/08/28/manipulating-test-execution-with-scalatest/#comments</comments>
		<pubDate>Sun, 28 Aug 2011 19:01:54 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[rules]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[scalatest]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=906</guid>
		<description><![CDATA[My favorite feature in the JUnit are Rules. With Rules you can manipulate the execution of your test, by wrapping your own code around the test execution. I have used this for setting up databases for test, making sure they execute in the EDT, limiting legal test execution time and for set up and tear [...]]]></description>
			<content:encoded><![CDATA[<p>My favorite feature in the <a href="/2011/07/24/rules-in-junit-4-9-beta-3/">JUnit are Rules</a>. With Rules you can manipulate the execution of your test, by wrapping your own code around the test execution. I have used this for setting up <a href="/2011/03/13/testing-databases-with-junit-and-hibernate-part-1-one-to-rule-them/">databases for test</a>, making sure they <a href="/2010/08/15/use-cases-for-junit-rules/">execute in the EDT</a>, limiting legal test execution time and for set up and tear down of various other resources.</p>
<p>So naturally when working with <a href="/2010/12/26/testing-with-scala/">ScalaTest</a> I pretty soon wanted to have something equivalent to Rules. While you find not much when searching for &#8216;Rules ScalaTest&#8217;, it is actually quite easy to implement.</p>
<p>No matter what kind of tests you write with ScalaTest, at the end of the day the method <tt>def withFixture(aTest : NoArgTest)</tt> will get called with your test to execute. &#8216;Your test&#8217; means in case of a FunSuite test the stuff between the curly braces that you pass to the <tt>test</tt> method.</p>
<p>The implementation of <tt>withFixture</tt> will finally execute your test. So all you have to do in order to get the equivalent of a JUnit Rule is to override <tt>withFixture</tt>. Lets give it a try:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">class ExampleTest extends FunSuite {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override def withFixture(test : NoArgTest){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;before&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; super.withFixture(test)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;after&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;example test&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;succeding test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;example failing test&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;failing test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; fail(&quot;embrace failure&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>This produces the following output on the console:</p>
<pre>

before
succeding test
after

before
failing test
</pre>
<p>As you can see, if you want to do stuff after the test, you better put it in a <tt>finally</tt> block, so it gets executed no matter if the test fails or not.</p>
<p>While this works, we don&#8217;t want to explicitly override <tt>withFixture</tt> every time we need our &#8216;rule&#8217;. The solution to this is to extract it into a trait:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">trait ExampleRule extends AbstractSuite {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; self : Suite =&gt;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override abstract def withFixture(test : NoArgTest) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;before&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; try {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ExampleRule.super.withFixture(test)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; } finally {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; println(&quot;after&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">class Example2Test extends FunSuite with ExampleRule {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;example test&quot;) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;succeding test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;example failing test&quot;) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;failing test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; fail(&quot;embrace failure&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>The trait extends AbstractSuite, which makes <tt>withFixture</tt> available. It has a selftype of Suite, in order to ensure it gets only mixed into test suites.</p>
<p>So how does this solution compare to the implementation of a JUnit Rule? With a Junit Rule we have to create the actual Rule plus a Statement instance. With ScalaTest we only extend a single trait. Also since all this is standard Scala inheritance an no reflection involved, so it is pretty strait forward to find out how this works. While how and why a Rule gets executed is kind of tricky from the source alone. Finally you can explicitly control the order in which your traits apply, by controlling the order in which you put them in the extends clause:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">trait Example3Rule extends AbstractSuite {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; self : Suite =&gt;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override abstract def withFixture(test : NoArgTest) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;3 before&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; try {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Example3Rule.super.withFixture(test)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; } finally {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; println(&quot;3 after&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">@RunWith(classOf[JUnitRunner])
</div>
</li>
<li class="li1">
<div class="de1">class Example3Test extends FunSuite &nbsp;with Example3Rule with ExampleRule{
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;example test&quot;) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;succeding test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;example failing test&quot;) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;failing test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; fail(&quot;embrace failure&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<pre>
before
3 before
succeding test
3 after
after

before
3 before
failing test
3 after
after
</pre>
<p>With Junit Rules there is currently no ready to use way to do this, but a feature to achieve this <a href="https://github.com/stefanbirkner/junit/commit/3584c44bedd8705f30dda4f4213fa45655b998c7">is in development</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/08/28/manipulating-test-execution-with-scalatest/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Usage Patterns of Scala Traits</title>
		<link>http://blog.schauderhaft.de/2011/08/21/usage-patterns-of-scala-traits/</link>
		<comments>http://blog.schauderhaft.de/2011/08/21/usage-patterns-of-scala-traits/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 11:28:10 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[trait]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=901</guid>
		<description><![CDATA[One of the many cool features in Scala are traits. traits are like a mixture of abstract classes and interfaces: You can &#8216;implement&#8217; as many of them as you want just as with interfaces, but they can also contain implementation, which makes them similar to abstract classes. You also can&#8217;t instantiate a trait on its [...]]]></description>
			<content:encoded><![CDATA[<p>One of the many cool features in Scala are traits. traits are like a mixture of abstract classes and interfaces: You can &#8216;implement&#8217; as many of them as you want just as with interfaces, but they can also contain implementation, which makes them similar to abstract classes. You also can&#8217;t instantiate a trait on its own, so there is another similarity to abstract classes.</p>
<p>While digging my way through various libraries I found a couple of different usage patterns, how traits are getting used. Here is what I found so far:</p>
<div><strong>The Introvert Trait</strong>: These are traits that aren&#8217;t intended for changing the behavior of a class for outside clients of the class, but for the code inside the class itself. They often make an internal DSL available. An example are the <a href="http://www.scalatest.org/scaladoc-1.6.1/#org.scalatest.matchers.ShouldMatchers">ShouldMatchers</a> in <a href="http://www.scalatest.org/">ScalaTest</a>. You mix in this trait into your test class in order to use syntax like <tt>someValueToTest should be (23)</tt> The problem with this kind of usage is that you can&#8217;t really control the scope in which your trait/DSL applies. So if you want to use two such traits which happen do define the same method or operator with different meaning you are in trouble. Often you can replace the trait with an object which you import. Since scoping rules apply for imports as well you can control much better which part of your class have access to that object. I see two reasons why this kind of trait makes sense: It makes the presence of the trait/DSL very obvious since it is right next in the beginning of the class declaration, while an import statement might get overlooked. The other reason is, if you want to fool around with <a href="http://www.scala-lang.org/node/124">self types</a>, i.e. you want to limit the kind of classes the trait can get mixed in to or if you want to reference that class.</div>
<div><strong>Classes with dissociative identity disorder:</strong> Sometimes things are two things at once. A wooden chair might be furniture as well as fuel for an oven. A square is a rectangle and a rhombus. This works perfectly with traits. While in java you would often have two interface, but one class implementing both, you can easily split the implementation between two traits in scala. Nice. But you should carefully check if these two behaviors  actually belong in a single class, or if you are violating the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a>.<br />
<strong></strong></div>
<div><strong>The Jigsaw Puzzle Trait:</strong> In this pattern traits are used to separate different aspects of a responsibility in a very fine grained manner. The results are traits that are really hard to understand on their own. Actually they are easy to understand since the often only consist of half a dozen lines of code. What is difficult is to understand how this can be useful in any way. Yet if done right it allows do reduce code duplication to an absolute minimum. The best example for this usage is the <a href="/2010/12/19/the-scala-collection-api-sucks-or-is-it-a-work-of-beauty/">Scala collection API</a>. It consists of a huge number of traits, that get assembled in different ways in order to form the different classes.<br />
<strong>The Steam Roller Trait</strong>: What happens when you drive a steam roller over something small, let&#8217;s say an interface? It gets very wide. This is another technique used in the Scala Collection API. The trait defines a self type, either using another trait or a structural type and defines lots of other stuff based on that interface. This completely solves one of the basic challenges in Java interface design: If you define wide interfaces, i.e. interfaces with lots of methods, it increases the chances for users to find the method they need. On the other hand those poor bastards who have to implement such an interface have a lot of work to do. If you have any doubts how powerful this pattern is, check out <a href="http://www.scala-lang.org/docu/files/collections-api/collections-impl.html">how little code you have to write</a> in order to create a new collection implementation which nicely integrates with all the others and has hundreds of methods just like all the other Scala collections as well.</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/08/21/usage-patterns-of-scala-traits/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How Scala changed the way I think about my Java Code</title>
		<link>http://blog.schauderhaft.de/2011/08/14/how-scala-changed-the-way-i-think-about-my-java-code/</link>
		<comments>http://blog.schauderhaft.de/2011/08/14/how-scala-changed-the-way-i-think-about-my-java-code/#comments</comments>
		<pubDate>Sun, 14 Aug 2011 12:22:17 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=885</guid>
		<description><![CDATA[Some people advocate their preferred language as the only way to enlightenment and productivity boosts way in the two digit percentage range compared to another language in the same category. I don&#8217;t believe it. (It&#8217;s probably true when you compare things like Java and Assembler, but few do that) There are others that tell you [...]]]></description>
			<content:encoded><![CDATA[<p>Some people advocate their preferred language as the only way to enlightenment and productivity boosts way in the two digit percentage range compared to another language in the same category. I don&#8217;t believe it. (It&#8217;s probably true when you compare things like Java and Assembler, but few do that)</p>
<p>There are others that tell you the language doesn&#8217;t matter at least not between languages like Scala and Java. I think they are wrong as well. The reason is: Although I don&#8217;t actually use Scala during my day job it does affect my Java Coding. Here are some of the things I noticed.</p>
<ul>
<li>I appreciate immutability. I was aware for a long time of the benefits of immutability. But in Java using immutable data structures is so clumsy that I only used this approach in small areas, like rather simple value objects. But now I find my self more often tempted to use an immutable data structure even for relatively complex things.</li>
<li>Lots of small classes. Classes in Scala are unbelievable small. It&#8217;s easy to write a single page of code with half a dozen classes in it if you count the &#8216;class&#8217;, &#8216;object&#8217; and &#8216;trait&#8217; keywords and even more when you look at what the Scala compiler creates from closures and similar. Although creating a class is much more work in Java I find myself thinking much strict about the single responsibility principle, resulting in more smaller classes, which are easier to test.</li>
<li>Thinking more in DSLs. Scala is great for creating internal DSLs. Lots of libraries use that approach for designing their APIs and I do it in my little projects as well. Java is pretty useless for DSLs. But there are things you can do. Even if it is simple stuff like method chaining. I use that a lot lately, especially when testing is concerned, because here readability of code is even more important then with normal code.</li>
<li>I pretty much gave up on Java Generics. After seeing what is possible with a good type system, even when the compiled code runs on the same JVM as Java, made me also see the severe limitations of Java Generics. Before that I tended to think its just me who is to stupid. While this assumption is often true. Many things I tried to do in the past with Java Generics just can&#8217;t work, because Java is lacking the necessary power (e.g. covariance and contravariance). So I drop generics from my code as soon as more then one type parameter gets involved.</li>
</ul>
<p>So go ahead and learn a new language. Even if you can&#8217;t use it in your normal job. You still will learn useful stuff. But be warned. I might as well make you hate parts of your day job:</p>
<p>I really, really hate semicolons, primitives, arrays and collection APIs without higher order functions. And switching on Strings is a joke.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/08/14/how-scala-changed-the-way-i-think-about-my-java-code/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Input Validation with Scala and Swing</title>
		<link>http://blog.schauderhaft.de/2011/07/03/input-validation-with-scala-and-swing/</link>
		<comments>http://blog.schauderhaft.de/2011/07/03/input-validation-with-scala-and-swing/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 21:03:56 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[moreThanProperties]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=831</guid>
		<description><![CDATA[An important part of any kind of GUI is input validation. If you are living in the Java world, you probably know about Bean Validation and its reference implementation Hibernate Validation. Using Bean Validation you sprinkle your code with annotations in order to declare the maximum size attributes, if they may be Null and many [...]]]></description>
			<content:encoded><![CDATA[<p>An important part of any kind of GUI is input validation. If you are living in the Java world, you probably know about Bean Validation and its reference implementation Hibernate Validation. Using Bean Validation you sprinkle your code with annotations in order to declare the maximum size attributes, if they may be Null and many more. It looks like this:</p>
<div class="geshi no java">
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; @NotNull</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; @Size<span class="br0">&#40;</span>min = <span class="nu0">2</span>, max = <span class="nu0">14</span><span class="br0">&#41;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="kw2">private</span> <span class="kw3">String</span> licensePlate<span class="sy0">;</span></div>
</li>
</ol>
</div>
<p>That&#8217;s not bad. It&#8217;s declarative and you can use the same annotation for your presentation model and your persistence model. If you use Hibernate for persistence it creates the right kind of constraint for the database as well. But there are a couple of shortcomings.</p>
<ul>
<li>If you want to do anything else with the information from the annotation you are forced to use ugly error prone reflection, which is especially bothersome, because a property consists of  field  getter and setter. So where exactly is the annotation? What if the annotation on the getter contradict the one on the field?</li>
<li>You can&#8217;t abstract over the annotations. If comments should always have a minimum length of 5 and a maximum length of 500 there is no way to put this information in a proper abstraction. The best you can do is to define two constants.</li>
<li>It doesn&#8217;t work with my <a href="/2011/05/01/binding-scala-objects-to-swing-components/"><tt>Property</tt> class I introduced earlier.</a></li>
</ul>
<p>The last point is obviously my own problem, but it also provides a starting point for a solution for the other shortcomings. </p>
<p>For those too lazy to read the referenced article, let me reintroduce the <tt>Property</tt> class. You define a <tt>Property</tt> like this:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">val age = new Property(20)</div>
</li>
</ol>
</div>
<p>This line of code is pretty much equivalent to this java code (with <tt>pcs</tt> being an instance of <tt>PropertyChangeSupport</tt>):</p>
<div class="geshi no java">
<ol>
<li class="li1">
<div class="de1"><span class="kw4">int</span> age = <span class="nu0">20</span><span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1"><span class="kw2">public</span> <span class="kw4">void</span> setAge<span class="br0">&#40;</span><span class="kw4">int</span> theAge<span class="br0">&#41;</span><span class="br0">&#123;</span> </div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="kw4">int</span> oldAge = age</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; age = theAge<span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; pcs.<span class="me1">firePropertyChange</span><span class="br0">&#40;</span><span class="st0">&quot;age&quot;</span>, oldAge, age<span class="br0">&#41;</span></div>
</li>
<li class="li1">
<div class="de1"><span class="br0">&#125;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1"><span class="kw2">public</span> <span class="kw4">int</span> getAge<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="kw2">return</span> age<span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1"><span class="br0">&#125;</span></div>
</li>
</ol>
</div>
<p>You can set its value (with <tt>p</tt> being an instance of what ever class contains the code above):</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">p := 63</div>
</li>
</ol>
</div>
<p>You can retrieve its value:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">val ageOfP = p()</div>
</li>
</ol>
</div>
<p>And you can register a listener on it</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">p.age.registerListener(println(_))</div>
</li>
</ol>
</div>
<p>Back to validation. For <tt>age</tt> I only want to allow values between 9 and 99. How would you like to check if a given age is valid? Well, I would like to ask the property!</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">if (p.age.valid()) doSomething()
</div>
</li>
<li class="li1">
<div class="de1">else doSomethingElse()</div>
</li>
</ol>
</div>
<p>If I want to know what is wrong with the age value, I&#8217;d like to ask the property for a list of validation messages like this:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">val problems = p.age.validationMessages()</div>
</li>
</ol>
</div>
<p>All you have to do for this, is to add a trait to the age <tt>Property</tt></p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">val age = new Property(20) with Size { min = 9; max = 99 }</div>
</li>
</ol>
</div>
<p>You can properly abstract over constraints as well by defining you own Property classes:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; class Name(value : String) extends Property(value) with Length { min = 3; max = 20 }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; val firstname = new Name(&quot;&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; val lastname = new Name(&quot;&quot;)</div>
</li>
</ol>
</div>
<p>And it is easy to define your own <tt>Validations</tt>. Have look at the implementation of <tt>Length</tt></p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">trait Length extends Validation[String] {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; self : Property[String] =&gt;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; var min : Int = -1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; var max : Int = Int.MaxValue
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override def validate : List[String] = minimumValidation ::: maximumValidation ::: super.validate
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def minimumValidation = if (value != null &amp;&amp; value.length &lt; min) List(&quot;Should have minimum length &quot; + min) else List()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def maximumValidation = if (value != null &amp;&amp; value.length &gt; max) List(&quot;Should have maximum length &quot; + max) else List()
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>There are a couple of simple rules for implementing a <tt>Validation</tt>:</p>
<ul>
<li>It has to have a selftype of <tt>Property</tt></li>
<li>You must override the method <tt>validate</tt></li>
<li>And when doing so you have to take care to append your validation messages to the results of <tt>super.validate</tt>. By doing this you make sure you can combine different validation traits.</li>
</ul>
<p><tt>validationMessages</tt> and <tt>valid</tt> aren&#8217;t methods but are Properties themselves. Therefor you can register listeners with them and bind your swing GUI to it. For example the following code snippet binds the <tt>validationMessages</tt> and <tt>valid</tt> to the tooltip and the visibility of label, resulting in a validation marker for a <tt>Property</tt></p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">def bindValidation(validation : Validation[_], component : JComponent) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; component.setVisible(!validation.valid)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; validation.valid.registerListener(valid =&gt; component.setVisible(!valid))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def setToolTip(messages : List[String]) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; component.setToolTipText(
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messages match {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case x :: xs =&gt;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;&lt;html&gt;&quot; + (x :: xs).mkString(&quot;&lt;br/&gt;&quot;) + &quot;&lt;/html&gt;&quot;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case _ =&gt; null
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; setToolTip(validation.validationMessages())
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; validation.validationMessages.registerListener(setToolTip)
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>If you are interested in more source code: Everything is up at github under the working title <a href="https://github.com/schauder/More-Than-Properties">&#8220;moreThanProperties&#8221;</a>. You can also find other related articles by looking for the <a href="http://blog.schauderhaft.de/tag/morethanproperties/">tag moreThanProperties</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/07/03/input-validation-with-scala-and-swing/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Clean Code with Swing and Scala</title>
		<link>http://blog.schauderhaft.de/2011/06/26/clean-code-with-swing-and-scala/</link>
		<comments>http://blog.schauderhaft.de/2011/06/26/clean-code-with-swing-and-scala/#comments</comments>
		<pubDate>Sun, 26 Jun 2011 13:23:23 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[clean code]]></category>
		<category><![CDATA[moreThanProperties]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=821</guid>
		<description><![CDATA[I guess everybody who knows Java and Swing also knows the Swing Tutorial. It is a great source of information if you want to learn Swing. It is also a major catastrophy when it comes to structuring code. The problem is: Lots of people miss critical information contained in the tutorial like &#8216;Everything concerned with [...]]]></description>
			<content:encoded><![CDATA[<p>I guess everybody who knows Java and Swing also knows the <a href="http://download.oracle.com/javase/tutorial/uiswing/">Swing Tutorial</a>. It is a great source of information if you want to learn Swing. It is also a major catastrophy when it comes to structuring code. The problem is: Lots of people miss critical information contained in the tutorial like &#8216;Everything concerned with Swing must happen in the EDT&#8217; but they seem to suck up the messy way to structure code like a sponge.</p>
<p>This might result in code like the one below. It is actually Scala code, but that shouldn&#8217;t matter much. The only piece that is a little special are the calls to <tt>Binder</tt>, which is a little <a href="/2011/05/01/binding-scala-objects-to-swing-components/">Swing Binding Framework</a> which I introduced a couple of weeks ago.</p>
<div class="geshi no scala">
<div class="head">private def createPersonPanel(p : PersonEditor) = {</div>
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val panel = new JPanel()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val layout = new GridBagLayout()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val c = new GridBagConstraints()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridy = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.setLayout(layout)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(new JLabel(&quot;firstname&quot;), c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridx += 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val firstnameTF = new JTextField()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(firstnameTF, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(p.firstname, firstnameTF)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridy += 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(new JLabel(&quot;lastname&quot;), c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridx += 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val lastnameTF = new JTextField()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(p.lastname, lastnameTF)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(lastnameTF, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridy += 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.anchor = GridBagConstraints.SOUTHEAST
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val button = new JButton(&quot;save&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(p.save, button)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(button, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }</div>
</li>
</ol>
</div>
<p>What is so bad about this piece of crap &#8230; ähm &#8230; code?</p>
<p>The method is long. 38 lines is about 10 times longer than healthy for a method.</p>
<p>There is tons of code duplication.</p>
<p>The method does lots of different things: creating components, adding them to a panel, configuring the layout.</p>
<p>There is a strong dependency on the order of commands. We can&#8217;t just move stuff up or down in the method and still hope the result will be something reasonable, even if we stick to rearrangements allowed by the compiler.</p>
<p>All this together makes the method extremely hard to understand. How long does it take to understand what kind of GUI results? Don&#8217;t bother to much, I help. It looks like this:</p>
<p><a href="http://blog.schauderhaft.de/wp-content/uploads/2011/06/small.png"><img class="alignnone size-full wp-image-824" title="Image of the Frame in packed state." src="http://blog.schauderhaft.de/wp-content/uploads/2011/06/small.png" alt="" width="132" height="104" /></a></p>
<p>and if you resize it, it looks like this</p>
<p><a href="http://blog.schauderhaft.de/wp-content/uploads/2011/06/large.png"><img class="alignnone size-full wp-image-825" title="Resized Frame" src="http://blog.schauderhaft.de/wp-content/uploads/2011/06/large.png" alt="" width="315" height="214" /></a></p>
<p>Arguably the result looks just as ugly as the code, but once the code is clean we might be able to improve on the visual design as well.</p>
<p>If you don&#8217;t see it in the code, you might see it in the images: There are three different ways JComponents are handled by the method: <tt>JLabels</tt> are in the left column and don&#8217;t resize. The <tt>JTextField</tt>s are in the right column and do resize and the JButton doesn&#8217;t resize and is in the buttom right. In the code this is completely hidden in the manipulation of the <tt>GridBagConstraint</tt>. So lets make it explicit in the code:</p>
<div class="geshi no scala">
<div class="head">private def addToLabelColumn(</div>
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel : JPanel,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; component : JComponent,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; row : Int) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val c = new GridBagConstraints()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridy = row
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(component, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; private def addToComponentColumn(
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel : JPanel,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; component : JComponent,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; row : Int) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val c = new GridBagConstraints()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridy = row
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(component, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; private def addButton(
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel : JPanel,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; component : JButton,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; row : Int) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val c = new GridBagConstraints()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.gridy = row
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.fill = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; c.anchor = GridBagConstraints.SOUTHEAST
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.add(component, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; private def createPersonPanel(p : PersonEditor) = {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val panel = new JPanel()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val layout = new GridBagLayout()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.setLayout(layout)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; addToLabelColumn(panel, new JLabel(&quot;firstname&quot;), 0)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val firstnameTF = new JTextField()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(p.firstname, firstnameTF)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; addToComponentColumn(panel, firstnameTF, 0)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; addToLabelColumn(panel, new JLabel(&quot;lastname&quot;), 1)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val lastnameTF = new JTextField()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(p.lastname, lastnameTF)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; addToComponentColumn(panel, lastnameTF, 1)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val button = new JButton(&quot;save&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(p.save, button)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; addButton(panel, button, 2)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }</div>
</li>
</ol>
</div>
<p>I introduced three methods. One for adding a JLabel, one for adding a JComponent and one for adding JButtons. These handle the arrangement of components on a JPanel. The total length of the code increased because we create the GridBagConstraints insided the methods and have to set all properties and don&#8217;t rely anymore on the previous step to leave the constraint in a specific state.</p>
<p>If we now look at the <tt>createPersonPanel</tt> we&#8217;ll get a strong fealing of repetition in various places:</p>
<ul>
<li>each call to add* methods takes the same JPanel as an argument. We can improve on this by creating a Builder wich crates the panel, contains the add* methods and can return the fully configured panel at the end.</li>
<li>for each property we create a <tt>JLabel</tt>, a <tt>JTextField</tt>, bind the property to the later and add both to the <tt>JPanel</tt>. We can fix this by encapsulating it in a seperate method.</li>
</ul>
<p>The result might look like this:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; case class PanelBuilder() {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val panel = new JPanel()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val layout = new GridBagLayout()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; panel.setLayout(layout)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; def add(components : (JLabel, JComponent), row : Int) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; addToLabelColumn(components._1, row)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; addToComponentColumn(components._2, row)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; def add(
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component : JButton,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row : Int) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val c = new GridBagConstraints()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.gridy = row
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.fill = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.anchor = GridBagConstraints.SOUTHEAST
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panel.add(component, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; private def addToLabelColumn(
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component : JComponent,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row : Int) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val c = new GridBagConstraints()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.gridy = row
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.fill = 0
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panel.add(component, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; private def addToComponentColumn(
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component : JComponent,
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row : Int) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val c = new GridBagConstraints()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.gridx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.gridy = row
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.weightx = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.fill = 1
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panel.add(component, c)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; private def create(name : String, property : Property[String]) : (JLabel, JComponent) = {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val textField = new JTextField()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(property, textField)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; (new JLabel(name), textField)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; private def create(name : String, action : =&amp;gt; Unit) = {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val button = new JButton(&quot;save&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; Binder.bind(action, button)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; button
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; private def createPersonPanel(p : PersonEditor) = {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; val builder = PanelBuilder()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; builder.add(create(&quot;firstname&quot;, p.firstname), 0)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; builder.add(create(&quot;lastname&quot;, p.lastname), 1)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; builder.add(create(&quot;save&quot;, p.save), 2)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; builder.panel
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }</div>
</li>
</ol>
</div>
<p>The <tt>PanelBuilder</tt> has now two simple public <tt>add</tt> methods. In order to imitate the method signitures in Java we would have to create a couple of helper classes and interfaces. It would make the code less compact but this shouldn&#8217;t be a serious problem. Creation of the various components is just as the binding extracted in two create Methods. The <tt>createPersonPanel</tt> has now only 5 lines of code. Adding another property to the form should be trivial. Changing the extremely simplistic layout should be trivial and is at least limited to a single small class. I think this is pretty much OK for a first step toward clean swing code. So I leave it like it is right now. Although I do have further plans for this.</p>
<p>I hope most of you agree that the code is much easier to understand and maintain in the form it is right now. But is it really worth the effort? Some might say no. If the whole application would consist of only this little panel. I would agree. But a Swing application typically does not have a single panel with two textfields and a button. But tens or even hundreds of panels. Many consisting of large collections of components. If you have to maintain such a monster, would you prefer createPersonPanel methods like the last one, or would you prefer the first version? What if the customer if finally fed up with your crappy layout and insists on proper spacing between the labels and the <tt>JTextFields</tt> or other components?</p>
<p>All this is pretty nice when you start a new Swing application. But what if you have an existing Swing application? One with convoluted code just as the Swing Tutorial taught you? Well &#8230; start changing it now. Don&#8217;t sit down for two months and rewrite all your code, but find pieces of code duplication and extract them. It will be a long way, but you wont reach the end if you don&#8217;t start walking.</p>
<p>But what if you are not using Swing, but writing a web application? Well it really shouldn&#8217;t matter much. Your PanelBuilder might be written in JavaScript, or create HTML, but the principle is the same: Seperate creation of components, layout of components and binding of components to properties and actions.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/06/26/clean-code-with-swing-and-scala/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Binding Scala Objects to Swing Components</title>
		<link>http://blog.schauderhaft.de/2011/05/01/binding-scala-objects-to-swing-components/</link>
		<comments>http://blog.schauderhaft.de/2011/05/01/binding-scala-objects-to-swing-components/#comments</comments>
		<pubDate>Sun, 01 May 2011 18:21:20 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[moreThanProperties]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=772</guid>
		<description><![CDATA[If you do Swing application development, especially the enterprise application type you know lots of code that looks like this: public class Person &#123; &#160; &#160; private final PropertyChangeSupport pcs = new PropertyChangeSupport&#40;this&#41;; &#160; &#160; &#160; public void setName&#40;String aName&#41;&#123; &#160; &#160; &#160; &#160; String oldValue = name; &#160; &#160; &#160; &#160; name = aName; [...]]]></description>
			<content:encoded><![CDATA[<p>If you do Swing application development, especially the enterprise application type you know lots of code that looks like this:</p>
<div class="geshi no java">
<ol>
<li class="li1">
<div class="de1"><span class="kw2">public</span> <span class="kw2">class</span> Person <span class="br0">&#123;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="kw2">private</span> <span class="kw2">final</span> <span class="kw3">PropertyChangeSupport</span> pcs = <span class="kw2">new</span> <span class="kw3">PropertyChangeSupport</span><span class="br0">&#40;</span><span class="kw2">this</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw4">void</span> setName<span class="br0">&#40;</span><span class="kw3">String</span> aName<span class="br0">&#41;</span><span class="br0">&#123;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw3">String</span> oldValue = name<span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; name = aName<span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; pcs.<span class="me1">firePropertyChange</span><span class="br0">&#40;</span><span class="st0">&quot;name&quot;</span>, oldValue, aName<span class="br0">&#41;</span><span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="br0">&#125;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw3">String</span> getName<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">return</span> name<span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; <span class="br0">&#125;</span></div>
</li>
</ol>
</div>
<p>Having properties like this you can bind them to Swing components using <a href="http://www.jgoodies.com/downloads/libraries.html">JGoodies Binding</a> like this:</p>
<div class="geshi no java">
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; MyBean bean = <span class="kw2">new</span> MyBean<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; BeanAdapter adapter = <span class="kw2">new</span> BeanAdapter<span class="br0">&#40;</span>bean, <span class="kw2">true</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; ValueModel stringModel = adapter.<span class="me1">getValueModel</span><span class="br0">&#40;</span><span class="st0">&quot;name&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; <span class="kw3">JTextField</span> field = BasicComponentFactory.<span class="me1">createTextField</span><span class="br0">&#40;</span>stringModel<span class="br0">&#41;</span><span class="sy0">;</span></div>
</li>
</ol>
</div>
<p>If you don&#8217;t know <a href="http://www.javalobby.org/java/forums/t17672">JGoodies Binding you should read this article about it asap</a>.</p>
<p>If you do form based Swing applications this is the way to go: don&#8217;t write Listeners, bind components. </p>
<p>Yet I have a huge problem with this code. Actually multiple problems: </p>
<ul>
<li>You have to repeat the name of the property in four places and you will end up in hell if you don&#8217;t do it in the correct way: In the name of the setter, in the name of the getter, in the first argument to firePropertyChange and in the call to the binding framework.
</li>
<li>
A trivial property takes 8 lines of code. Thats EIGHT lines of code. Or depending on your code quality probably about 1/100th to 1/10th of a bug, for a trivial property.
</li>
<li>
Apart from being to much code, it also has a high degree of duplication, because it is the same pattern over and over again. Yet their doesn&#8217;t seem to be a reasonable way to abstract over this kind of thing
</li>
</ul>
<p>If you are willing to switch to another language you actually can abstract over this quite nicely. This of course in no surprise, since it should be easy to write a language that offers support for this kind of property. But that is not what I&#8217;m talking about. I&#8217;m of course talking about a little Scala goodness. How about this for defining a class with a property:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">class Person extends PropertyOwner {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; val name : Property[String] = &quot;smith&quot;
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>Note that there is only one line defining the property (including setting it to an initial value). So how would binding it to a JTextField look like? Like this:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; val p = new Person
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; val nameTextField = new JTextField()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; Binder.bind(p.name, nameTextField)</div>
</li>
</ol>
</div>
<p>Note that I don&#8217;t use the String &#8220;name&#8221; anywhere. Its all just normal, strongly typed values. If I use firstName instead of name by accident, the compiler will complain. The trick is obviously that I actually use objects of type <tt>Property</tt>, instead of fields, getters and setters. Yet using this thing looks (almost) perfect natural:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">&nbsp; &nbsp; val p = new Person
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; p.name := &quot;Alf&quot;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; println(p.name())</div>
</li>
</ol>
</div>
<p>The code to achieve this is rather simple and short. The key is that a <tt>Property</tt> has a <tt>apply</tt> method returning its value and an := operator as replacement for a setter.</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">class Property[T](var value : T) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; var listeners = List[T =&gt; Unit]()
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def apply() = value
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def :=(aValue : T) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; if (value != aValue) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value = aValue
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fireEvent
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def registerListener(l : T =&gt; Unit) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; listeners = l :: listeners
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; private def fireEvent {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; listeners.foreach(_(value))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">object Property {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; implicit def apply[T](t : T)(implicit owner : PropertyOwner) : Property[T] =
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; new Property(t : T)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; implicit def toT[T](p : Property[T]) : T = p()
</div>
</li>
<li class="li1">
<div class="de1">}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">trait PropertyOwner {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; implicit val THE_OWNER = this
</div>
</li>
<li class="li1">
<div class="de1">}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">object Binder {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def bind(p : Property[String], textField : JTextField) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; var locked = false
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; initTextField
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; syncFromTextFieldToProperty
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; syncFromPropertyToTextField
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; def initTextField = p() match {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case null =&gt; textField.setText(&quot;&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case _ &nbsp; &nbsp;=&gt; textField.setText(p().toString())
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; def syncFromPropertyToTextField {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p.registerListener { value : String =&gt;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (textField.getText != value)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; textField.setText(value)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; def syncFromTextFieldToProperty = textField.getDocument.addDocumentListener(new DocumentListener() {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; def changedUpdate(e : DocumentEvent) = updateProperty
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; def insertUpdate(e : DocumentEvent) = updateProperty
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; def removeUpdate(e : DocumentEvent) = updateProperty
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; })
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; def updateProperty = {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p := textField.getText
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>This is currently just a little toy, call it proof of concept if you like. It only works with JTextFields, and the event notification might needs tweaking, since it provides just the new value of the property right now. There are many more ideas how to use this as a basis for building nice clean code with a Swing GUI. Watch this blog for more ideas and toys like this.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/05/01/binding-scala-objects-to-swing-components/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Even More Testing With Scalatest</title>
		<link>http://blog.schauderhaft.de/2011/04/03/even-more-testing-with-scalatest/</link>
		<comments>http://blog.schauderhaft.de/2011/04/03/even-more-testing-with-scalatest/#comments</comments>
		<pubDate>Sun, 03 Apr 2011 19:03:44 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[after]]></category>
		<category><![CDATA[before]]></category>
		<category><![CDATA[fixture]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[scalatest]]></category>
		<category><![CDATA[setup]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=695</guid>
		<description><![CDATA[One important feature of any test framework is setting up a test fixture and tearing it down afterwards. In JUnit 3 for you did that by overriding the methods setup() and teardown() of the class TestCase, which every test needed to extend. JUnit 4 was a little more flexible. The name of the methods was [...]]]></description>
			<content:encoded><![CDATA[<p>One important feature of any test framework is setting up a test fixture and tearing it down afterwards.</p>
<p>In JUnit 3 for you did that by overriding the methods <tt>setup()</tt> and <tt>teardown()</tt> of the class <tt>TestCase</tt>, which every test needed to extend. JUnit 4 was a little more flexible. The name of the methods was irrelevant, instead you used annotations to tag the methods you wanted to use for setup or teardown. The anotations where are <tt>@Before</tt>, <tt>@BeforeClass</tt>, <tt>@After</tt> and <tt>@AfterClass</tt>. This lead to the somewhat messy situation where the setup of a test was sometimes called setup, sometimes Before and sometime it was given a name that actually described what it was doing like <tt>createAnEmptyStack()</tt>. As a result the setup and teardown methods weren&#8217;t easily identified any more.</p>
<p>How does ScalaTest solve the issue? It goes back to the inheritance solution, but benefits from the possibility to inherit from multiple traits. So you can still have tests that extend some completely unrelated trait. As so often scalatest offers multiple option. For JUnit developers the following is probably the most intuitive:</p>
<div class="geshi no scala">
<div class="head">import org.scalatest._</div>
<ol>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">class FibonacciScalaTest extends FunSuite with BeforeAndAfterEach with BeforeAndAfterAll {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override def beforeEach() {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;beforeEach&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override def afterEach() {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;afterEach&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override def beforeAll() {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;beforeAll&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; override def afterAll() {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;afterAll&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;test something&quot;) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; println(&quot;inside the test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; assert(1 === (3 &#8211; 2))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;test something else&quot;) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp;println(&quot;inside the test&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp;assert(2 &amp;gt; 1)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>We mix two traits <tt>BeforeAndAfterEach</tt> and <tt>BeforeAndAfterAll</tt> into our test class, which allows as to override before/afterEach and before/afterAll which get executed as probably expected yielding the following output:</p>
<pre>beforeEach
inside the test
afterEach
beforeEach
inside the test
afterEach
afterAll</pre>
<p>If you are using this technique to setup some variables that get used inside the test, note that there is only on instance of the test class no matter how many tests it contains. So make sure you clean everything up after your test. Since cleaning up is error prone there are other strategies you can use. You can use the <tt>OneInstancePerTest</tt> trait, which ensures that each test as its own test instance, as you are used to from JUnit.</p>
<p>I consider different approach more idiomatic for Scala(Test): pass the stuff you need inside your test into the test as a parameter! In order to do this for every Suite trait (like e.g. FunSuite) there is a matching Fixture* trait. Let&#8217;s examine an example using the <tt>FixtureFunSuite</tt>. In order to make it work we need to do three things:</p>
<ol>
<li>specify what kind of fixture our tests expect. We do this by defining the type <tt>FixtureParam</tt> inside the test class</li>
<li>the tests actually have to accept a fixture of that type as a parameter</li>
<li>we have have to create the FixtureParam objects and pass them into the tests when calling them for execution. This happens in the method <tt>withFixture</tt></li>
</ol>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">class FibonacciScalaTest extends FixtureFunSuite {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; type FixtureParam = scala.collection.mutable.Set[String]
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def withFixture(testExpectingOneArgument : OneArgTest){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp;testExpectingOneArgument(scala.collection.mutable.Set(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;length increases by adding elements&quot;) { set =&gt;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; set += &quot;x&quot;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; assert(4 === set.size)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; test(&quot;length decreases by adding elements&quot;) { set =&gt;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; set -= &quot;a&quot;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; assert(2 === set.size)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>Note that both tests would fail if they would see the changes done by the other tests, but they don&#8217;t. For just doing normal setup, this approach might be a little to verbose, but consider that you have full control over how you call the tests. You could use this in order to run each test 20 times in parallel threads in order to test for concurrency problems, or in the EDT of Swing for swing related tests. Faithful readers might remember such a list from a different article: It is exactly the kind of stuff you can do with <a href="/2010/08/15/use-cases-for-junit-rules/">JUnit Rules</a>.</p>
<p>If you read so far you might as well be interested in <a href="/2010/12/26/testing-with-scala/">Testing with Scala</a> and <a href="/2011/01/16/more-on-testing-with-scalatest/">More on Testing with Scalatest</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/04/03/even-more-testing-with-scalatest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Teaching a Kid Scala</title>
		<link>http://blog.schauderhaft.de/2011/02/06/teaching-a-kid-scala/</link>
		<comments>http://blog.schauderhaft.de/2011/02/06/teaching-a-kid-scala/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 09:16:28 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=717</guid>
		<description><![CDATA[My son Finn is 6 and as pretty much every kid of that age he is wondering &#8220;What the heck is daddy doing all day&#8221;. Therefore I was wondering for some time how I could teach him a little programming. I first considered Alice or to be more precise Alice Storytelling. Unfortunately it wasn&#8217;t working [...]]]></description>
			<content:encoded><![CDATA[<p>My son Finn is 6 and as pretty much every kid of that age he is wondering &#8220;What the heck is daddy doing all day&#8221;. Therefore I was wondering for some time how I could teach him a little programming. I first considered <a href="http://www.alice.org/">Alice</a> or to be more precise <a href="http://www.alice.org/kelleher/storytelling/index.html">Alice Storytelling</a>. Unfortunately it wasn&#8217;t working on my computer. There are plenty of other systems designed for teaching kids programming, but the more I looked the more I doubted this would be the right approach.</p>
<p>These systems often work with some kind of visual interface, which allows to drag and drop commands. Thats great for kids that are used to a mouse a lot. While my son is certainly able to use a mouse, drag&#8217;n'drop is something taking full concentration for him. And when something drops in the wrong spot it is often quite difficult for him to figure out what happened.</p>
<p>At the same time I was reading  <a href="http://www.amazon.de/gp/product/0262510871?ie=UTF8&amp;tag=schauderhafte-21&amp;linkCode=as2&amp;camp=1638&amp;creative=19454&amp;creativeASIN=0262510871">Structure and Interpretation of Computer Programs</a> which will teach you among other things Scheme. And I was amazed at the simplicity of the first program:</p>
<pre>486</pre>
<p>It will print 486. Not exacty a master piece of algorithm design, but you have to admit it is extremely easy. My son sure could do that. But I don&#8217;t know Lisp or Scheme and I am a JVM guy. So I considered learning Clojure, until I remembered the Scala REPL. The Scala REPL is an interactive console based environment which will interpret you input as Scala code. So I fired it up typing &lt;tt&gt;scala&lt;/tt&gt; in the command line and tried the program mentioned above:</p>
<div id="attachment_718" class="wp-caption alignnone" style="width: 616px"><a href="http://blog.schauderhaft.de/wp-content/uploads/2011/02/scala1.png"><img class="size-full wp-image-718 " title="scala1" src="http://blog.schauderhaft.de/wp-content/uploads/2011/02/scala1.png" alt="Scala REPL showing the simplest possible Scala programm" width="606" height="182" /></a><p class="wp-caption-text">Scala REPL showing the simplest possible Scala programm: 486 (click for full size)</p></div>
<p>So I started teaching Scala to my son. The first programs where things like</p>
<pre>2+3</pre>
<p>After trying different expressions I introduced the concept of variables and dictated:</p>
<pre>val lara = 3</pre>
<p>Explaining that &#8216;lara&#8217; has now the value 3</p>
<p>He immediately grasped the concept and tried the following</p>
<pre>finn = 6</pre>
<p>which resulted in</p>
<pre>:8: error: not found: value finn
val synthvar$0 = finn
                 ^
:5: error: not found: value finn
       finn = 6
       ^</pre>
<p>Since Finn can&#8217;t read yet and doesn&#8217;t speak English either there was no way he would understand the error message. So the only chance was comparing the command that worked and the command that doesn&#8217;t until he figured out what was wrong.</p>
<p>I think that was the very first big lesson learned: Computers are extremely picky about what they are willing to understand.</p>
<p>After understanding that he missed the &#8216;val&#8217; thingy at the beginning he declared a variable for himself, one for mom and one for dad, each filled with the respective age and added the ages until it was time to finish the first lesson of Scala programming.</p>
<p>So what are the lessons <strong>I</strong> learned from this?</p>
<ul>
<li>visual interfaces can be a distraction</li>
<li>the simplest Scala program is by orders of magnitude easier then the simplest Java program. If you doubt that write down the simplest Java program and compare it to <tt>486</tt> and then add the steps of saving the file, compiling and running it to the equation.</li>
<li>If you don&#8217;t have much to build on even the visual programming environments designed especially for kids are more difficult to master then the first steps in Scala</li>
</ul>
<p>BTW: When we continued with the second lesson (repetition of what we learned + functions) Finn started to teach the stuff he learned to his younger sister (3 years old). I&#8217;ll tell that anybody who tries to explain to me that he doesn&#8217;t know anything worth telling others in a Java User Group.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/02/06/teaching-a-kid-scala/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>More on Testing with Scalatest</title>
		<link>http://blog.schauderhaft.de/2011/01/16/more-on-testing-with-scalatest/</link>
		<comments>http://blog.schauderhaft.de/2011/01/16/more-on-testing-with-scalatest/#comments</comments>
		<pubDate>Sun, 16 Jan 2011 07:59:34 +0000</pubDate>
		<dc:creator>Jens Schauder</dc:creator>
				<category><![CDATA[Softwaredevelopment]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[scalatest]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.schauderhaft.de/?p=677</guid>
		<description><![CDATA[Some weeks ago I wrote about getting started with testing with scala. Now its time to explore a little more what&#8217;s in that ScalaTest library. I described one way of testing with scalatest using FeatureSpec. But there are many ways in which you can write tests. So just for the fun of it I&#8217;m using [...]]]></description>
			<content:encoded><![CDATA[<p>Some weeks ago I wrote about getting <a href="/2010/12/26/testing-with-scala/">started with testing with scala</a>. Now its time to explore a little more what&#8217;s in that <a href="http://www.scalatest.org/">ScalaTest</a> library.</p>
<p>I described one way of testing with scalatest using FeatureSpec. But there are many ways in which you can write tests. So just for the fun of it I&#8217;m using the FunSuite today:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">import org.scalatest.FunSuite
</div>
</li>
<li class="li1">
<div class="de1">import org.scalatest.matchers.ShouldMatchers
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">class SomeTest extends FunSuite with ShouldMatchers{
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;test(&quot;Some Test&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &quot;test&quot; should have length (4)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;test(&quot;Some other Test&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &quot;test&quot;.reverse should be (&quot;tset&quot;)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;}
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>This looks similar easy enough for every Java developer to to understand what is going to be tested. It might not be so obvious, what actually is going on in this class. Lets ignore the actual assertions for today. Note that we don&#8217;t define anything but the test class itself. So the the individual tests aren&#8217;t method definitions as in JUnit (and TestNG AFAIK), but calls to a function called <tt>test</tt>. It takes two arguments: the name of the test (which has to be unique in the test class) and the actual test which is just a code block. (Actually you can have additional tags after the test name, but again thats for a different article. The method test registers the test for execution. This happens at instantiation of the test class, since the calls to the <tt>test</tt> method are placed directly in the body of the test class. Once all the test classes are instantiated (and therefore all tests registered) scalatest starts executing all the tests, i.e. it executes all the code blocks passed as parameters to <tt>test</tt>.</p>
<p>As you might have noted, there was no &#8216;reflection&#8217; or &#8216;byte code magic&#8217; involved in all this. It&#8217;s all straight scala code. I guess Bill Venners liked that when he was writing the code. But why should we as a user care? Because we can do all the things we can do with normal code!</p>
<p>Lets assume you wrote a method to check if a string is a <a href="http://en.wikipedia.org/wiki/Palindrome">palindrome</a> obviously you want to have some tests for that:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">class Palindrome extends FunSuite with ShouldMatchers{
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;def palindrome(s: String) = s == s.reverse
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;test(&quot;empty String is a palindrome&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; assert (palindrome(&quot;&quot;))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;test(&quot;single character is a palindrome&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; assert(palindrome(&quot;a&quot;))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;test(&quot;sator square is a palindrome&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; assert(palindrome(&quot;sator arepo tenet opera rotas&quot;))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;}
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;test(&quot;xyz is not a palindrome&quot;){
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; assert(!palindrome(&quot;xyz&quot;))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;}
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>While the tests in this example are really simple we still see the code duplication. And once the tests get just a little more involved, it gets really annoying. But since tests are just method calls we can rewrite like this:</p>
<div class="geshi no scala">
<ol>
<li class="li1">
<div class="de1">class Palindrom2 extends FunSuite with ShouldMatchers {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; def palindrome(s: String) = s == s.reverse
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; val testvalues = Map(true -&gt; List(&quot;&quot;, &quot;a&quot;, &quot;sator arepo tenet opera rotas&quot;),
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; false -&gt; List(&quot;xyz&quot;))
</div>
</li>
<li class="li1">
<div class="de1">&nbsp;</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; for ((r, probes) ← testvalues; probe ← probes) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; test(probe + &quot; is &quot; + (if (!r) &quot;not &quot;) + &quot; a palindrome&quot;) {
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; assert(palindrome(probe) === r)
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; &nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">&nbsp; &nbsp; }
</div>
</li>
<li class="li1">
<div class="de1">}</div>
</li>
</ol>
</div>
<p>I start by creating a <tt>Map</tt> from the expected result of the method <tt>palindrome</tt> to a list of test values which should yield that result. I then loop through that Map and the contained list and for each entry I call </tt>test</tt>, with a dynamic name and a fixed code block.</p>
<p>To do the same thing in JUnit or TestNG you have to use special features of the test frameworks. With scalatest its just a basic application of language features. I like that.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.schauderhaft.de/2011/01/16/more-on-testing-with-scalatest/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

