<?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>Giordano Scalzo&#039;s Personal Blog &#187; java</title>
	<atom:link href="http://giordano.scalzo.biz/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://giordano.scalzo.biz</link>
	<description>Just another useless weblog</description>
	<lastBuildDate>Fri, 09 Jul 2010 09:41:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Objective-C for busy Java Developers 1: Calling methods</title>
		<link>http://giordano.scalzo.biz/2010/01/19/objective-c-for-busy-java-developers-1-calling-methods/</link>
		<comments>http://giordano.scalzo.biz/2010/01/19/objective-c-for-busy-java-developers-1-calling-methods/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 13:34:43 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=261</guid>
		<description><![CDATA[At last I got a wonderful MacBookPro, so I started to study Objective-C to develop some cool Iphone applications.
Objective-C is a language derived from C, to which it adds some modern features as ObjectOriented or Smalltalk-style messaging.
As far I&#8217;m a complete newbie, I&#8217;m trying to learn it recalling some well know patterns and scenarios as [...]]]></description>
			<content:encoded><![CDATA[<p>At last I got a wonderful MacBookPro, so I started to study <a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a> to develop some cool Iphone applications.</p>
<p><a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a> is a language derived from C, to which it adds some modern features as ObjectOriented or Smalltalk-style messaging.</p>
<p>As far I&#8217;m a complete newbie, I&#8217;m trying to learn it recalling some well know patterns and scenarios as made in Java , following <a href="http://cocoadevcentral.com/d/learn_objectivec/">this good tutorial</a>.</p>
<p><a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a> has a little strange way to call method, that could be disorienting at first glance:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
object.method;
object.methodWithInput(input);

output = object.methodWithOutput();
output = object.methodWithInputAndOutput(Object input);
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
[object method];
[object methodWithInput:input];

output = [object methodWithOutput];
output = [object methodWithInputAndOutput:input];
</pre>
<p>Obviously, it&#8217;s possible to call methods of class, instead of instance:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
Object oString = new String();
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
id oString = [NSString string];
</pre>
<p>The
<pre>id</pre>
<p> refers any kind of object, so it&#8217;s little different from Java counterpart.<br />
Better code is:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
String sString = new String();
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
NSString* sString = [NSString string];
</pre>
<p>With this style, it&#8217;s a little cumbersome write nested calls:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
calculator.add(numbers.split());
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
[calculator add:[numbers split]];
</pre>
<p>This syntax disencourage the nesting of more than one method.</p>
<p>Some methods take multiple input arguments, Objective-C deals with that allowing split method names:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
boolean writeToFile(String path, boolean useAuxiliaryFile)

boolean result = myData.writeToFile("/tmp/log.txt", false);
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
-(BOOL)writeToFile:(NSString *)path withAuxFile:(BOOL)useAuxiliaryFile;

BOOL result = [myData writeToFile:@"/tmp/log.txt" withAuxFile:NO];
</pre>
<p>Objective-C has properties built in, in Java you need to implement getters and setters:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
photo.setCaption("Day at the Beach");
output = photo.getCaption();
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
photo.caption = @"Day at the Beach";
output = photo.caption;
</pre>
<p>A property should be marked
<pre>@property</pre>
<p> in declaration and
<pre>@synthesize</pre>
<p> in implementation.</p>
<p>To create an object, the function
<pre>alloc</pre>
<p> should be called and then an init method should be called:</p>
<p><b>Java</b>:</p>
<pre class='brush:java'>
object = new ComplexObject(1.0f);
</pre>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
object = [[ComplexObject alloc] initWithFloat:1.0f];
</pre>
<p>When working in an environment without garbage collector, any object created with alloc should be released:</p>
<p><b>Objective-C</b>:</p>
<pre class='brush:c'>
[object release];
</pre>
<p>To complete this introductory post, take a look at this <a href='http://giordano.scalzo.biz/wp-content/uploads/2010/01/objectiveccheatsheet.pdf'>ObjectiveC CheatSheet</a>: it contains all the most used constructs needed to start to code for Mac.</p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/objective-c' rel='tag' target='_self'>objective-c</a>, <a class='technorati-link' href='http://technorati.com/tag/tutorial' rel='tag' target='_self'>tutorial</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2010/01/19/objective-c-for-busy-java-developers-1-calling-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No more excuses 2: junit testing System time</title>
		<link>http://giordano.scalzo.biz/2009/11/07/no-more-excuses-2-junit-testing-system-time/</link>
		<comments>http://giordano.scalzo.biz/2009/11/07/no-more-excuses-2-junit-testing-system-time/#comments</comments>
		<pubDate>Sat, 07 Nov 2009 13:59:37 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[trick]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=197</guid>
		<description><![CDATA[Another common exemple of static dependency, it&#8217;s the Time System dependency.
In greenfield project it could be possible inject time into the objects they&#8217;ll use it, but in legacy code it&#8217;s more difficult, so oftet we gave up and don&#8217;t unit test some behaviour dependent from time.
In a recent project, I had the problem to check [...]]]></description>
			<content:encoded><![CDATA[<p>Another common exemple of static dependency, it&#8217;s the Time System dependency.<br />
In greenfield project it could be possible inject time into the objects they&#8217;ll use it, but in legacy code it&#8217;s more difficult, so oftet we gave up and don&#8217;t unit test some behaviour dependent from time.</p>
<p>In a recent project, I had the problem to check the correct format of a filename that it had to contain the creation timestamp; I easily overcame it with a nice test pattern made by <a href="http://c2.com/cgi/wiki?PaoloPerrotta">Paolo &#8220;Nusco&#8221; Perrotta</a>, well known <a href="http://pragprog.com/titles/ppmetr/metaprogramming-ruby">Ruby Metaprogramming guru</a>, in a version wrote by <a href="http://bbossola.wordpress.com/">Bruno Bossola</a> in a nice <a href="http://www.vqwiki.org/">Open Source project</a>.</p>
<p>In a nutshell, the trick is to <em>adapt </em>System Time with another object.</p>
<p>Let see a simple example.<br />
This is the class to test:</p>
<pre class="brush: java">
package biz.scalzo.prod;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeFormatter {
	public String now() {
		SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm");
		return sdf.format(new Date(System.currentTimeMillis()));
	}
}
</pre>
<p>I know it mixes two responsibilities, it has a silly static dependecy and so on, but forgive my oversemplification used to show the pattern.</p>
<pre class="brush: java">
package biz.scalzo.test;

import junit.framework.Assert;
import org.junit.Test;

public class ATimeFormatter {
	@Test
	public void shouldFormatNowInFancyWay() {
		Assert.assertEquals("2009/10/13 15:29", new TimeFormatter().now());
	}

}
</pre>
<p>The behaviour to check is how well the Formatter formats current time in string; we have to find a way to set a well know time point so we can check te result of format.</p>
<p>To implement the <a href="http://c2.com/cgi/wiki?VirtualClock">VirtualClock</a> pattern, we declare a simple <em>Clock </em>interface:</p>
<pre class="brush: java">
package biz.scalzo.prod;

public interface Clock {
	public long now();
}
</pre>
<p>and a repository where we can insert our fake clock</p>
<pre class="brush: java">
package biz.scalzo.prod;

import java.util.Date;

public class SystemTime {
	private static Clock clock;

	private static final Clock defaultClock = new Clock() {
		public long now() {
			return System.currentTimeMillis();
		}
	};

	public static long asMillis() {
		return getClock().now();
	}

	public static Date asDate() {
		return new Date(getClock().now());
	}

	public static void reset() {
		clock = null;
	}

	public static void setClock(Clock aClock) {
		clock = aClock;
	}

	static Clock getClock() {
		return (clock != null ? clock : defaultClock);
	}
}
</pre>
<p>Now we can change our class using <em>SystemTime </em>instead of <em>System.currentTimeMillis(</em>):</p>
<pre class="brush: java">
package biz.scalzo.prod;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeFormatter {
	public String now() {
		SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm");
		return sdf.format(SystemTime.asDate());
	}
}
</pre>
<p>In test harness we can inject a fake clock</p>
<pre class="brush: java">
package biz.scalzo.test;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import biz.scalzo.prod.Clock;
import biz.scalzo.prod.SystemTime;
import biz.scalzo.prod.TimeFormatter;

public class ATimeFormatter {
	private static final long FAKED_TIME = 1255440571354L;

	private void fakeClock() {
		SystemTime.setClock(new Clock() {
			public long now() {
				return FAKED_TIME;
			}
		});
	}

	@Before
	public void setUp(){
		fakeClock();
	}

	@Test
	public void shouldFormatNowInFancyWay() {
		Assert.assertEquals("2009/10/13 15:29", new TimeFormatter().now());
	}

}
</pre>
<p>and we have green bar! Neat, isn&#8217;t it?</p>
<p>I know it&#8217;s a lot of code, but in legacy code it&#8217;s better than leave a feature without a test.</p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/test' rel='tag' target='_self'>test</a>, <a class='technorati-link' href='http://technorati.com/tag/trick' rel='tag' target='_self'>trick</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/11/07/no-more-excuses-2-junit-testing-system-time/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Extreme Refactoring or Is Guard clause Considered harmful?</title>
		<link>http://giordano.scalzo.biz/2009/09/18/extreme-refactoring-or-is-guard-clause-considered-harmful/</link>
		<comments>http://giordano.scalzo.biz/2009/09/18/extreme-refactoring-or-is-guard-clause-considered-harmful/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 14:56:34 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[agile]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[refactor]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=112</guid>
		<description><![CDATA[During the JDave try, the focus was on Bdd side of the exercise, but, nonetheless, the StringTemplater&#8217;s code was yelling &#8220;Refactor me! Refactor me!&#8221; at me  .
Actually, that I like least, it&#8217;s the Guard Clause, I used to split a marker in key-value form:

private String name(String[] pair) {
		if (pair.length != 2)
			return "";
		return "$" + [...]]]></description>
			<content:encoded><![CDATA[<p>During the <a href="http://giordano.scalzo.biz/2009/09/17/using-jdave-a-quick-introduction-to-specs-framework/">JDave try</a>, the focus was on Bdd side of the exercise, but, nonetheless, the StringTemplater&#8217;s code was yelling &#8220;<em>Refactor me! Refactor me!</em>&#8221; at me <img src='http://giordano.scalzo.biz/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<p>Actually, that I like least, it&#8217;s the <a href="http://www.c2.com/cgi/wiki?GuardClause">Guard Clause</a>, I used to split a marker in key-value form:</p>
<pre class="brush: java">
private String name(String[] pair) {
		if (pair.length != 2)
			return "";
		return "$" + pair[0].trim();
	}
</pre>
<p>Usually I like that pattern, it&#8217;s a well know <a href="http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html"> way to avoid nested conditional</a>, but <a href="http://www.antiifcampaign.com/">Anti-If Campaign</a>, promoted by <a href="http://cirillosscrapbook.wordpress.com/">Francesco Cirillo</a> made me think.</p>
<p>The first try didn&#8217;t satisfied me:</p>
<pre class="brush: java">
private String name(String[] pair) {
		return  (pair.length != 2) ? "" : "$" + pair[0].trim();
	}
</pre>
<p>Indeed, I believe it&#8217;s more cryptic and ugly than the original one.</p>
<p>Looking the code more carefully, I saw another thing: I was violating the principle &#8220;<em>Ask, don&#8217;t tell</em>&#8220;, handling some data that could be tied together.</p>
<p>Creating the new class, I thought another thing:<br />
&#8220;<em>Why am I using the &#8216;<strong>IF</strong>&#8216;</em>?&#8221;<br />
I did for avoid a runtime exception&#8230; but is an exception evil?<br />
It isn&#8217;t if we can handle it!</p>
<p>So at the end this is my final product:</p>
<pre class="brush: java">
package biz.scalzo.kata.stringtemplater.jdave;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class StringTemplater {

	public String replace(String stringToReplace) {
		return replace(stringToReplace, "");
	}

	public String replace(String stringToReplace, String markers) {
		return replaceEmptyMarkers(replace(stringToReplace, initialIterator(markers)));
	}

	private String replaceEmptyMarkers(String stringToReplace) {
		return stringToReplace.replaceAll("\\$\\w+", "");
	}

	private Iterator<String> initialIterator(String markers) {
		return Arrays.asList(markers.split(",")).iterator();
	}

	private String replace(String stringToReplace, Iterator<String> markers) {
		try {
			return replaceMarker(stringToReplace, markers);
		} catch (NoSuchElementException e) {
			return stringToReplace;
		}
	}

	private String replaceMarker(String stringToReplace,
			Iterator<String> markers) {
		Pair pair = new Pair(markers.next());
		String newString = stringToReplace.replace(pair.name, pair.value);
		return replace(newString, markers);
	}

	private class Pair {
		private String name;
		private String value;

		private Pair(String nameAndValue) {
			init(nameAndValue.split(":"));
		}

		private void init(String[] nameAndValue) {
			try {
				name = "$" + nameAndValue[0].trim();
				value = nameAndValue[1].trim();
			} catch (IndexOutOfBoundsException e) {
				name = "";
				value = "";
			}
		}
	}
}
</pre>
<p>I think a I could refactor more, but I was enough satisfied: I reached my goal to avoid <strong>IF</strong> and I&#8217;ve start to think the exception in different way.</p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/eclipse' rel='tag' target='_self'>eclipse</a>, <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/refactor' rel='tag' target='_self'>refactor</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/18/extreme-refactoring-or-is-guard-clause-considered-harmful/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using JDave: A quick introduction to specs framework</title>
		<link>http://giordano.scalzo.biz/2009/09/17/using-jdave-a-quick-introduction-to-specs-framework/</link>
		<comments>http://giordano.scalzo.biz/2009/09/17/using-jdave-a-quick-introduction-to-specs-framework/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 15:13:47 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[bdd]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[jdave]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=90</guid>
		<description><![CDATA[As second Bdd engine to try, I choose JDave, a specification oriented engine.
JBehave is, instead, user-stories-oriented: the difference is very subtle and I&#8217;m not sure I caught it completely  .
Anyway, JDaveis inspired by RSpec, at the moment the most used bdd engine, so I thought it deserved a try.
In order to compare JDave with [...]]]></description>
			<content:encoded><![CDATA[<p>As second Bdd engine to try, I choose <a href="http://www.jdave.org/">JDave</a>, a specification oriented engine.<br />
<a href="http://jbehave.org/">JBehave </a>is, instead, user-stories-oriented: the difference is very subtle and I&#8217;m not sure I caught it completely <img src='http://giordano.scalzo.biz/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .<br />
Anyway, <a href="http://www.jdave.org/">JDave</a>is inspired by <a href="http://rspec.info/">RSpec</a>, at the moment the most used bdd engine, so I thought it deserved a try.<br />
In order to compare <a href="http://www.jdave.org/">JDave</a> with <a href="http://jbehave.org/">JBehave</a>, I implemented the StringTemplater kata, as in my <a href="http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/">previous post</a>.</p>
<h3>Installing JDave</h3>
<p>After creating a java project, I simply downloaded the <a href="http://www.jdave.org/resources.html">last version of JDave</a> and extracted all jar in lib directory of my project:</p>
<p><img src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/bdd.png" alt="JDave Jars" title="JDave Jars" width="259" height="441" class="aligncenter size-full wp-image-97" /></p>
<p>They are a lot of jars, and I&#8217;m sure I won&#8217;t use all of them, but it&#8217;s just a try so it doesn&#8217;t deserve the time to filter only the used ones.</p>
<p><a href="http://jbehave.org/">JBehave</a> is a story runner, so each scenario must be written as:</p>
<pre><strong>Given</strong> something
<strong>When </strong>something happens
<strong>Then </strong>this happens</pre>
<p>Instead, <a href="http://www.jdave.org/">JDave</a> is a specification engine and each scenario show a behavior of a class:</p>
<pre>AThingIWantToWrite
  - ShouldDoThis
  - ShouldDoThat
  - ShouldntDoThat</pre>
<p>In other words, <a href="http://jbehave.org/">JBehave</a> is similar to <a href="http://cukes.info/">Cucumber</a>, <a href="http://www.jdave.org/">JDave</a> is similar to <a href="http://rspec.info/">RSpec</a>.</p>
<p>Writing a specification is really straightforward:<br />
first of all, we create a <code>Specification </code>object, passing the object we want to write; then we create a serie of inner classes:</p>
<pre class="brush: java">@RunWith(JDaveRunner.class)
public class StringTemplaterSpec extends Specification&lt;ThingIWantToWrite&gt; {
	public class AThingIWantToWrite {
		public void ShouldDoThis() {
		}
		public void ShouldDoThat() {
		}
        }
   ...
}</pre>
<p>As <a href="http://jbehave.org/">JBehave</a>, <a href="http://www.jdave.org/">JDave</a> is a wrapper built over JUnit, so we can use our Ide integration to run the specifications.<br />
That&#8217;s it!</p>
<h3>The code</h3>
<p>As in <a href="http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/">JBehave try</a>, I implemented the same scenarios as in Corey Haines Video:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jdave;

import org.junit.runner.RunWith;

import jdave.Specification;
import jdave.junit4.JDaveRunner;

@RunWith(JDaveRunner.class)
public class StringTemplaterSpec extends Specification&lt;StringTemplater&gt; {
	public class AStringTemplater {
		private StringTemplater stringTemplater;

		public void create() {
			stringTemplater = new StringTemplater();
		}

		public void shouldReturnEmptyWhenAnEmptyStringIsPassed() {
			specify(stringTemplater.replace(""), must.equal(""));
		}

		public void shouldReturnTheOriginalStringWhenNoMarkersArePassed() {
			specify(stringTemplater.replace("original string"), must.equal("original string"));
		}

		public void shouldReplaceAToken() {
			specify(stringTemplater.replace("Hello, $name","name: giordano"),
					must.equal("Hello, giordano"));
		}

		public void shouldReplaceTwoTokens() {
			specify(stringTemplater.replace("Hello, $name, how a $attitude day","name: giordano, attitude:  wonderful"),
					must.equal("Hello, giordano, how a wonderful day"));
		}

		public void shouldRemoveNotProvidedMarkers() {
			specify(stringTemplater.replace("Hello, $name, how a $attitude day","name: giordano"),
					must.equal("Hello, giordano, how a  day"));
		}
	}

}</pre>
<p>The Junit view of Eclipse is very explicative of the behaviors of StringTemplater:<br />
<img src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/junit_view.png" alt="JUnit View" title="JUnit View" width="491" height="326" class="aligncenter size-full wp-image-98" /></p>
<p>For sake of completeness, this is the final implementation of StringTemplater:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jdave;

import java.util.Arrays;
import java.util.Iterator;

public class StringTemplater {

	public String replace(String stringToReplace) {
		return replace(stringToReplace, "");
	}

	public String replace(String stringToReplace, String markers) {
		return replace(stringToReplace, initialIterator(markers));
	}

	private String[] tupla(String pair) {
		return pair.split(":");
	}

	private Iterator&lt;String&gt; initialIterator(String markers) {
		return Arrays.asList(markers.split(",")).iterator();
	}

	private String replace(String stringToReplace, Iterator&lt;String&gt; markers) {
		if (!markers.hasNext())
			return stringToReplace;
		String[] pair = tupla(markers.next());
		String newString = stringToReplace.replace(name(pair), value(pair));
		return replaceEmptyMarkers(replace(newString, markers));
	}

	private String replaceEmptyMarkers(String replace) {
		return replace.replaceAll("\\$\\w+", "");
	}

	private String value(String[] pair) {
		return (pair.length != 2) ? "" : pair[1].trim();
	}

	private String name(String[] pair) {
		if (pair.length != 2)
			return "";
		return "$" + pair[0].trim();
	}
}</pre>
<h3>Conclusions</h3>
<p><a href="http://www.jdave.org/">JDave</a> is very easy to learn and the specifications written throught it are very complete and expressive.<br />
If I have to make a choice, I liked slightly more <a href="http://www.jdave.org/">JDave</a>, but I think are just two tools: BDD is a way to think, not a framework or an engine to use.</p>
<p>In conclusions, I believe <a href="http://jbehave.org/">JBehave </a>and <a href="http://www.jdave.org/">JDave</a> could be used together, the former to describe the user stories, at user level, the latter to describe the behaviors of the classes, at developer level.</p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/bdd' rel='tag' target='_self'>bdd</a>, <a class='technorati-link' href='http://technorati.com/tag/eclipse' rel='tag' target='_self'>eclipse</a>, <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/jdave' rel='tag' target='_self'>jdave</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/17/using-jdave-a-quick-introduction-to-specs-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Infinitest: an autotest for Eclipse</title>
		<link>http://giordano.scalzo.biz/2009/09/09/infinitest-an-autotest-for-eclipse/</link>
		<comments>http://giordano.scalzo.biz/2009/09/09/infinitest-an-autotest-for-eclipse/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 17:00:07 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[agile]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[infinitest]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=70</guid>
		<description><![CDATA[In my experimental trips in Ruby world, other than the elegance of the language, the Bdd as default and the lot of new exciting things created by the community, a thing I liked a lot was autotest , a little gem that launches our testsuite when we change a source file.
It could seem a silly [...]]]></description>
			<content:encoded><![CDATA[<p>In my experimental trips in Ruby world, other than the elegance of the language, the Bdd as default and the lot of new exciting things created by the community, a thing I liked a lot was <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">autotest</a> , a little gem that launches our testsuite when we change a source file.<br />
It could seem a silly utility, but I can assure it&#8217;s a really time saver and can take us in a high productive mental flow: I really missed it in Java world.</p>
<p>Of course, I&#8217;ve heard about <a href="http://www.threeriversinstitute.org/junitmax/subscribe.html" target="_blank">Junit Max</a>, the Kent Beck&#8217;s attempt to create a product, but my laziness delayed me to try it, until Kent got bored and dismiss the project <img src='http://giordano.scalzo.biz/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> .</p>
<p>Today while reading distractedly the Twitterverse, I bumped into <a href="http://infinitest.org" target="_blank">Infinitest</a>, that seems exactly what I was looking for.<br />
<a href="http://infinitest.org" target="_blank">Infinitest</a> isn&#8217;t open source, but for personal use it should be possible get a free of charge <a href="http://improvingworks.com/products/infinitest/for-individuals/" target="_blank">individual license</a>.</p>
<p>The installation is straightforward as usual, just add <code>http://update.improvingworks.com </code>to Eclipse&#8217;s software updates, and we are ready to start!</p>
<p><a href="http://infinitest.org" target="_blank">Infinitest</a> stay in the right bottom of Eclipse, waiting far some changes:</p>
<p><img class="aligncenter size-full wp-image-71" title="waiting for changes" src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/waiting.png" alt="waiting for changes" width="441" height="43" /></p>
<p>When we save some file <a href="http://infinitest.org" target="_blank">Infinitest</a> starts and show the results of all test it founds in the project:</p>
<p><img class="aligncenter size-full wp-image-74" title="red test" src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/red.png" alt="red test" width="507" height="199" /></p>
<p>A nice feature is the yellow bar when there is some error in the workspace and tests can&#8217;t run:</p>
<p><img class="aligncenter size-full wp-image-76" title="yellow bar" src="http://giordano.scalzo.biz/wp-content/uploads/2009/09/ytest.png" alt="yellow bar" width="716" height="359" /></p>
<p>That&#8217;s all!<br />
I have to try it more, but it seems very promising and useful.</p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/bdd' rel='tag' target='_self'>bdd</a>, <a class='technorati-link' href='http://technorati.com/tag/eclipse' rel='tag' target='_self'>eclipse</a>, <a class='technorati-link' href='http://technorati.com/tag/infinitest' rel='tag' target='_self'>infinitest</a>, <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/tdd' rel='tag' target='_self'>tdd</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/09/infinitest-an-autotest-for-eclipse/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Bdd with JBehave</title>
		<link>http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/</link>
		<comments>http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 11:50:20 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[bdd]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[jbehave]]></category>
		<category><![CDATA[kata]]></category>

		<guid isPermaLink="false">http://www.scalzo.biz/?p=32</guid>
		<description><![CDATA[Somebody defined Behaviour-Driven Development &#8220;TDD done right&#8221;; maybe is a bit too provocative as definition, but I think it&#8217;s the time to get my hands wet and give Bdd a chance.
JBehave is the first BDD&#8217;s framework, developed by the BDD&#8217;s inventor himself, Dan North, and still one of the more supported in Java community.
I choose [...]]]></description>
			<content:encoded><![CDATA[<p>Somebody defined <a href="http://behaviour-driven.org/" target="_blank">Behaviour-Driven Development</a> &#8220;TDD done right&#8221;; maybe is a bit too provocative as definition, but I think it&#8217;s the time to get my hands wet and give Bdd a chance.</p>
<p><a href="http://jbehave.org/" target="_blank">JBehave</a> is the first BDD&#8217;s framework, developed by the BDD&#8217;s inventor himself, <a href="http://dannorth.net/" target="_blank">Dan North</a>, and still one of the more supported in Java community.</p>
<p>I choose a simple kata to develop in Bdd-way, the StringTemplater kata, as saw in a <a href="http://www.coreyhaines.com/" target="_blank">Corey Haines</a>&#8216; <a href="http://blog.envylabs.com/2009/08/corey-haines-performance-kata/" target="_blank">video</a> and following this excellent <a href="http://www.shaafshah.com/2009/08/12/getting-started-with-jbehave-in-8-steps/" target="_blank">post</a>.</p>
<h3>JBehave on Eclipse: half an hour tutorial</h3>
<p>First of all, we should create a project under Eclipse and add JBehave <a href="http://jbehave.org/software/download/" target="_blank">jars</a>.</p>
<p>Then we should write the basic infrastructure: a textual file with the scenarios and two classes connecting our stories to JBehave.</p>
<p>By default the scenarios file should be without extension and in the same directory of classes, but, aiming to separate specs code and production code, I created a new source directory called <code>scenario</code>.</p>
<p>The scenarios file should have a meaningful name and the words should separated by underscores; in this example I called it <code>replace_tokens_in_string</code>.</p>
<p>At the beginning of the file, we can write the story we should implement: it isn&#8217;t mandatory, but it&#8217;s useful if we use specs to comunicate with the customers.<br />
Following we can write a first basic scenario:</p>
<pre class="brush: bash">Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string
Given I have a StringTemplater
When I ask to replace an emptystring
Then I should get an emptystring</pre>
<p>The story is just descriptive, but the scenario must be of the form of<br />
<code><strong>Given</strong> something<br />
<strong>When</strong> action<br />
<strong>Then</strong> check</code></p>
<p>Now we need create two java classes.<br />
The first one is JBehave wrapper to JUnit TestCase and its name should match the one of textual file converted in CamelCase: in our example should be <code>ReplaceTokensInString</code>.</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.Scenario;

public class ReplaceTokensInString extends Scenario{
	  public ReplaceTokensInString() {
	        super(new ReplaceTokensInStringSteps());
	    }
}</pre>
<p>The second class, <code>ReplaceTokensInStringSteps</code>, implementing the steps of the scenario:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
}</pre>
<p>That&#8217;s it!<br />
As said before, JBehave is built over JUnit so we can run <code>ReplaceTokensInString</code> as Junit test obtaining a message from the engine:</p>
<pre class="brush: bash">Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string

Given I have a StringTemplater (PENDING)
When I ask to replace an emptystring (PENDING)
Then I should get an emptystring (PENDING)</pre>
<p><code>PENDING</code> means we have to build that step; so we do it with an empty implementation:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
	@Given("I have a StringTemplater")
	public void createStringTemplater() {
	}
	@When("I ask to replace an emptystring")
	public void replaceAnEmptystring() {
	}
	@Then("I should get an emptystring")
	public void shouldGetEmptyString() {
	}
}</pre>
<p>and when we run again the test, the <code>PENDING</code> messages should disappear.</p>
<p>This is the basic infrastructure, but, in my tiny experience was the most difficult part: once the empty scenario worked, implement the complete kata was quite straightforward.</p>
<p>This is my final scenarios file:</p>
<pre class="brush: java">Story: replace tokens in String
As a user
I would like replace token in a string with values
So that I can create templates for my configuration files

Scenario: replace empty string
Given I have a StringTemplater
When I ask to replace an emptystring
Then I should get an emptystring

Scenario: replace string without tokens
Given I have a StringTemplater
When I ask to replace 'this string'
Then I should get 'this string'

Scenario: replace string with a token
Given I have a StringTemplater
When I ask to replace 'Hello, $name' with [name : pippo]
Then I should get 'Hello, pippo'

Scenario: replace string with two tokens
Given I have a StringTemplater
When I ask to replace 'Hello, $name, how a $attitude day' with [name : pippo, attitude: wonderful]
Then I should get 'Hello, pippo, how a wonderful day'

Scenario: replace string with two adjacent tokens
Given I have a StringTemplater
When I ask to replace 'Hello, $adj$name' with [name : friend, adj: good]
Then I should get 'Hello, goodfriend'

Scenario: replace string with two tokens and only one value
Given I have a StringTemplater
When I ask to replace 'Hello, $name, how a $attitude day' with [name : pippo]
Then I should get 'Hello, pippo, how a  day'</pre>
<p>This my steps:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.jbehave.Ensure.ensureThat;

import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
	private StringTemplater templater;
	private String result;

	@Given("I have a StringTemplater")
	public void createStringTemplater() {
		templater = new StringTemplater();
	}

	@When("I ask to replace an emptystring")
	public void replaceAnEmptystring() {
		result = templater.replace("");
	}

	@Then("I should get an emptystring")
	public void shouldGetEmptyString() {
		ensureThat(result, is(equalTo("")));
	}

	@When("I ask to replace '$stringToReplace'")
	public void replaceStringWithoutTokens(String stringToReplace) {
		result = templater.replace(stringToReplace);
	}

	@Then("I should get '$expected'")
	public void checkStringResult(String expected) {
		ensureThat(result, is(equalTo(expected)));
	}

	@When("I ask to replace '$stringToReplace' with [$tokens]")
	public void replaceStringWithTokens(String stringToReplace, String tokens) {
		result = templater. replace(stringToReplace,tokens);
	}

}</pre>
<p>and, last but not least, <code>StringTemplater</code> class:</p>
<pre class="brush: java">package biz.scalzo.kata.stringtemplater.jbehave;

import java.util.HashMap;
import java.util.Map.Entry;

public class StringTemplater {

	public String replace(String originaleString) {
		return replace(originaleString, "");
	}

	public String replace(String stringToReplace, String tokensAsString) {
		HashMap tokensMap = splitTokens(tokensAsString);
		return removeKeywordWithoutValue(replaceKeywords(stringToReplace,
				tokensMap));
	}

	private String removeKeywordWithoutValue(String replaceKeywords) {
		return replaceKeywords.replaceAll("\\$\\w+", "");
	}

	private String replaceKeywords(String initialValue,
			HashMap tokensMap) {
		String result = initialValue;
		for (Entry entry : tokensMap.entrySet()) {
			result = result
					.replaceAll("\\$" + entry.getKey(), entry.getValue());
		}
		return result;
	}

	private HashMap splitTokens(String tokensAsString) {
		String[] pairs = splitPairs(tokensAsString);

		HashMap result = new HashMap();
		for (String pair : pairs) {
			String[] tokens = pair.split(":");
			if (tokens.length &gt; 1) {
				result.put(tokens[0].trim(), tokens[1].trim());
			}
		}
		return result;
	}

	private String[] splitPairs(String tokensAsString) {
		return tokensAsString.split(",");
	}
}</pre>
<h3>Conclusions</h3>
<p>This is my first impact with Bdd in Java, I liked and I think it&#8217;s very promising.<br />
Neverthless, I still don&#8217;t know if it is something I can do in day by day work or just a proof of concept: Jbehave is quite verbose and the stories are high level specifications, so we need to write a lot of boilerplate code to specify a class.</p>
<p>In my trip in Bdd-land, next steps will be give other Bdd engines a try, starting with ones written in high level languages as <a href="http://www.easyb.org/" target="_blank">easyb</a> or <a href="http://www.artima.com/scalatest/" target="_blank">scalatest</a>.</p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/bdd' rel='tag' target='_self'>bdd</a>, <a class='technorati-link' href='http://technorati.com/tag/eclipse' rel='tag' target='_self'>eclipse</a>, <a class='technorati-link' href='http://technorati.com/tag/java' rel='tag' target='_self'>java</a>, <a class='technorati-link' href='http://technorati.com/tag/jbehave' rel='tag' target='_self'>jbehave</a>, <a class='technorati-link' href='http://technorati.com/tag/kata' rel='tag' target='_self'>kata</a>, <a class='technorati-link' href='http://technorati.com/tag/tutorial' rel='tag' target='_self'>tutorial</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/04/bdd-with-jbehave/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
