Alexandre Martins’ Blog

On software & technology

Archive for the ‘Java’ tag

Hamcrest Out Of Test Code!

with 7 comments

It’s been a while since I read some interesting posts showing creative uses of Hamcrest library out of test code. Since then I’ve been proscrastinating to implement my own version, trying strongly typed java delegates.

Thankfully this week I came across a nice API called hamcrest-collections. It uses Hamcrest to implement features such as select, reject, map, reduce and zip familiar from languages like Ruby and Python.

Selectors

Selectors can be used to select or reject items that matches a given Matcher, from any iterable object. It reminds me the Specification Pattern from Domain-Driven Design, which is also used for querying objects that satisfies defined specifications.

public static final Person john = new Person("John", 28);
public static final Person nicole = new Person("Nicole", 12);
public static final Person ryan = new Person("Ryan", 23);
public static final Person nathan = new Person("Nathan", 18);

public static final List list() {
    return Arrays.asList(john, nicole, ryan, nathan);
}



The code below selects from the list of users defined above, the ones that are under twenty.

@Test
public void should_select_only_people_under_twenty_years_old() {
    List users = Person.list();
    Iterable underTwentyList = select(users, underAge(20));
    assertThat(underTwentyList, hasItems(nicole, nathan));
    assertThat(underTwentyList, not(hasItems(john, ryan)));
}



The code below rejects all the users that are under twenty.

@Test
public void should_reject_every_people_under_twenty_years_old() {
    List users = Person.list();
    Iterable aboveTwentyList = reject(users, underAge(20));
    assertThat(aboveTwentyList, hasItems(john, ryan));
    assertThat(aboveTwentyList, not(hasItems(nicole, nathan)));
}


Map and Reduce

Map is used to apply a function onto each item in any iterable object, whereas Reduce combines all these elements, applying a Reducer implementation. In our example, we map the timesTwo function, that doubles each element in the list, and then we reduce it by adding up all of them.

@Test
public void should_double_each_number_in_the_list_then_sum_all_of_them() {
    List numbers = Arrays.asList(1, 2, 3);
    MultiplyBy timesTwo = new MultiplyBy(2);

    Iterable result = map(numbers, timesTwo);
    assertThat(result, hasItems(2, 4, 6));

    Integer sum = reduce(result, new Sum());
    assertThat(sum, equalTo(12));
}


public class MultiplyBy implements Function {
    private Integer factor;

    public MultiplyBy(Integer factor) {
        this.factor = factor;
    }

    public Integer apply(Integer number) {
        return (int)number * factor;
    }
}


public class Sum implements Reducer {
    public Integer apply(Integer first, Integer second) {
        return first + second;
    }
}


Despite the bias created by some developers, that Hamcrest should not be used anywhere else but test code, specially after JUnit has defined it as its new matcher library, just ignore it and add these features to your runtime library, so that you can let your creativity drive you when developing. Get rid of “for” loops from your life! :)

Written by Alexandre Martins

February 19th, 2009 at 6:38 am

Clojure: Integrating With Java

with 3 comments

Currently I am learning Clojure. It is a functional programming language, but not a pure one, since you can both write code that share state (mutable) and also ones that doesn’t.

Why Clojure?

The main reason why I chose Clojure is its easy interoperability with Java, still one of the most used languages, bringing to it the power of Lisp. It’s fast, since the code is compiled, and it supplements some of Java’s weakness, such as the Collections framework and concurrent programming. It is pretty straightforward to write concurrent programs, everything is automatic, no manual lock management!

Integrating With Java

Importing classes

A single class:

(import java.util.List)

Multiple classes from the same package:

(import '(java.util List Set))

Creating instances

Using Java’s new keyword:

(new java.util.ArrayList)
(new ArrayList) ; after importing

Assigning a new List to a Clojure variable:

(def list (new java.util.List))
-> #'user/list

Syntactic Sugar:

(ArrayList.)

Accessing fields

Static fields:

(. Math PI)

Syntactic Sugar:

Math/PI

Invoking methods

Static Methods

(.currentTimeMillis System)

Syntactic Sugar:

(System/currentTimeMillis)

Non-static Methods

(. list size)
(. list get 0) ; returns the object stored at index 0

Syntactic Sugar:

(.size list)

Mixing Them All

Clojure provides a macro called memfn that makes possible execute Java methods as functions. So, for a list of String objects, if I want to make all of them upper-case, all I have to do is:

(map (memfn toUpperCase) ["a" "short" "message"])

The map function applies the function/method toUpperCase to each element in ["a" "short" "message"]

You can also use the bean function to wrap a Java bean in an immutable Clojure map.

(bean (new Person "Alexandre" "Martins"))
-> {:firstName "Alexandre", :lastName "Martins"}

Once converted, you can manipulate the new map using any of Clojure’s map functions, like:

(:firstName (bean (new Person "Alexandre" "Martins")))
-> Alexandre

The code above extracts the firstName key, originally from the Person object.

Written by Alexandre Martins

January 1st, 2009 at 12:44 am

Acceptance Tests With JBehave, Selenium & Page Objects

with 5 comments

Since JBehave 2.0 was released in September, I’ve been using it on my current project to verify the acceptance criteria for the features we are implementing, ensuring that the web interface is following the right workflow, and is displaying the data as expected, as well as some other important elements.

What is JBehave?

JBehave is a framework for Behaviour-Driven Development, that allows customers and developers to work together more closely on features for the system. They get together to discuss and define a set of executable criteria (scenarios) for each of the features that will be used to determine if they are fully implemented or not. The cool thing is that the scenario execution produces an easy-to-read output, so that customers can keep track of the implementation status.

An Example

In this example, I’m not covering all the bits and pieces about writing and running acceptance tests with JBehave. If you want to see it in details, there’s a very good introduction article here. The intention is to show how we are doing it on my project, integrating with Selenium and using the Page Objects pattern.

New Feature

Suppose the customer wanted to provide exclusive content for the user of the website. For that, we would have to implement an authentication framework, so that we could guarantee that only registered users would access that content. So the story looks like this:

As an user
I want to login into the website
So that I can view the exclusive contents

Defining Scenarios

Scenario: Invalid Username
Given the user is on the login page
 When the user types username wrong!
  And the user types password 123456
  And clicks the login button
 Then the page should display Invalid Authentication message

Scenario: Successful Login
Given the user is on the login page
 When the user types username alexandre
  And the user types password 123456
  And clicks the login button
 Then the user should be redirected to home page
  And the page should display welcome message to alexandre

Each scenario needs its own implementation, providing the necessary steps to be verified, in our case the LoginSteps class. Another improvement on version 2.0 is that it allows you to define multiple scenarios in a single file.

public class LoginScenarios extends Scenario {
	public LoginScenarios() {
		super(new LoginSteps());
	}
}

Defining Steps (Integrating Selenium)

After defining the scenarios on the text file, it’s time to map each scenario step to its implementation. Once you start mapping them you will come across ones that are already mapped, and will realise that defining new scenarios is just a matter of combining existing steps.

Initially, for each step, we were extracting the code sniped from Selenium IDE record and placing into it. But it felt a bit clumsy, with code duplication in some spots. It quickly reminded me how hard it is to maintain a suite of tests when it starts evolve and there is not enough effort on refactoring. We wanted to avoid duplication and come up with a more elegant and reusable solution.

One day my friend Uday Rayala came up with the idea of using the Page Objects pattern for writing our acceptance tests, so that we could encapsulate the logic to interact and verify page state into these objects. The first time I heard about it was from Simon Stewart, when he was in Sydney for the JAOO conference. He said that they implemented WebDriver based on this pattern, and showed me some examples. Here is a definition, extracted from the WebDriver wikipage:


Within your web app’s UI there are areas that your tests interact with. A Page Object simply models these as objects within the test code. This reduces the amount of duplicated code and means that if the UI changes, the fix need only be applied in one place.

public class LoginSteps extends Steps {

	@Given("the user is on the login page")
	public void theUserIsOnTheLoginPage() {
		LoginPage loginPage = new LoginPage();
		loginPage.verifyPresenceOfUsernameAndPasswordFields();
		loginPage.verifyPresenceOfLoginButton();
	}

	@When("the user types username $username")
	public void theUserTypesUsername(String username) {
		loginPage().typeUsername(username);
	}

	@When("the user types password $password")
	public void theUserTypesPassword(String password) {
		loginPage().typePassword(password);
	}

	@When("clicks the login button")
	public void clicksTheLoginButton() {
		loginPage().login();
	}

	@Then("the page should display $errorMessage message")
	public void thePageShouldDisplayErrorMessage(String errorMessage) {
		loginPage().verifyPresenceOfErrorMessage(errorMessage);
	}

	@Then("the user should be redirected to home page")
	public void theUserShouldBeRedirectedToHomePage() {
		HomePage homePage = new HomePage();
		homePage.verifyPage();
	}

	@Then("the page should display welcome message to $user")
	public void thePageShouldDisplayWelcomeMessage(String user) {
		homePage().verifyPresenceOfWelcomeMessageTo(user);
	}

	private LoginPage loginPage() {
		return (LoginPage) Page.current();
	}

	private HomePage homePage() {
		return (HomePage) Page.current();
	}
}

Written by Alexandre Martins

November 14th, 2008 at 6:30 pm

Spring MVC, almost there!

without comments

One of the things I really like about Spring 2.5 is the new set of annotations for defining controllers.
Now you don’t have to extend any superclass to turn your class into a controller, just add the @Controller annotation on the top of the class definition and that’s it, you got one (still have to define it as a bean in the XML file). Another cool feature in this set, is the combination of the @RequestMapping and @RequestParam annotations.

@Controller
public class ProductController {

	@Autowired
	private MemberRepository repository;

	@RequestMapping(value="/product", method=RequestMethod.GET)
	public String product(@RequestParam(value="id") String id, ModelMap model) {
		model.addAttribute("product", repository.getProduct(id));
		return "product/view";
	}
}

@RequestMapping gives you flexibility to map methods in the controller to whatever URIs and HTTP methods (default to RequestMethod.GET) you like. They are not dependent on another or on controller’s name. This really turns things easier when mapping your methods to RESTful URIs. The only downside in this implementation is that it doesn’t allow you to pull out parameters from an URI. If you want to grab some data from the URL, you are going to have to do it the old fashioned way, like:

mystore/product?id=123456

But on the other hand the @RequestParam annotation frees you from the dirty job of extracting parameters from a request. Thus, you don’t even need to know about the HttpServletRequest and HttpServletResponse objects. To retrieve a parameter from a request, just add it as a method parameter and define it as a @RequestParam. The value attribute on the annotation should match the URL parameter name.

@RequestMapping("/products")
public String products(@RequestParam(value="letter", required=false) String letter, ModelMap model) {
	checkLetter(letter);
	model.addAttribute("products", repository.getProducts(letter));
	return "product/list";
}

You also have the option of defining a request parameter as required or not (default set to required), so as in the example above, the method would be able to handle requests coming from both mystore/products, to list all existent products, and mystore/products?letter=A, to list all existent products starting with the letter ‘A’. Really neat!

The good news is that Spring 3.0 is coming out next November, and it will include the URI templating functionality. According to Springify blog, you will be able to define a URI like mystore/product/123456, and that will map to the controller method as follows:

@RequestMapping("/product/${id}")
public String product(@RequestParam("id") String id, ModelMap model) {
	model.addAttribute("product", repository.getProduct(id));
	return "product/view";
}

So let’s wait for it!

Written by Alexandre Martins

September 30th, 2008 at 3:07 am

Benefits of supporting tools

without comments

One of the deliverables to our current client is a project template, containing tools to guide them to build better software, ensuring lower bug occurrence and system integrity.
One tool we are using is Findbugs. One day, when running it, we came across an interesting issue, Findbugs was complaining that a class in a project was exposing its internal state, subjecting it to unexpected modifications. The class contained a single constructor with parameters setting its initial state and a set of getter methods. Any Java developer used to getters and setters pattern would say that the code below is valid.

public class Person {

	private String name;
	private Date dateOfBirth;

	public Person(String name, Date dateOfBirth) {
		this.name = name;
		this.dateOfBirth = dateOfBirth;
	}

	public Date getDateOfBirth() {
		return dateOfBirth;
	}
	public String getName() {
		return name;
	}
}

What would happen if you create a Person instance passing as parameter, pre-defined name and dateOfBirth variables and then, perform operations over these variables, modifying its states? And what if you retrieve these attributes (through getter methods), assigning them to new variables and start performing operations over them? For the name attribute it wouldn’t be a problem, since String objects are immutable, but certainly both cases would affect the dateOfBirth attribute, corrupting the state of the object.

One of the solutions to this problem would be to make getter methods always return a new object, copy of the original one and during object construction, initialize instance variables with new objects, copy from the original ones passed as constructor parameters.

public class Person {
	...

	public Person(String name, Date dateOfBirth) {
		this.name = name;
		this.dateOfBirth = new Date(dateOfBirth.getTime());
	}

	public Date getDateOfBirth() {
		return new Date(dateOfBirth.getTime());
	}
	...
}

So, unless the objects you are implementing are good citizens and contains side-effect-free functions, you should consider programming in a more defensive way, to avoid unexpected behaviors in your project and also make use of tools like Findbugs to turn the development easier. Checkstyle and Cobertura are a good start.

Written by Alexandre Martins

April 15th, 2008 at 5:16 pm

Posted in Coding

Tagged with , ,

Seeking code quality

without comments

This week, during another refactoring session, I had the idea that every time I come across code that needs to be modified to conform to one of the principles of best practices for software development, I’ll modify it and share the solution through this blog, exploring its drawbacks, benefits gained by conforming to the principle and also providing a brief explanation of it. Starting now with the OCP - Open-Closed Principle.

The Open-Closed Principle

This principle is the foundation for building code that is maintainable and reusable. Modules that conform to this principle are, at the same time, “open for extension”, so that they can behave in different ways, as the requirements of the application are modified or as new ones are added. And “closed for modification”, which means that the module implementation cannot be violated, nobody can modify its source code.

The description above may seem quite contradictory, since to extend a module functionality, a code modification needs to be done. Therefore, we deduce that a functionality that cannot be modified is given as fixed. How could we deal with this conflict? The best way is to show it up through an example.

In my current project, there’s a task manager module, which is responsible for executing asynchronous tasks queued up by its clients. Basically it iterates over all the elements in a pending tasks list and executes each of them, respecting the order they appear. The excerpt below shows how this class was implemented, it’s a bit different from the original version, making it easier to understand.

public class TaskManager {

    public List pendingTasks;

    public void executePendingTasks() {
        for (Task task : pendingTasks) {

            switch (task.type()) {
            case computeTrophies:
                engine.computeTrophies();
                break;

            case computeStatistics:
                engine.computeStatistics();
                break;

               // .... and so on ....
            }
        }
    }
}

The method executePendingTasks() doesn’t conform to the Open-Closed Principle, because it cannot be closed against new task implementations. If your client suddenly comes up, asking you to extend the task manager module, to start handling a new task — this is always happening and since we’re all agile, we’re ready to handle it eh? — so this method will always have to be modified to support a new task. This can be easily done by inserting a new case statement, but it’s far from an elegant solution.

Unfortunately most of developers follow this approach, the easier one (seemingly), specially when dealing with legacy code, when the solution is already “thought”. All they have to do is follow the way the implementation has been done, not assessing it. Eventually, the code ends up with a huge number of lines (eighteen case statements in my case) and at that time, luckily, maybe a sensible developer will realize the code oddity and will try to improve its quality.

In the following excerpt, I’m showing the solution I gave to the problem, conforming to the OCP. Summarizing, the Task class is now abstract and I included an abstract method called execute(). Following this approach, ALL new tasks being created will be derivatives of this abstract class, providing their implementations of the execute() method.

public class abstract Task {
    public abstract void execute();
}
public class ComputeTrophiesTask extends Task {
    public void execute() {
        // logic to compute trophies...
    }
}
public class ComputeStatisticsTask extends Task {
    public void execute() {
        // logic to compute statistics...
    }
}

And from now on, to our task manager, executing the pending tasks has became much easier. All it has to do is go through each of them and invoke their execute() method, resulting a cleaner, decoupled and non-intrusive code.

public class TaskManager {

    public List pendingTasks;

    public void executePendingTasks() {
        for (Task task : pendingTasks) {
            task.execute();
        }
    }
}

Now if we want to extend executePendingTasks() to start executing any other new task, all we need to do is create a new derivative of the Task class. This method is now conforming to the Open-Closed Principle. Its behaviour can be extended but its implementation doesn’t change.

Written by Alexandre Martins

September 21st, 2007 at 3:23 pm

PicoContainer is alive!

without comments

Paul Hammant has just announced the PicoContainer 2.0 beta release. I’m particularly happy with the news, because I thought they had stopped to work on this project and I’ve always preferred this dependency injection container, its configuration is quite simple. So now it’s time to check it out!

Written by Alexandre Martins

July 18th, 2007 at 5:41 pm

Posted in News

Tagged with , ,

JBehave Matchers

without comments

JBehave and JMock2 are tools I’ve been using on my latest projects to define the behaviours of my objects. Both, when used together supplies pretty much all the resources needed to write effective behaviour verification. But in this topic I’m going to talk about JBehave Matchers.

Matchers are handy objects, inspired by JUnit Assert class, but much more elaborated. They can help us in loads of scenarios, without the need to write repeated code, such as loops, ifs, elses, turning out the code cleaner and much more intuitive. Currently there are six matcher subtypes: UsingArrayMatchers, UsingCollectionMatchers, UsingEqualityMatchers, UsingExceptions, UsingLogicalMatchers e UsingStringMatchers. For now, I’m just going to talk about four of them, which for me are the most innovative ones.

UsingArrayMatchers e UsingCollectionMatchers

Both are quite similar in their behaviours, the only thing that distinguishes them, as their names indicates, is the object on which operations are executed upon. I decided using the UsingArrayMatchers matcher to show some examples of features it comprises:

1 - Check if a Collection/Array contains a certain object:

Integer[] array = new Integer[] {3};
Ensure.that(array, contains(3));
Ensure.that(array, not(contains(5)c));

2 - Check if a Collection/Array contains a certain set of objects:

Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, contains(3, 4));
Ensure.that(array, contains(3, 4, 5));

3 - Check if a Collection/Array contains only a certain set of objects, and nothing more:

Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, containsOnly(3, 4, 5));
Ensure.that(array, not(containsOnly(3, 4)));

4 - Check if a Collection/Array contains a certain set of objects, in a defined order:

Integer[] array = new Integer[] {3, 4, 5};
Ensure.that(array, containsInOrder(3, 4, 5));
Ensure.that(array, not(containsInOrder(4, 5, 3)));

UsingStringMatchers

The methods in this class are self-explanatory, just check it out:

Ensure.that("octopus", contains("top"));
Ensure.that("octopus", not(contains("pee")));
Ensure.that("octopus", startsWith("octo"));
Ensure.that("octopus", not(startsWith("pee")));
Ensure.that("octopus", endsWith("pus"));
Ensure.that("octopus", not(endsWith("pee")));

UsingLogicalMatchers

Using this class, it’s possible to negate any matcher and define matcher compositions using AND, OR, EITHER, BOTH. This class for me is the most powerful one, it gives us a wide range of interesting possibilities. Let’s try some of them, so you can see how far you can go.

1 - Using conditional matchers:

String horse = "horse";
String cow = "cow";

Ensure.that(horse, or(eq(horse), eq(cow)));
Ensure.that(cow, either(eq(horse), eq(cow)));

Ensure.that(horse, and(eq(horse), contains("ors")));
Ensure.that(cow, both(eq(cow), endsWith("ow")));

2 - Using negative matcher:

Ensure.that("horse", not(eq("cow")));

There are still a couple of matchers to talk about, one is the UsingEqualityMatchers class which is pretty much like JUnit Assert class, and the UsingExceptions class. Both also deserves your attention. Maybe someday I talk about them here. :)

Written by Alexandre Martins

July 4th, 2007 at 9:29 pm

Value Objects & RoR

without comments

Currently I’m working on my personal project, aiming to increase my Ruby On Rails skills. It’s quite a simple system for my dad’s company and one of the features is to register his clients. I started it out writing the Specs and as I’m new to the Ruby world, doubts started to pop inside my head. I was wondering how to use Value Objects ( Eric Evans definition, please! ) integrated with RoR, something I can do with Java as shown below:

public class Phone() {
    private int code;
    private int number;
    ....
}
public class Client() {
    private String name;
    private Phone home;
    private Phone mobile;
    ....
}

Chatting with Carlos Villela, he advised me to take a look at composed_of feature, that it would help me get the solution for my problem. The final result is shown below. I’m definitely not used to the Ruby syntax yet, for me it’s still a bit confusing.

class Phone
  attr_reader :code, :number
  def initialize(code, number)
      @code, @number = code, number
  end

  def ==(other)
      code==other.code && number==other.number
  end
end
class Client < ActiveRecord::Base
  composed_of :home, :class_name => "Phone",
        :mapping => [ %w(home_code code), %w(home_number number) ]
  composed_of :mobile, :class_name => "Phone",
        :mapping => [ %w(mob_code code), %w(mob_number number) ]
end

Written by Alexandre Martins

June 11th, 2007 at 7:14 pm

Posted in Coding, Design

Tagged with , ,

[WTF] Eureka!

without comments

If you think you know how to work out the age of a person, based on his date of birth, it’d be better to review your concepts about implementing this functionality. Enjoy the code!!

    public UserImpl( UserTO user, String status ) {
        _user = user;
        _status = status;

        _age = 0;
        Calendar today = Calendar.getInstance();
        Calendar birthdate = Calendar.getInstance();
        birthdate.setTimeInMillis( getBirthdate().getTime() );
        birthdate.roll( Calendar.YEAR, 1 );
        while ( today.after( birthdate ) ) {
            birthdate.roll( Calendar.YEAR, 1 );
            _age++;
        }
    }

Written by Alexandre Martins

January 25th, 2007 at 4:21 pm

Posted in Coding

Tagged with , , ,