Feb 06 2010

Milano XpUg January Coding Dojo

Category: java,presentationgiordano scalzo @ 3:04 pm

Lately, I’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 the “Ocp Way” to do katas, as conceived by Matteo Vaccari in his blog:

We had a lot of fun, and we are committed to arrange another Dojo, at the end of February.
If someone is interested to practice more, here you can find the text of the kata we practiced and here the code we produced.

Technorati Tags: , ,

Tags: , ,


Dec 23 2009

What I learned doing a Katacast

Category: me,presentationgiordano scalzo @ 10:32 am

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 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!

Anyway, I tried to record a good enough kata, that means without compilation error, in resonable time and typed in smooth way.
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.
I noticed how often I did errors in first steps, I think while I’m not into the “flow”, or at the end, when I start to relax.

Anyway, the only way to perform a Kata in a acceptable time for katakasts.com (less than 15 minutes) is to master the editor of choice.
I use vim for kata, but I’m far to be ‘fluent’ on it! Anyway, to save precious time, I learned a few usefu thricks.

First of all, we need to forget to navigate the text throught 'hjkl' or arrows keys, and use the line numbers features of vim.
With this command:

:set number

every line will appear with its number.
Almost every command of vim should be applied to a range of rows.
For example with this:

:20,30 co 35

we copy the block from line 20 to line 30 to line 35.
Or with this:

:20,30s/java/scala/g

we change word java with scala in previous code.
A little variant is

:20,30 co .

that copies the block at the current cursor position.

Anyway, you can enjoy these and other basic vim tricks in my Katacast:

KataCast: StringCalculator in Scala from giordano scalzo on Vimeo.

Technorati Tags: , ,

Tags: , ,


Oct 26 2009

Birthday Greetings Kata in Ruby

Category: agile,ruby,tutorialgiordano scalzo @ 9:30 pm

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’s karate lesson, and now it’s a well know practice to become a better developer.

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.

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’ll met similar problems I’ll be very productive, doing the right decision without any logical think.
Amazing, isn’t it?

The main argument of last Milan Xpug meeting was the Birthday Greetings Kata, a workshop Matteo Vaccari will submit to next Xp Days Benelux 2009.
Unfortunately I couldn’t be present, but I implemented the kata on my own, using Ruby instead of Java.

I enjoyed it very much, and I start thinking to try it still a couple of times and then screencasting it: I’m far behind this level, but review my actions can help me get better.

$:.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
$:.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
$:.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
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
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) &&
			@firstname == other.firstname &&
			@lastname == other.lastname &&
			@birthdate == other.birthdate &&
			@email == other.email
	end
end
require 'employee'

class String
	def same_day?(other)
		date1 = split('/')
		date2 = other.split('/')
		date1[1] == date2[1] && 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
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

Interesting I wrote more specs code than production code.

I do like I didn't used any IF, 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!

Technorati Tags: ,

Tags: ,


Sep 22 2009

Bowling Kata with Ruby and RSpec

Category: bdd,ruby,Uncategorizedgiordano scalzo @ 8:59 pm

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 I use a Windows Xp system.

Installing Ruby is straightforward thanks to RubyInstaller, a wonderful project that let you configure a Ruby environment under Windows; to dive into a complete Bdd flow I configured autospec and Growl following this useful post: I advice every Bdd practitioner to give autospec a try, it can save a lot of windows and mental switch… but it can’t be told, try it and enjoy it.

While I’m very happy with Eclipse during Java coding, I never found a satisfactory editor for Ruby code.
So I decided to try to enter in guru world and use Vim, adding a bunch of useful plugin, as the wondeful snipMate that import the Textmate snippets under Vim.

Back to kata, these are my specs:

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

They are virtually identical to UncleBob’s ones.

And this is my code:

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 && !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

I'm quite satisfied for the result, I like the encapsulation of responsibility inside Frame, 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.

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.

Technorati Tags: , , , , ,

Tags: , , , , ,


Sep 04 2009

Bdd with JBehave

Category: bdd,java,tutorialgiordano scalzo @ 1:50 pm

Somebody defined Behaviour-Driven Development “TDD done right”; maybe is a bit too provocative as definition, but I think it’s the time to get my hands wet and give Bdd a chance.

JBehave is the first BDD’s framework, developed by the BDD’s inventor himself, Dan North, and still one of the more supported in Java community.

I choose a simple kata to develop in Bdd-way, the StringTemplater kata, as saw in a Corey Hainesvideo and following this excellent post.

JBehave on Eclipse: half an hour tutorial

First of all, we should create a project under Eclipse and add JBehave jars.

Then we should write the basic infrastructure: a textual file with the scenarios and two classes connecting our stories to JBehave.

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 scenario.

The scenarios file should have a meaningful name and the words should separated by underscores; in this example I called it replace_tokens_in_string.

At the beginning of the file, we can write the story we should implement: it isn’t mandatory, but it’s useful if we use specs to comunicate with the customers.
Following we can write a first basic scenario:

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

The story is just descriptive, but the scenario must be of the form of
Given something
When action
Then check

Now we need create two java classes.
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 ReplaceTokensInString.

package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.Scenario;

public class ReplaceTokensInString extends Scenario{
	  public ReplaceTokensInString() {
	        super(new ReplaceTokensInStringSteps());
	    }
}

The second class, ReplaceTokensInStringSteps, implementing the steps of the scenario:

package biz.scalzo.kata.stringtemplater.jbehave;

import org.jbehave.scenario.steps.Steps;

public class ReplaceTokensInStringSteps extends Steps {
}

That’s it!
As said before, JBehave is built over JUnit so we can run ReplaceTokensInString as Junit test obtaining a message from the engine:

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)

PENDING means we have to build that step; so we do it with an empty implementation:

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() {
	}
}

and when we run again the test, the PENDING messages should disappear.

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.

This is my final scenarios file:

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'

This my steps:

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);
	}

}

and, last but not least, StringTemplater class:

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 > 1) {
				result.put(tokens[0].trim(), tokens[1].trim());
			}
		}
		return result;
	}

	private String[] splitPairs(String tokensAsString) {
		return tokensAsString.split(",");
	}
}

Conclusions

This is my first impact with Bdd in Java, I liked and I think it’s very promising.
Neverthless, I still don’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.

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 easyb or scalatest.

Technorati Tags: , , , , ,

Tags: , , , , ,