Sep 24 2009

Installing Sinatra on Site5

Category: ruby,tutorialgiordano scalzo @ 11:28 am

I think Rails is a wonderful framework that boosts the success of Ruby, but sometimes is a a little overkill.
Enter Sinatra, a microframework in Ruby, aims to create simple web applications.

As mentioned in a previous post, I own a shared access on a Site5, so I began to search any documentation to install a simple Sinatra app on Site5.
I didn’t find a lot of documentation, but a post gave some hints in the right direction.

First of all, it need to install locally Sinatra gem configuring GEM_PATH and GEM_HOME.
Then we need to create a subdomain, i.e. sinatra.scalzo.biz, where we’ll implement Sinatra’s app. For an unknown reason, I’d to configure a subdirectory as document root:

Domain Configuration

The htaccess directory contains the file .htaccess that enables Phusion Passenger:

PassengerEnabled on
RackBaseURI /

In parent directory we write the Phusion Passenger configuration, config.ru:

ENV['GEM_PATH'] = "/home/USER/gems:/usr/lib/ruby/gems/1.8"
ENV['GEM_HOME'] = "/home/USER/gems"
require 'rubygems'
require 'sinatra'

require 'app'
run Sinatra.application

and our Sinatra application (I call it app):

get '/' do
  "Hello World!"
end
get '/hi' do
  "Hi World!"
end

That’s it!
Now we can call the urls ‘http://sinatra.scalzo.biz/‘ and ‘http://sinatra.scalzo.biz/hi‘.

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 18 2009

Extreme Refactoring or Is Guard clause Considered harmful?

Category: agile,javagiordano scalzo @ 4:56 pm

During the JDave try, the focus was on Bdd side of the exercise, but, nonetheless, the StringTemplater’s code was yelling “Refactor me! Refactor me!” at me :-) .

Actually, that I like least, it’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 "$" + pair[0].trim();
	}

Usually I like that pattern, it’s a well know way to avoid nested conditional, but Anti-If Campaign, promoted by Francesco Cirillo made me think.

The first try didn’t satisfied me:

private String name(String[] pair) {
		return  (pair.length != 2) ? "" : "$" + pair[0].trim();
	}

Indeed, I believe it’s more cryptic and ugly than the original one.

Looking the code more carefully, I saw another thing: I was violating the principle “Ask, don’t tell“, handling some data that could be tied together.

Creating the new class, I thought another thing:
Why am I using the ‘IF?”
I did for avoid a runtime exception… but is an exception evil?
It isn’t if we can handle it!

So at the end this is my final product:

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 initialIterator(String markers) {
		return Arrays.asList(markers.split(",")).iterator();
	}

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

	private String replaceMarker(String stringToReplace,
			Iterator 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 = "";
			}
		}
	}
}

I think a I could refactor more, but I was enough satisfied: I reached my goal to avoid IF and I’ve start to think the exception in different way.

Technorati Tags: , ,

Tags: , ,


Sep 17 2009

Using JDave: A quick introduction to specs framework

Category: bdd,java,tutorialgiordano scalzo @ 5:13 pm

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’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 JBehave, I implemented the StringTemplater kata, as in my previous post.

Installing JDave

After creating a java project, I simply downloaded the last version of JDave and extracted all jar in lib directory of my project:

JDave Jars

They are a lot of jars, and I’m sure I won’t use all of them, but it’s just a try so it doesn’t deserve the time to filter only the used ones.

JBehave is a story runner, so each scenario must be written as:

Given something
When something happens
Then this happens

Instead, JDave is a specification engine and each scenario show a behavior of a class:

AThingIWantToWrite
  - ShouldDoThis
  - ShouldDoThat
  - ShouldntDoThat

In other words, JBehave is similar to Cucumber, JDave is similar to RSpec.

Writing a specification is really straightforward:
first of all, we create a Specification object, passing the object we want to write; then we create a serie of inner classes:

@RunWith(JDaveRunner.class)
public class StringTemplaterSpec extends Specification<ThingIWantToWrite> {
	public class AThingIWantToWrite {
		public void ShouldDoThis() {
		}
		public void ShouldDoThat() {
		}
        }
   ...
}

As JBehave, JDave is a wrapper built over JUnit, so we can use our Ide integration to run the specifications.
That’s it!

The code

As in JBehave try, I implemented the same scenarios as in Corey Haines Video:

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<StringTemplater> {
	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"));
		}
	}

}

The Junit view of Eclipse is very explicative of the behaviors of StringTemplater:
JUnit View

For sake of completeness, this is the final implementation of StringTemplater:

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<String> initialIterator(String markers) {
		return Arrays.asList(markers.split(",")).iterator();
	}

	private String replace(String stringToReplace, Iterator<String> 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();
	}
}

Conclusions

JDave is very easy to learn and the specifications written throught it are very complete and expressive.
If I have to make a choice, I liked slightly more JDave, but I think are just two tools: BDD is a way to think, not a framework or an engine to use.

In conclusions, I believe JBehave and JDave 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.

Technorati Tags: , , ,

Tags: , , ,


Sep 09 2009

Infinitest: an autotest for Eclipse

Category: agile,bdd,javagiordano scalzo @ 7:00 pm

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 utility, but I can assure it’s a really time saver and can take us in a high productive mental flow: I really missed it in Java world.

Of course, I’ve heard about Junit Max, the Kent Beck’s attempt to create a product, but my laziness delayed me to try it, until Kent got bored and dismiss the project :-( .

Today while reading distractedly the Twitterverse, I bumped into Infinitest, that seems exactly what I was looking for.
Infinitest isn’t open source, but for personal use it should be possible get a free of charge individual license.

The installation is straightforward as usual, just add http://update.improvingworks.com to Eclipse’s software updates, and we are ready to start!

Infinitest stay in the right bottom of Eclipse, waiting far some changes:

waiting for changes

When we save some file Infinitest starts and show the results of all test it founds in the project:

red test

A nice feature is the yellow bar when there is some error in the workspace and tests can’t run:

yellow bar

That’s all!
I have to try it more, but it seems very promising and useful.

Technorati Tags: , , , ,

Tags: , , , ,


Sep 07 2009

Scrum in an Hour

Category: agile,presentationgiordano scalzo @ 10:50 pm

Some time ago, I attended a Scrum Master Course (I’m embarrassed to call it Certification…) held by the Agile pioneer and team dynamics expert Joseph Pelrine.

It was an exciting and enriching experience, although little sigular because we were only two student: Pierlugi Pugliese and me!

Anyway, back to work my boss asked me to prepare a little presentation on Scrum to the upper and middle management; so I looked around and took several sources to write a simple, but appealing presentation.

The presentation was a success so that I performed it three more time to the whole Engineering department!

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: , , , , ,


Sep 01 2009

About me 2.0

Category: megiordano scalzo @ 8:53 am

I these frenetic 2.0 times, we need a way to distinguish from the masses.
Someone say the blog is the new resume, and this is one of the reason I started to blog more frequently.

But to attract more busy people, another approach is to create an appealing presentation and share it on Slideshare.

So, after some days of working, here it is my visual resume.
I think is quite good, but my opinion isn’t very important ;-) .

Technorati Tags:

Tags: