Archive for Java

Benefits of supporting tools

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.

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.

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.

Comments (2)

Seeking code quality

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.

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.

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.

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.

Comments (3)

PicoContainer is alive!

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!

Comments

Behaviour Matchers

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:

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

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

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

UsingStringMatchers

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

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:

2 - Using negative matcher:

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. :)

Comments (3)

Value Objects & RoR

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:

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.

Comments

[WTF] Eureka!

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

Comments