Jan 19 2010

Objective-C for busy Java Developers 1: Calling methods

Category: java,objective-c,tutorialgiordano scalzo @ 2:34 pm

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’m a complete newbie, I’m trying to learn it recalling some well know patterns and scenarios as made in Java , following this good tutorial.

Objective-C has a little strange way to call method, that could be disorienting at first glance:

Java:

object.method;
object.methodWithInput(input);

output = object.methodWithOutput();
output = object.methodWithInputAndOutput(Object input);

Objective-C:

[object method];
[object methodWithInput:input];

output = [object methodWithOutput];
output = [object methodWithInputAndOutput:input];

Obviously, it’s possible to call methods of class, instead of instance:

Java:

Object oString = new String();

Objective-C:

id oString = [NSString string];

The

id

refers any kind of object, so it’s little different from Java counterpart.
Better code is:

Java:

String sString = new String();

Objective-C:

NSString* sString = [NSString string];

With this style, it’s a little cumbersome write nested calls:

Java:

calculator.add(numbers.split());

Objective-C:

[calculator add:[numbers split]];

This syntax disencourage the nesting of more than one method.

Some methods take multiple input arguments, Objective-C deals with that allowing split method names:

Java:

boolean writeToFile(String path, boolean useAuxiliaryFile)

boolean result = myData.writeToFile("/tmp/log.txt", false);

Objective-C:

-(BOOL)writeToFile:(NSString *)path withAuxFile:(BOOL)useAuxiliaryFile;

BOOL result = [myData writeToFile:@"/tmp/log.txt" withAuxFile:NO];

Objective-C has properties built in, in Java you need to implement getters and setters:

Java:

photo.setCaption("Day at the Beach");
output = photo.getCaption();

Objective-C:

photo.caption = @"Day at the Beach";
output = photo.caption;

A property should be marked

@property

in declaration and

@synthesize

in implementation.

To create an object, the function

alloc

should be called and then an init method should be called:

Java:

object = new ComplexObject(1.0f);

Objective-C:

object = [[ComplexObject alloc] initWithFloat:1.0f];

When working in an environment without garbage collector, any object created with alloc should be released:

Objective-C:

[object release];

To complete this introductory post, take a look at this ObjectiveC CheatSheet: it contains all the most used constructs needed to start to code for Mac.

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


Aug 28 2009

Private git repositories on Site5

Category: tutorialgiordano scalzo @ 4:51 pm

It happens I have a shared host on Site5 and it happens most of kool koders are moving to git.
I’m not a so kool koder, but I think git deserve a try.

I know Github offers a wonderful service for open source projects, and I tried it for a bunch of pet works, but something is better to keep private, so, some month ago, I tried to set up a git repository on my Site5 account without success.

Some day ago, I bumped into a couple of posts and, finally, I reached my goal.

Set up a password-less connection

git communication is based on ssh, but a password request each ‘git push’ or ‘git pull’ can be annoying in day-by-day working, so the first thing is to make our connection trusted by the server.
In this post, we can find detailed instructions for a Linux system:

user@localhost:~$ ssh-keygen -t dsa
user@localhost:~$ scp ~/.ssh/id_dsa.pub remoteuser@remotehost:
user@localhost:~$ ssh remoteuser@remotehost:
[remoteuser@remotehost ~]$ cat id_dsa.pub >> .ssh/authorized_keys

For other OS, Google is your friend.

Create a repository on Site5

Some month ago, all Site5‘s servers migrated to the last version of git , but if you can’t find it installed, you can open a ticket: Site5‘s support is always friendly and quick.
Now we can create our repository:

[remoteuser@remotehost ~]$ mkdir -p git/repo.git
[remoteuser@remotehost ~]$ cd git/repo.git
[remoteuser@remotehost ~]$ git --bare init
[remoteuser@remotehost ~]$ exit

and create our local repository:

user@host:~$ mkdir git
user@host:~$ cd git
user@host:~$ git clone ssh://remoteuser@remotehost/~/git/repo.git

user@host:~$ echo 'Here we go' > README
user@host:~$ git add .
user@host:~$ git commit
user@host:~$ git push

Fixing “fatal: no matching remote head”-error

After that, when I tried to push my modifies I got an “fatal: no matching remote head” error… fortunately I wasn’t alone with that problem.
First of all we need create an empty local repository then tell git that the “origin” of the local repository is the remote repository

user@host:~$ cd repo
user@host:~$ git init
user@host:~$ echo 'Here we go' > README
user@host:~$ git add .
user@host:~$ git commit -ma ''
user@host:~$ git push
user@host:~$ git remote add origin ssh://remotehost/~/git/repo.git

Then we have to connect the upstream “origin” with the current local branch:

vi .git/config

and adding the following at the bottom:

[branch "master"]
  remote = origin
  merge = refs/heads/master

Finally we have to synchronize remote with local repository:

git push origin master

After that

git push

and

git pull

should work without problem

Conclusion

When discovered all necessary steps, any new repository installation goes smooth; in this post I tried to be complete and gather all the necessary informations.
If you are new to git in this page you will find some useful links.

Technorati Tags: , , ,

Tags: , , ,