<?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; kata</title>
	<atom:link href="http://giordano.scalzo.biz/tag/kata/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>Milano XpUg January Coding Dojo</title>
		<link>http://giordano.scalzo.biz/2010/02/06/milano-xpug-january-coding-dojo/</link>
		<comments>http://giordano.scalzo.biz/2010/02/06/milano-xpug-january-coding-dojo/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 14:04:58 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[doding dojo]]></category>
		<category><![CDATA[kata]]></category>
		<category><![CDATA[xpug]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=278</guid>
		<description><![CDATA[Lately, I&#8217;m more and more involved in Milan XpUg meetings; last week I had the pleasure to attend my first Coding Dojo.
A Coding Dojo is a meeting where some people practice Tdd and try to learn new things, without schedule and deadline pressure.
As introduction I prepared a little presentation, mainly with the aim to clarify [...]]]></description>
			<content:encoded><![CDATA[<p>Lately, I&#8217;m more and more involved in Milan XpUg meetings; last week I had the pleasure to attend my first Coding Dojo.<br />
A Coding Dojo is a meeting where some people practice Tdd and try to learn new things, without schedule and deadline pressure.<br />
As introduction I prepared a little presentation, mainly with the aim to clarify the &#8220;<a href="http://matteo.vaccari.name/blog/archives/293">Ocp Way</a>&#8221; to do katas, as conceived by <a href="http://matteo.vaccari.name/blog/">Matteo Vaccari in his blog</a>:</p>
<div style="width:425px;text-align:left" id="__ss_3020789"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/giordano/xpug-coding-dojo-katayahtzee-in-ocp-way" title="XpUg Coding Dojo: KataYahtzee in Ocp way">XpUg Coding Dojo: KataYahtzee in Ocp way</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cfakepathxpugcodingdojo1-100129030453-phpapp01&#038;stripped_title=xpug-coding-dojo-katayahtzee-in-ocp-way" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cfakepathxpugcodingdojo1-100129030453-phpapp01&#038;stripped_title=xpug-coding-dojo-katayahtzee-in-ocp-way" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">presentations</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/giordano">giordano scalzo</a>.</div>
</div>
<p>We had a lot of fun, and we are committed to arrange another Dojo, at the end of February.<br />
If someone is interested to practice more, <a href="http://milano-xpug.pbworks.com/f/KataYahtzee.doc">here </a> you can find the text of the kata we practiced and <a href="http://github.com/gscalzo/Code-Kata/tree/KataYahtzee">here</a> the code we produced.</p>

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

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/doding+dojo' rel='tag' target='_self'>doding dojo</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/xpug' rel='tag' target='_self'>xpug</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2010/02/06/milano-xpug-january-coding-dojo/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What I learned doing a Katacast</title>
		<link>http://giordano.scalzo.biz/2009/12/23/what-i-learned-doing-a-katacast/</link>
		<comments>http://giordano.scalzo.biz/2009/12/23/what-i-learned-doing-a-katacast/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 09:32:36 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[me]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[kata]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=258</guid>
		<description><![CDATA[As said before, last week at Milan Xpug meeting, we organized a kata evening, with the same challenge done with different language.
During the practice to reach a quite well solution, I publicized my attempts through Twiiter gaining attention from Corey Haines hinself who asked me if I was interested to appear on katakasts.com as a [...]]]></description>
			<content:encoded><![CDATA[<p>As <a href="http://giordano.scalzo.biz/2009/12/17/stringcalculator-kata-at-xpug/">said before</a>, last week at <a href="http://milano-xpug.pbworks.com/">Milan Xpug</a> meeting, we organized a kata evening, with the same challenge done with different language.<br />
During the practice to reach a quite well solution, I publicized my attempts through Twiiter gaining attention from <a href="http://www.coreyhaines.com/">Corey Haines</a> hinself who asked me if I was interested to appear on <a href="http://www.katacasts.com/">katakasts.com</a> as a guest: wow, I felt like a teenage U2 fan who, while playing in garage, receive a call from The Edge asked him if interest to play some concerts with them!</p>
<p>Anyway, I tried to record a good enough kata, that means without compilation error, in resonable time and typed in smooth way.<br />
That could sound as a straightforward thing to do (I thought it that way), but I invite everyone tho give it a try: I did almost 10 complete recording, not counting all false starts or big mistakes near the end of kata.<br />
I noticed how often I did errors in first steps, I think while I&#8217;m not into the &#8220;flow&#8221;, or at the end, when I start to relax.</p>
<p>Anyway, the only way to perform a Kata in a acceptable time for <a href="http://www.katacasts.com/">katakasts.com</a> (less than 15 minutes) is to master the editor of choice.<br />
I use <a href="http://www.vim.org/">vim </a>for kata, but I&#8217;m far to be &#8216;fluent&#8217; on it! Anyway, to save precious time, I learned a few usefu thricks.</p>
<p>First of all, we need to forget to navigate the text throught <code>'hjkl'</code> or arrows keys, and use the line numbers features of vim.<br />
With this command:</p>
<pre class="brush ruby">
:set number
</pre>
<p>every line will appear with its number.<br />
Almost every command of vim should be applied to a range of rows.<br />
For example with this:</p>
<pre class="brush ruby">
:20,30 co 35
</pre>
<p>we copy the block from line 20 to line 30 to line 35.<br />
Or with this:</p>
<pre class="brush ruby">
:20,30s/java/scala/g
</pre>
<p>we change word <code>java</code> with <code>scala</code> in previous code.<br />
A little variant is</p>
<pre class="brush ruby">
:20,30 co .
</pre>
<p>that copies the block at the current cursor position.</p>
<p>Anyway, you can enjoy these and other basic vim tricks in my Katacast:</p>
<p><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=8326880&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=8326880&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object>
<p><a href="http://vimeo.com/8326880">KataCast: StringCalculator in Scala</a> from <a href="http://vimeo.com/user2802092">giordano scalzo</a> on <a href="http://vimeo.com">Vimeo</a>.</p>

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

<p class='technorati-tags'>Technorati Tags: <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/scala' rel='tag' target='_self'>scala</a>, <a class='technorati-link' href='http://technorati.com/tag/vim' rel='tag' target='_self'>vim</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/12/23/what-i-learned-doing-a-katacast/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Birthday Greetings Kata in Ruby</title>
		<link>http://giordano.scalzo.biz/2009/10/26/birthday-greetings-kata-in-ruby/</link>
		<comments>http://giordano.scalzo.biz/2009/10/26/birthday-greetings-kata-in-ruby/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 20:30:31 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[agile]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[kata]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=208</guid>
		<description><![CDATA[Lately the pratice of Kata seems spreading out very quickly, thanks to work of well known Software Craftsmen as Corey Haynes or the Clean Code evangelist Uncle Bob.
It all started waiting for a kid&#8217;s karate lesson, and now it&#8217;s a well know practice to become a better developer.
Basicly a code kata is a small problem [...]]]></description>
			<content:encoded><![CDATA[<p>Lately the pratice of Kata seems spreading out very quickly, thanks to work of well known Software Craftsmen as <a href="http://www.coreyhaines.com">Corey Haynes</a> or the Clean Code evangelist <a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings">Uncle Bob</a>.</p>
<p><a href="http://codekata.pragprog.com/codekata/2007/01/code_katahow_it.html">It all started</a> waiting for a kid&#8217;s karate lesson, and now it&#8217;s a well know practice to become a better developer.</p>
<p>Basicly a code kata is a small problem to be resolved without any pressure and requests, but to play with different techniques or programming language.</p>
<p>Another interesting point of view considers a code kata as a training for muscles of memory, focusing on repetitions, memorizations of decisions and keyboard shortcuts; the point is: if I get trained to do design decisions at subconscious level, when I&#8217;ll met similar problems I&#8217;ll be very productive, doing the right decision without any logical think.<br />
Amazing, isn&#8217;t it?</p>
<p>The main argument of last <a href="http://milano-xpug.pbworks.com/">Milan Xpug meeting</a> was the <a href="http://matteo.vaccari.name/blog/archives/154">Birthday Greetings Kata</a>, a workshop Matteo Vaccari will submit to next <a href="http://www.xpday.net/Xpday2009/sessions/Birthday%20Greetings%20Kata.html">Xp Days Benelux 2009</a>.<br />
Unfortunately I couldn&#8217;t be present, but I <a href="http://github.com/gscalzo/Birthday-Greetings-Kata/tree/in_ruby">implemented the kata</a> on my own, using Ruby instead of Java.</p>
<p>I enjoyed it very much, and I start thinking to try it still a couple of times and then screencasting it: I&#8217;m far behind <a href="http://katas.softwarecraftsmanship.org/">this level</a>, but review my actions can help me get better.</p>
<pre class="brush: ruby">
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require 'rumbster'
require 'message_observers'
require 'net/smtp'
require 'gserver'
require 'birthday_service'
require 'employee_repository'

describe "Greetings Service" do
	NON_STANDARD_PORT = 10015
	def send_message(to, message)
    		Net::SMTP.start('localhost', NON_STANDARD_PORT) do |smtp|
      			smtp.send_message message, 'your@mail.address', to
    		end
	end
	before :each do
	 	@rumbster =  Rumbster.new(NON_STANDARD_PORT)
   		@message_observer = MailMessageObserver.new
		@rumbster.add_observer @message_observer
		@rumbster.start

		@birthdayService = BirthdayService.new("localhost", NON_STANDARD_PORT);
	end
	after :each do
		@rumbster.stop
	end
	context "with a file with one person born today" do
		before :each do
			@birthdayService.send_greetings EmployeeRepository.new("employee_data.txt"), "2008/10/08"
		end

		it "should send one email" do
			@message_observer.messages.size.should == 1
		end

		it "should send correct message" do
			@message_observer.messages.first.subject.should == "Happy Birthday!"
			@message_observer.messages.first.body.chomp.should == "Happy Birthday, dear John!"
			@message_observer.messages.first.to.should == ["john.doe@foobar.com"]
		end
	end

end
</pre>
<pre class="brush: ruby">
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require "employee_repository"

describe "EmployeeRepository" do
	it "should read Employees from a file" do
		repository = EmployeeRepository.new "employee_data.txt"
	end

	it "should have a well know size" do
		repository = EmployeeRepository.new "employee_data.txt"
		repository.size.should == 3
	end
	it "should return first employee" do
		repository = EmployeeRepository.new "employee_data.txt"
		expected_employee = Employee.new("Doe, John, 1982/10/08, john.doe@foobar.com")
		repository.first.should == expected_employee
	end
	it "should return employees born an a given date" do
		repository = EmployeeRepository.new "employee_data.txt"
		expected_employee = Employee.new("Doe, John, 1982/10/08, john.doe@foobar.com")
		repository.born_on('2008/10/08').first.should == expected_employee
	end
end
</pre>
<pre class="brush: ruby">
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require "message"
require "employee"

describe "Message" do
	before :each do
		@message = Message.new Employee.new("Doe, John, 1982/10/08, john.doe@foobar.com")
	end

	it "should have employee's email as destination" do
		@message.to.should == "john.doe@foobar.com"
	end
	it "should construct a complete body" do
		@message.body.should == "To: john.doe@foobar.com\nSubject: Happy Birthday!\n\nHappy Birthday, dear John!"
	end
end
</pre>
<pre class="brush: ruby">
require "message"

class BirthdayService
	def initialize(host, port)
		@host = host
		@port = port
	end
	def send_greetings(employees, date)
		employees.born_on(date).each do |employee|
			send_message(Message.new employee)
		end
	end
	def send_message(message)
    		Net::SMTP.start(@host, @port) do |smtp|
      			smtp.send_message message.body, 'your@mail.address', message.to
    		end
	end
end
</pre>
<pre class="brush: ruby">
class Employee
	attr_reader :firstname
	attr_reader :lastname
	attr_reader :birthdate
	attr_reader :email
	def initialize(args)
		tokens = args.split(',').map { |e| e.strip }
		@firstname = tokens[1]
		@lastname = tokens[0]
		@birthdate = tokens[2]
		@email = tokens[3]
	end

	def ==(other)
		other.instance_of?(self.class) &#038;&#038;
			@firstname == other.firstname &#038;&#038;
			@lastname == other.lastname &#038;&#038;
			@birthdate == other.birthdate &#038;&#038;
			@email == other.email
	end
end
</pre>
<pre class="brush: ruby">
require 'employee'

class String
	def same_day?(other)
		date1 = split('/')
		date2 = other.split('/')
		date1[1] == date2[1] &#038;&#038; date1[2] == date2[2]
	end
end

class EmployeeRepository
	private
	def skip_header
		@employees.shift
	end

	public
	def initialize(employees_filename)
		@employees = []
		File.open(employees_filename).each_line do |line|
			@employees << Employee.new(line)
		end
		skip_header
	end

	def size
		@employees.size
	end

	def first
		@employees.first
	end

	def born_on(current_date)
		@employees.find_all { |e| e.birthdate.same_day?(current_date) }
	end
end
</pre>
<pre class="brush: ruby">
class Message
	def initialize(employee)
		@employee = employee
	end
	def to
		@employee.email
	end
	def body
		["To: #{to}",
		"Subject: Happy Birthday!",
		"",
		"Happy Birthday, dear #{@employee.firstname}!"].join("\n")
	end
end
</pre>
<p>Interesting I wrote more specs code than production code.</p>
<p>I do like I didn't used any <em>IF</em>, but I don't like to open String to model date and the use of split to tokenize things: I'll focus on thant in next attempt!</p>

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

<p class='technorati-tags'>Technorati Tags: <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/ruby' rel='tag' target='_self'>ruby</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/10/26/birthday-greetings-kata-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bowling Kata with Ruby and RSpec</title>
		<link>http://giordano.scalzo.biz/2009/09/22/bowling-kata-with-ruby-and-rspec/</link>
		<comments>http://giordano.scalzo.biz/2009/09/22/bowling-kata-with-ruby-and-rspec/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 18:59:34 +0000</pubDate>
		<dc:creator>giordano scalzo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[bowling]]></category>
		<category><![CDATA[kata]]></category>
		<category><![CDATA[rspec]]></category>
		<category><![CDATA[vi]]></category>

		<guid isPermaLink="false">http://giordano.scalzo.biz/?p=117</guid>
		<description><![CDATA[Looking around in daily feeds reading, suddenly I realized I never practiced the first code kata: that Bowling Kata that started all.
I decided to implement it while exploring RSpec and configuring my Ruby environment for Windows:
I used to do my programming under  friendly Ubuntu, but  because my recent jobs duties in Delphi, mainly [...]]]></description>
			<content:encoded><![CDATA[<p>Looking around in daily feeds reading, suddenly I realized I never practiced the first code kata: that <a href="http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata">Bowling Kata</a> that started all.<br />
I decided to implement it while exploring RSpec and configuring my Ruby environment for Windows:<br />
I used to do my programming under  friendly Ubuntu, but  because my recent jobs duties in Delphi, mainly I use a Windows Xp system.</p>
<p>Installing Ruby is straightforward thanks to <a href="http://rubyinstaller.org/">RubyInstaller</a>, a wonderful project that let you configure a Ruby environment under Windows; to dive into a complete Bdd flow I configured <a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autospec</a> and <a href="http://www.growlforwindows.com/gfw/default.aspx">Growl</a> following this useful <a href="http://monket.net/blog/2009/07/autotest-growl-for-windows/">post</a>: I advice every Bdd practitioner to give <a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autospec</a> a try, it can save a lot of windows and mental switch&#8230; but it can&#8217;t be told, try it and enjoy it.</p>
<p>While I&#8217;m very happy with Eclipse during Java coding, I never found a satisfactory editor for Ruby code.<br />
So I decided to try to enter in guru world and use <a href="http://www.vim.org/">Vim</a>,  adding a bunch of useful plugin, as the wondeful <a href="http://www.vim.org/scripts/script.php?script_id=2540">snipMate</a> that import the Textmate snippets under Vim.</p>
<p>Back to kata, these are my specs:</p>
<pre class='brush: ruby'>
require File.join(File.dirname(__FILE__), "//spec_helper")

describe Bowling do

	before(:each) do
		@game = Bowling.new
	end

	def roll_many(num, pins)
		num.times do |hit|
			@game.hit(pins)
		end
	end

	it "should score 0 for gutter game" do
		roll_many(20, 0)
		@game.score.should == 0
	end

	it "should score 20 for a pin each frame" do
		roll_many(20, 1)
		@game.score.should == 20
	end

	def roll_spare()
		@game.hit(5)
		@game.hit(5)
	end

	it "should score 20 when make a spare and 3 and 4 after " do
		roll_spare
		@game.hit(3)
		@game.hit(4)
		roll_many(16, 0)
		@game.score.should == 20
	end

	def roll_strike()
		@game.hit(10)
	end

	it "should score 24 when make a strike and 3 and 4 after " do
		roll_strike
		@game.hit(3)
		@game.hit(4)
		roll_many(16, 0)
		@game.score.should == 24
	end
end
</pre>
<p>They are virtually identical to UncleBob&#8217;s ones.</p>
<p>And this is my code:</p>
<pre class='brush: ruby'>
class Bowling
	private
	class Frame
		def initialize
			@rolls = []
			@rolls[0] = @rolls[1] = 0
			@index = 0
		end

		def sum
			@rolls[0]+@rolls[1]
		end

		def strike?
			@rolls[0] == 10
		end

		def spare?
			sum == 10 &#038;&#038; !strike?
		end

		def bonus_for_strike
			sum
		end

		def bonus_for_spare
			@rolls[0]
		end

		def pins=(value)
			@rolls[@index] = value
			@index = @index + 1
		end

		def finished?
			@index > 1 || strike?
		end

	end

	def add_frame?
		@frames.empty? || @frames.last.finished?
	end

	public

	def initialize
		@frames = []
	end

	def hit(pins)
		@frames << Frame.new if add_frame?
		@frames.last.pins=pins
	end

	def score
		was_spare = false
		was_strike = false
		@frames.inject(0) do |score, current_frame|
			if(was_strike)
				score = score + current_frame.bonus_for_strike
			end
			if(was_spare)
				score = score + current_frame.bonus_for_spare
			end
			was_spare = current_frame.spare?
			was_strike = current_frame.strike?

			score + current_frame.sum

		end
	end
end
</pre>
<p>I'm quite satisfied for the result, I like the encapsulation of responsibility inside <code>Frame</code>, but I don't like at all the fact I saved a state during the score's calculation: I will focus on that in next practice.  </p>
<p>At last, the environment created has been very friendly, I didn't miss Eclipse for normal developing, maybe I miss a bit a helper for extracting method, but with snippets and the Vim shortcuts, I gained a lot of productivity.</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/bowling' rel='tag' target='_self'>bowling</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/rspec' rel='tag' target='_self'>rspec</a>, <a class='technorati-link' href='http://technorati.com/tag/ruby' rel='tag' target='_self'>ruby</a>, <a class='technorati-link' href='http://technorati.com/tag/vi' rel='tag' target='_self'>vi</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://giordano.scalzo.biz/2009/09/22/bowling-kata-with-ruby-and-rspec/feed/</wfw:commentRss>
		<slash:comments>0</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>
