Guice Modules for Play apps

As a former Java / Spring developer I liked the concept of configuration classes (i.e. Java classes annotated with the Spring @Configuration annotation).

I recently started to work with Play 2.3.x and Guice and one smell that I immediately found was the duplication in creating RedisClient objects.

Basically each Dao was reading the configuration and creating its own copy of the bean. While most of the RedisClient(s) were configured slightly differently, some Daos contained literally copy-and-paste code.

After some research I came across the Guice AbstractModule class and the @Provides annotation. For those of you familiar with Java + Spring a Guice Module is similar to a Java class annotated with the Spring @Configuration.

Below there is an example of the MyRedisService that relies on two RedisClients. The two RedisClients are configured in the Config Guice Moducle and individuated by their names.

The Config Module:

The Service:

In order to link everything together and inform Guice of the new Config Module, it’s necessary to add:

play.modules.enabled += "config.Config"

in the configuration.

Full example and app available in:


Given When Then – How To

Expressing tests in a Given When Then style is the core practice of the Behavior Driven Development (BDD) methodology. Details about BDD can be found here.

Writing tests in a GWT style can become tricky when there is no clear understanding / definition of what the actual test and preconditions are.

As explained in Martin Fowler’s post, the Given When Then (GWT from now on) journey begins with the Four Phase Test.

The Four Phase Test steps:

  • Setup
  • Excercise
  • Verify
  • Tear-down

The setup step puts the system in a specific, well known state.

The exercise step stimulates the system and brings it into a new state. The stimulation is the actual feature under test.

The verification step is nothing else than the comparison between the expected and actual state of the system.

Finally the tear-down step allows the test process to clean after itself.

From a functional (business) point of view the tear-down step does not have any value and this might be the reason why it has been dropped in the GWT style.

GWT is nothing else than the Four Phase without the tear-down step.

The previous definition of the GWT style testing seems to rely on the concept of state of the system. Not all the features in a system rely on the state of the system itself. A natural question then is: is the Given step always necessary when writing GWT tests? The short answer is, of course, NO.

Before proceeding, let’s step back and try to classify tests with a pinch of scientific approach!


Time dependant or stateful tests

All the tests where the history of the system is somehow relevant to determine how the system will react to a user stimulation, fall under this category.

A simple example is, for instance, accessing user details in a web-app protected by authentication.

An authentication failure or the nonexistence of the user will prevent the test from being executed. A successful user authentication is a necessary precondition required for the correct execution of the test.

A GWT test would look like:

  • Given the user is successfully authenticated on the system
  • When the user clicks on the details button
  • Then the name is displayed
  • And the last name is displayed
  • And the date of birth is displayed

Another example is the attempt of redeeming an expired deal:

  • Given I bought a deal
  • And the deal is expired
  • When I try to redeem the voucher
  • Then an error is displayed

A graphic representation of this kind of tests could be:



A – represents the initial status

f – is the user action (the feature under test)

B – represents the final status

If the actual status B matches the expected status then the test completed successfully.

From a math point of view if we think of the user action as a mathematical function, a stateful test satisfies the condition:

B = f(A)

If the resulting status is C instead of the expected B then we found a bug!


Time independent or stateless tests

No matter when it’s tested, but 2+2 it’s always going to be 4. Assuming we have for example a service that performs a mathematical calculation, no matter when the feature is tested, but its results will always (hopefully!) be the same.

Under these circumstances the Given step loses its importance and can be omitted

The only interaction with the system (the actual test) would be enough to perform assertions.

Assuming we’re testing a summation service a typical WT would look like:

  • When I sum 5 and 7
  • Then the result is 12

Mathematical oriented features are not the only ones belonging to this category. A few more examples are:

  • Currency or time conversion
  • Picture Resize
  • Echo service

Now that some context has been given, let’s proceed with a more accurate definition of the GWT style


A given statement is required when the feature under test requires either

  • the system to be in a specific state (eg. user authentication)
  • an action to happen before the feature under test can be invoked (eg. ticket bought, the browser has loaded a page)
  • time related constraints are met (eg. expiration date)

Sometimes the given step is mistakenly used as initialization or setup step. Some examples could be:

  • Prepare data that will be consumed during the When step
  • initialize resources (db connection, remote services)
  • pre-load data on database
Renaming/rewriting of a Given into a business action

From a business perspective a “Given the database is prepopulated…” is not of any use. At the same time though, these data are fundamental to the correct execution of the test. A good way of resolving this issue is to replace the “Given the database is pre-populated …”   with the business action that led to the creation of these data, such as “Given a user is registered on the system”.

Context initialization

Initializing resources like db / rest connections should not be listed in the GWT steps. Most of the current BDD frameworks provide developers with test setup phase where required resources can be initialized.


A when statement represents the feature under test. While in a GWT test there can be multiple given or then, there should be one and only one when.


Then(s) are the verification or assertion steps. It is a good habit to have then(s) steps to assert one single condition per then, and there should not be more than two or three then(s) in a GWT test.

Having too many then(s) is a symptom of testing too much or testing two features at the same time.


Git for impatients

Clone a project:
git clone

Commit a change
git commit -am "comment"

Push (to remote) a change
git push

Retrieve changes for the current branch (it’s actually more but you’re impatient!)
git pull --rebase

Create a branch
git branch branch_name

Switch to a branch
git checkout branch_name

Switch and Branch in one go
git checkout -b new_branch_name

Push local branch to remote (after you can use the normal push above)
git push -u origin branch_name

Merge branch into master

git checkout master
git merge branch_name

Remove local reference to deleted branches

git remote prune origin

Remove file from git source control without deleting
git rm --cached file_name

Won’t add more coz it’s just for impatient, if you need more..

git --help

Equals and hashcode how to for Hibernate and JPA in general

This morning I was manually writing a Hibernate bean and, when I got to question myself whether or not implementing equals and hashcode, I stumbled upon quite a few dilemmas:

  • shall I create them at all? (well yeah coz you want to use them in collections and the comparison between two objects should rely upon their pk and determine if they’re the same. But does the provider even care about it? )
  • will the pk be enough to implement equals and hashcode?

I then checked other entities in the project and found out all of them were using all the attributes for determining equality and hash. WT*??

As usual google is your friend and TADAAAA!!! One of the best written articles I’ve read recently.

Equals and Hashcode, all you need to know for your java JPA provider!

Kudos to the writer

The Kanban recipe to success

Recently I’ve read the illuminating book “Kanban” of David J. Anderson.
One of the chapter that impressed me the most is “A Recipe for Success”.
I’ve been working for the past few years in Agile teams and individuating ways of improving our work and simplifying the development process, was not an easy and immediate exercise. Retrospectives would help, but it would require quite few meetings, and therefore months, before being able to appreciate improvements.

In “A Recipe for Success” David introduce six ingredients that will definitely improve team performance. These ingredients are listed from the easiest to be applied to the most complex one.

They are:

  • Focus on Quality
  • Reduce Work-in-progress
  • Deliver Often
  • Balance Demand against Throughput
  • Prioritize
  • Attack Sources of Variability to Improve Predictability

Focus on Quality is the simplest one because does not require any agreement or cooperation with individuals external to the team, but is more a technical exercise. Putting in place a Continuous Integration system, introducing peer review and involve QA Engineers in the software life-cycle, will increase the overall quality with a relatively small effort. This should be your team’s first investment.

Nobody likes context switch and reducing Work-in-progress will allow individuals to keep the focus on a single task as well as stabilize the lead time. Introducing or reducing the wip will allow team member to deliver more doing less.
Introducing wip has to be agreed with upstream (PM) and downstream stakeholders (PM / Ops), so some level of coordination is required.

Agile is all about communication and feedback, deliver often can be read into the more effective “fail fast”. Fail is not a problem, it can happen, but the quicker it happens, the better.
Here again some coordination is required and it might also have an impact on costs (release coordination cost). The easier is to release software to production environment the better.

Demand and Throughput. They are related to the WIP and bottlenecks and it takes a while to get those bad boys right, but once that all the bottlenecks have been individuated and solved, the team should be able to work at a steady pace. This is a pretty complex subject and I will hopefully write something in the future.

Prioritize. Ask your Product Owner, “if you could deploy in production a feature / bug / improvement just with a snap of the fingers, what would it be?” Then that’s the item you should be work on.

Attack Source of Variability to Improve Predictability. Predictability is the key for building trust with Product Owners and Manager.
Superficial stories breakdown, cards blocked because of dependencies to resources external to the team, are all elements that affect predictability. Decent Throughput can still be maintained incrementing the wip (at the cost of stressing more the team!) but it would also increase the lead time. Tackling sources of variability is not a trivial exercise and requires a non banal team maturity. Attempting to resolve them should only be considered last, when all the other steps have already been taken.

Best way of mining bitcoins today

I recently started to analyse the phenomenon of bitcoins. Bitcoin is a digital p2p virtual coin. Explaining what bitcoins are is out of the scope of this article, but if you ever considered starting mining there are a few things you want to know.

Couple of weeks ago a former colleagues of mine introduced me to the bitcoin world, with its pros and cons. Also he told me that there was a way of mining (creating) bitcoins.

Mining bitcoins, at the end of the day, is literally solving a math problem again and again. For every bitcoin (block) found, the problem to solve becomes more and more complicated.

If you’re curios to understand more about mining there are two nice articales straight from bitcoin mining wiki page:

The hardware used in mining evolved along with the growth of the mining problem. The list is:

  1. CPU
  2. GPU (graphic card / hpc)
  3. ASIC and FPGA (dedicated hardware)
  4. Cloud

The full hardware comparison list is at wiki link.

If you heard bitcoin for the first time today (or just a few days ago) thinking to mine them at home, or for hobbies will be hard and most likely a waste of power (specially if you’re not familiar with linux, programming languages, ASIC and FPGA).

Today everything runs in cloud, and surprise surprise, there are already kick-ass cloud solutions for mining bitcoins.

The top two I found are:


Even if I have an account on, I still prefer because it’s a way more mature and complete platform, they are part of (the biggest mining pool). They mine NMC, IXC and DVC. Last but not the least, if configured, they will send you updates on every block resolved.

So, if you ever decide to start mining, do it with and use the link so that I can take advantage of the referral bonus.

If you think this article was usefull to you, please donate a few mBTC to 1D4Li5ckG81JLbBt3Kb2UT1wQqHZddVqEL 🙂

Open Distributed Messaging Platform – Powered by Groupon

Some time ago I’ve been hearing quite often that HornetQ was not a good product or at least a bad choice for the platform we were working on. I really could not understand these.

The company eventually decided to move away from it and adopt a different technology for their new developments.

I recently joined Groupon as a Java Developer and, surprise surprise, I’ve met again the little bee!

Without surprise I found out that Groupon makes use of HornetQ for Message Bus, a distributed Messaging System that has been made recently public on Message Bus.

Cannot really say much about the product, but you can easily imagine the volume of traffic that has been handled for the past five years, daily, by HornetQ.

If I think to these comments again, a smile appears on my face 🙂

Gist a github feature for sharing language specific formatted code

Finally after months and months I’ve found a neat, clear, formatted and even version controlled way of sharing code snippets.

Gist allows you to have language specific formatted code and embed it in any HMTL page or in a free blog like this one.

Here below is an example!

Hope this post helps people out there encouraging them to move all the embedded code that for years we’ve been raw pasting in our blogs, tidy them up and re-add in a cleaner, clearer way!

REST Payload API Versioning

In the last few days my focus has been on NoSQL DB(s) and REST services.

Points I’m more interested into are:

  • Payload API versioning
  • Platform independent Payload serialization and / or compression

I found on stackoverflow a very interesting debate on the versioning aspect.

Although exposing the API version in the URI gives great readability and control, I’m still a supporter of the media type field in the header.

I’ve initialized a github project so to realize a few PoC about the subjects I’m studying.

Examples make use of Jersey and Grizzly2 as container for tests. Everything is glued up with Spring 3.0 and built with Maven.

The code includes examples around:

  • Plain Json
  • Compressed (gzip) Json
  • Protocol buffer

You can dowload the code from github with the following command:

git clone

Any feedback is welcome.

Grep4j @ Google Dublin Group

Last 26th of February, I and my colleague Marco have been talking about Grep4J ( at Google Dublin Group (GDG).

Here is a link to the event:

The Bright Side of Java & Linux

Yet another Java blog


Bringing empathy into knowledge workers life

%d bloggers like this: