Tuesday, February 14, 2006

Another case for Specifications

Yesterday I've started to hold my third week of courses, introducing people to Enterprise Application Design and Development using the wonderful Hibernate and Spring.

Using, as a reference, the well known Patterns Of Enterprise Application Architecture book, I've came across this sentences:
One of the hardest parts of working with domain logic seems to be that people often find it difficult to recognize what is domain logic and what is other forms of logic.
...
A good example of this is a system I was told about that contained a list of products in which all the products that sold over 10 percent more than they did the previous month were colored in red. To do this the developers placed logic in the presentation layer that compared this month's sales to last month's sales and if the difference was more than 10 percent, they set the color to red.

The trouble is that that's putting domain logic into the presentation.

Suddenly, I said : "Specifications, here, are at their best!"

Create a generic IncreasingSaleSpecification interface, implement it for your particular case and apply for determining the color of the product in your view!

Doing so:

  • Business logic remains in your domain (into your Specification).

  • Your view implements no business logic.

  • You can implement new increasing sale specifications and simply change on the fly the behaviour defining when your products should be displayed in red.


Amazing!

Monday, February 13, 2006

SourceSense : Logo Challenge

My (should I say "ex", Gianugo?) colleague Gianugo Rabellino is starting a new, very promising, open source based company : SourceSense.

If you feel comfortable with graphics, you can submit a fancy logo for SourceSense here and try to win a new MacBook Pro laptop (if you are reading, Mario, you should REALLY REALLY try)!

So, good luck for your logo! ... and a shiny future for your company, Gianugo!

Wednesday, February 01, 2006

Rome JUG : First Meeting

Since December 2005, Rome has its first, official, Java User Group.



On 25th January 2006 there was its first meeting, with two interesting talks regarding:

  • Neural networks and the Joone framework, by Paolo Morrone.

  • Alternative persistence frameworks, by Ugo Landini (yes, the OO guru!).


If you crunch Italian language, you can download presentations and audio podcasts of the two talks here.


This is great for all us Java developers, and I'm waiting for a lot of cool events here in Rome!
Hope to see you in the next meeting!

Monday, January 30, 2006

A case for Specifications

It has been a long time since I wanted to post about this, and now, finally, here I am.

In this post I want to talk a bit about Specification, a Domain-Driven Design pattern I think very interesting and useful in a lot of situations.

What is, so, a Specification?

Domain models are not only about entities, relations and collaborations. Domain models must also host a lot of implicit concepts and rules you must deal with, because they are important parts of your business domain : for example, booking policies, payment delinquent rules and so on.
The problem is to find a place for this concepts.
You can model and implement them inside your entities, your business objects, but doing so you couple your objects with concepts regarding them but not being part of them; more important :

  • You lose a lot of expressivity, because you sink your meaningful (but implicit) concepts into your object code.

  • You lose a lot of flexibility, because you cannot change or apply them regardless of your business objects.

The answer is the Specification Pattern.

Specifications, as said by Eric Evans, are a concept borrowed from logic programming: they are tiny classes with a method representing a boolean predicate.
The Specification models a particular concept that applies to a particular entity, providing a method which expresses the concept as a predicate; in particular, the method tests if a given instance of the entity satisfies the expressed predicate.

Let me show you a practical example.

Say you have an employee who issues some requests, for example permit requests.
The employee cannot directly request a permit for a number of days greater than those remaining; if he wants to request more days, he must ask the secretary, but even in this case he cannot exceed a certain limit.

How do you model this?

You'll have an Employee entity, a generic Request and a PermitRequest entity.
But what about all those concepts regarding the employee request?
Remember, a permit request which exceed the employee remaining days is not valid if made by the employee, and so on ...

If you don't use Specifications, you can implement a validation method inside your PermitRequest class :
public class PermitRequest
implements Request, ValidationAware {
private static final int limit = -10;
private Employee owner;
private int requestedDays;
// ...
public void validate() {
int remaining = owner.getRemainingDays();
if (remaining < this.requestedDays) {
// notice this ...
}
if ((remaining - this.requestedDays)
< PermitRequest.limit) {
// notice this ...
}
// ...
}
}
Doing so, however, you couple your rules and cannot separately apply them, breaking your requirements!
You can surely use two distinct validation methods:
public class PermitRequest
implements Request {
private static final int limit = -10;
private Employee owner;
private int requestedDays;
// ...
public void validateForEmployee() {
int remaining = owner.getRemainingDays();
if (remaining < this.requestedDays) {
// notice this ...
}
// ...
}
public void validateForSecretary() {
int remaining = owner.getRemainingDays();
if ((remaining - this.requestedDays)
< PermitRequest.limit) {
// notice this ...
}
// ...
}
}
But doing so you couple yourself with the particular Request entity, breaking a lot of design principles ... what if we want to validate a request without knowing its actual type? What method to call?

Implementing two distinct Specifications is simple and solves all your problems.
You'll have an ExceedDaysSpecification for the first rule (requested day cannot exceed remaining days), and an ExceedLimitSpecification for the second one (requested days cannot exceed a certain limit), each with the predicate method accepting a Request and testing the given rule over it.
public class ExceedDaysSpecification
implements RequestSpecification {
public boolean isValid(Request request) {
int remaining = request.getOwner().getRemainingDays();
int requested = request.getRequestedDays();
if (remaining < requested) {
return false;
}
else {
return true;
}
}
}

public class ExceedLimitSpecification
implements RequestSpecification {
private static final int limit = -10;
public boolean isValid(Request request) {
int remaining = request.getOwner().getRemainingDays();
int requested = request.getRequestedDays();
if ((remaining - requested)
< ExceedLimitSpecification.limit) {
return false;
}
else {
return true;
}
}
}
In this way :

  • Implicit concepts are powerfully expressed.

  • Specifications can be applied to every base type of entity (Request) : if you need to know the actual type inside the Specification predicate method, you can do a downcast or apply a simplified Visitor pattern.

  • Specifications can be easily combined : simply combine the evaluation of the predicate methods!

You have the obvious drawback of having to implement a given quantity (maybe a lot, for complex domains) of small classes, but I think the gained expressivity and flexibility well worth the effort.

What's your way of thinking about this?

Friday, January 20, 2006

Google, finally!

Google finally hit the target, again.

Now, if you search for "sergio bossa blog" you'll get my personal blog (yes, this site) as its first result.

I'm very well-satisfied ... don't you see?

Thursday, January 19, 2006

A funny quote ...

I can't help but laughing about this:

The March of Progress

1980: C

printf("%10.2f", x);

1988: C++

cout << setw(10) << setprecision(2) << showpoint << x;

1996: Java

java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String s = formatter.format(x);
for (int i = s.length(); i < 10; i++) System.out.print(' ');
System.out.print(s);

2004: Java

System.out.printf("%10.2f", x);

Found here.

Tuesday, January 17, 2006

Teaching Object Oriented-ness

OK, new year, old life, and very poor free time for posting or enjoying a lot of new technologies waiting for me and requesting my attention!!!!

I should find more time .... no, correct myself .... I MUST find more time!!!!
Repeat, please : more time, more time, more time ..... !!!!

However, I don't want to talk about this, but rather about what happened to me some days ago: in fact, last week I started my first, true, teaching experience.
I started teaching Object Oriented Design & Programming in Java to a class of eight: I am very passionate about object oriented design and I totally devoted myself in communicating them OO principles, achieving also good results.

The eight would-be OO Java developers had all a strong Visual Basic 6.0 background, and what mostly surprised me was how many bad habits this sort of programming language embed in whoever is exposed to it for a lapse of time greater than, say, one year.

Visual Basic literally destroyed a generation of programmers.

Moreover, I truly discovered how difficult is to move from procedural way of thinking, to object oriented one, and how difficult is to solve a problem in object oriented fashion.

However, this should not surprise myself, because I know a lot of developers who, while using Java or C++, don't really develop in OO and maybe don't fully understand it.

I think that object oriented design (and programming) is one of that things which everyone theorically praise but practically (almost) never do.
And this is very bad, and this is the reason why many projects literally go spaghetti.

This is why I'm starting to love Domain-Driven Design .... but this is another story.

Which maybe I will tell you some day.

Monday, January 02, 2006

A New Year

Another year passed fast.

Another year starts to pass.

For our memories.

Shantih shantih shantih.
(T.S. Eliot, The Waste Land, verse 433)

Friday, December 16, 2005

The beauty of the State (Pattern)

Ok, let's talk about design, please.

First, recall what said in my previous post:

Say the boost() method, depending on the GearType, must do the following:

  • Decreasing Car fuelQuantity and oilQuantity.

  • Calling changeGear() on TransmissionGear


How would you do this?


For a moment, I'll talk about the straightforward way: if you have a boost() method on the Car object, which must behave differently depending upon a property of some associated object, simply code a sequence of if statements upon this property.
So, if GearType is FIRST, change fuelQuantity and oilQuantity accordingly and change gear to SECOND; if it is SECOND, change them in a different way and change gear to THIRD; and so on.

You can code this in minutes, but if you do so you'll have a lot of problems.
Your code has a lot of if statements, is not so object oriented and is hard to read.
Moreover, the biggest problem is that if you must add another gear, you'll have to directly modify the boost() method for add another if!
You are changing some code that actually works ... what happens if your change breaks something?!

The best would be to completely isolate the various boost() algorithms, and the adding of another gear, that is, another algorithm for boost().

A good way to do so is applying the State design pattern.

You'll have to simply:

  1. Encapsulate the Car properties, changed by the boost() method, into a value object (LiquidQuantity, sorry for the stupid name) : this prevents from directly changing Car properties.
    Note that this is an optional step, because you could simply insert two getters/setters into the Car class, but in this case I'd suggest you to make this
    setters package-protected.

  2. Create a "state" class for every gear type, implementing a common interface (GearState): it represents the changing state.

  3. Implement, in every GearState, a boost() and a changeGear() method: the former must implement the algorithm which changes the LiquidQuantity, the latter must determine the next gear.

  4. Associate the TransmissionGear with all GearState objects through a Map, whose keys are the various GearType: doing so, the TransmissionGear can access the GearState using its GearType property, representing the current gear.

  5. Implement a boost() method in TransmissionGear, which delegates to its current GearState for the appropriate boost() and changeGear() behaviour.

  6. Implement the boost() method in Car, making a call to the boost() method on TransmissionGear.


This is a class diagram with some meaningful comments and Java code snippets:



Maybe I should show you an interaction diagram, too, but for now I'm too lazy, maybe in the next post if you care ;)

Using the state pattern, so, you can clearly separate the behaviour that changes in conjunction with the state of some object, and add another state, with another behaviour, without affecting old code: in our example, simply implement another GearState and add it to the TransmissionGear map.
Moreover, the state changing is also absolutely transparent.

This, obviously, at the cost of some more class and some more dependency between classes, but I think that benefits overcome.

As always, have a good design!

Friday, November 25, 2005

Object Challenge

Challenges are always something people love to face ..... if you want an example, think to Sudoku success!!!
So, I want to submit you a challenge based on some object oriented crunches.
Give me your attention for some minutes, if you care, or if you don't have something better to do.

Say you have a Car object in your business domain.
It has state and behaviour, so no, it is not an anemic business object.
Say you have, besides all other components, a TransmissionGear which is a part of your car.
It has its good state and behaviour, in particular it has a GearType attribute which defines the actual gear, and a changeGear() method for changing gear.
Car, on its side, has a boost() method which interacts with the TransmissionGear and whose behaviour depends on the GearType.
Take a look at this diagram:



Say the boost() method, depending on the GearType, must do the following:

  • Decreasing Car fuelQuantity and oilQuantity.

  • Calling changeGear() on TransmissionGear


How would you do this?

There's no best method, but surely there's a method better than another one.

If you care, leave a short comment, or simply think.
Think about this.

I'll give you my solution in one of my next posts!

Tuesday, November 22, 2005

Unit testing with the Spring Framework, Part 2

In one of my old posts, Unit testing DAO classes in the Spring Framework, I talked about how to test Hibernate based DAO classes implemented with the HibernateDAOSupport Spring template.

However, inspired by a Matt Raible blog post, I've recently started to use the AbstractTransactionalDataSourceSpringContextTests Spring class.

It's a long time since I want to post about this very interesting piece of thing.

This class provides an easy way to do unit, but I'd better say integration, tests over your Spring managed business objects and services, importing your Spring configuration, loading an appropriate Spring application context based on it, and wrapping your test methods each in a separated transaction which will be rolled back at the end of the method, avoiding so to insert test data into your database tables.

This sounds very good, because you don't have to manually configure Hibernate (it will be configured in your Spring application context), nor to manually manage transactions, nor to worry about unwanted test data!!!

So, you will simply have to:

In your test methods, you can use all normal JUnit assert methods.

Moreover, you will be able to do a lot of other cool things, like accessing a jdbcTemplate variable for making SQL queries, committing transactions instead of rolling them back, or making special setup operations before every test method in the same context of its transaction or in another one.

Take a look at its javadoc.

Good testing!

Tuesday, November 15, 2005

Strange side effects of White Phosphorus (WP)

From an interview to Lieutenant Colonel Steve Boylan, spokesperson for the U.S. military in Iraq, Jeff Englehart, former army Specialist in Iraq, and Maurizio Torrealta, News Editor for the Italian television RAI and co-producer of the film "Fallujah: The Hidden Massacre":


LT. COL. STEVE BOYLAN: We have used it in the past. It is a perfectly legal weapon to use.

AMY GOODMAN: Maurizio Torrealta, news editor for the Italian state broadcaster, RAI 24. Your response?

MAURIZIO TORREALTA: Well, the United States, as the UK and Italy, signed the convention about prohibition of chemical weapons. And the convention define precisely that what make forbidden an agent, a chemical agent, is not the chemical agent itself. Because as Lieutenant said, the white phosphorus can be used to light the scene of a battle. And in that case, it's acceptable. But what make a chemical agent forbidden is the use that is done with it. If you use white phosphorus to kill the people, to burn and to block them, people and animals, even animals say the convention that we all sign, Italy, United States and UK, this is a forbidden chemical agent.

And we are full of picture that show bodies of young people, of children, of women which have strange -- particular, they are dead with a big corruption of the skin and show even the bone. And the clothes are intact, untouched. And that shows there has been an aggressive agent like white phosphorus that has done that. And we have all the number of those bodies and the place where they have been buried. So any international organization that wanted to inquire about that has all the tools and information to do it. And even the witness -- the U.S. military that we interview confirmed that the use of white phosphorus was against the population. And we have even picture of the fact that has been told by the helicopter down to the city, not by the ground up in the air to light the scene. Also the images, they spoke by themselves.

AMY GOODMAN: Jeff Englehart, you are the Specialist -- former U.S. Specialist in the Army, a member now speaking out against the war. You are interviewed in this documentary explaining how white phosphorus was used in Fallujah. Can you tell us more?

JEFF ENGLEHART: Oh, yeah. I mean, I definitely heard it being called for. And I even talked to reconnaissance scouts after the siege, and they said they had actually called for it. The Pentagon spokesperson says that they use this for concealment, or some sources say they use it for illumination. But, I mean, I think that's ridiculous, because we would use -- just based on my training as a reconnaissance scout myself, we would use illumination separately, as it’s on exclusive ground. Since my training, we were taught that white phosphorus is used for troops out in the open or to destroy equipment and that it burns and that the only way to prevent the burning is to douse it with wet mud.

To me, it's definitely a chemical weapon in the fact that it burns, and it burns indiscriminately. In fact, the use of white phosphorus violates the Geneva protocol for the prohibition of use in war of asphyxiating, poisonous or other gases and bacterial methods of warfare. So, I mean, even if the Geneva Protocol says it's illegal, I don't see how we're able to use it and then say that it's used for our own cover or illumination, when it actually could hurt our own troops. So I just think that, from the very top, the big problem with this war is that from the very top to the lowest level soldier, everyone's being lied to. And then the news gets gentrified by the mass media to make it sound like, ‘Oh, well, white phosphorus is a good weapon that we can use to help spot targets,’ when it's actually designed to burn its victims.

How good is White Phosphorus (WP)

From an interview to Lieutenant Colonel Steve Boylan, spokesperson for the U.S. military in Iraq:


AMY GOODMAN: So are you confirming that you used white phosphorus in Fallujah, but saying that it's simply not illegal?

LT. COL. STEVE BOYLAN: White phosphorus has been used. I do not recall it was used as an offensive weapon. White phosphorus is used for marking targets for both air and ground forces. White phosphorus is used to destroy equipment and other types of things. It is used to destroy weapons caches. And it is used to produce a white smoke which can obscure the enemy's vision of what we are doing.

AMY GOODMAN: And you're using it in Iraq?

LT. COL. STEVE BOYLAN: We have used it in the past. It is a perfectly legal weapon to use.

How to survive White Phosphorus (WP) ...

... if you are ACCIDENTALLY hit by WP particles during a military action.

From GlobalSecurity.org (see here):

If burning particles of WP strike and stick to the clothing, take off the contaminated clothing quickly before the WP burns through to the skin. Remove quickly all clothing affected by phosphorus to prevent phosphorus burning through to skin. If this is impossible, plunge skin or clothing affected by phosphorus in cold water or moisten strongly to extinguish or prevent fire. Then immediately remove affected clothing and rinse affected skin areas with cold sodium bicarbonate solution or with cold water. Moisten skin and remove visible phosphorus (preferably under water) with squared object (knife-back etc.) or tweezers. Do not touch phosphorus with fingers! Throw removed phosphorus or clothing affected by phosphorus into water or allow to bum in suitable location. Cover phosphorus burns with moist dressing and keep moist to prevent renewed inflammation. It is neccessary to dress white phosphorus-injured patients with saline-soaked dressings to prevent reignition of the phosphorus by contact with the air.

Some nations recommend washing the skin with a 0.5-2.0% copper sulphate solution or a copper sulphate impregnated pad. Wounds may be rinsed with a 0.1%-0.2% copper sulphate solution, if available. Dark coloured deposits may be removed with forceps. Prevent prolonged contact of any copper sulphate preparations with the tissues by prompt, copious flushing with water or saline, as there is a definite danger of copper poisoning. It may be necessary to repeat the first aid measures to completely remove all phosphorus.

White Phosphorus (WP)

From GlobalSecurity.org (see here):

WP is a colorless to yellow translucent wax-like substance with a pungent, garlic-like smell. The form used by the military is highly energetic (active) and ignites once it is exposed to oxygen. White phosphorus is a pyrophoric material, that is, it is spontaneously flammable.


White phosphorus results in painful chemical burn injuries. The resultant burn typically appears as a necrotic area with a yellowish color and characteristic garliclike odor.


Incandescent particles of WP may produce extensive burns. Phosphorus burns on the skin are deep and painful; a firm eschar is produced and is surrounded by vesiculation. The burns usually are multiple, deep, and variable in size. The solid in the eye produces severe injury. The particles continue to burn unless deprived of atmospheric oxygen. Contact with these particles can cause local burns. These weapons are particularly nasty because white phosphorus continues to burn until it disappears. If service members are hit by pieces of white phosphorus, it could burn right down to the bone. Burns usually are limited to areas of exposed skin (upper extremities, face). Burns frequently are second and third degree because of the rapid ignition and highly lipophilic properties of white phosphorus.

Friday, November 11, 2005

Your Face Tomorrow

Sometimes I wonder if my life would be a lot better and easier if I didn't know anything.
Anything about people, I mean.
Anything about my friends, my family, even about me, even about unknown people.

This is a strange thing to tell and I don't know if anything of you can understand, but what I think is that people, but I'd rather better say humans, rarely know by itself what they really are and want.
They often build castles and paint pictures of what they would like to be, of what life should be, but this is not reality.
Reality is never clear.

And being unclear in respect of yourself, how can you be clear in respect of other people?

So, I'll never know how your face will look tomorrow, and probably will never know also mine.
I'll never know my friends, my enemies, what is good and what is bad, so the only thing we have to do is trust or don't trust, and left all to time and destiny, which I think, time and destiny, are the same.

This is what people do, this is what people is used to do and want to do, and this is what permit them to stay safe.
Shut your eyes, your mouth, your ears, and be safe.
Because knowing something about you, about people, about life, something that you'd never want to know, really hurts.

I can assure you, waking up some day, discovering that you are not what you think and what you'd like to be, and that people living with you is not what appear to you ... really, really, hurts.

Knowing that your life is somewhat predictable, at least that you could predict what will be good or bad, could kill you, because this would force you to confront life face by face, and would revoke the possibility to say: "I didn't know, I could never have predicted this."

Knowing is responsability.

So, "we love to throw away our shield, marching mild and waving our spear like an ornament".

--

Inspired by Your Face Tomorrow - Fever and Spear, a novel by Javier Marias.

Tuesday, November 08, 2005

The importance of being extremely built

Ok, as said in my last post, daily builds are good, but what is better?

Like pointed out by my colleague Ugo Cei, like recommended by XP practises, and like well explained here by Martin Fowler, it is better and better to install a Continuous Integration System, in order to go through the "checkout / build / test" process in a fully automated way and many times per day, avoiding the so called "integration hell".

In these days I wanna put my eyes over these open source products for continuous integration:

I'll let you know, so stay tuned.

Friday, November 04, 2005

The importance of being daily built.

Yesterday I was reading "The Joel Test: 12 Steps to Better Code" : I had already read that article, but yesterday I've given it more than a thought.

Among other things, my mind was caught by the third item : "Do you make daily builds?".

My answer was "no", and my question was: why is this so important?
Yes, I said, they are a good thing and let your team check every day if their new commits do not break old builds ... but I didn't give it much importance.

So, at the end of the day, I committed my daily work, closed orwell (for those who don't know, orwell is my linux box), and came back home.

What happened while coming back, was that ... my mind reminded me that I had forgiven to commit also some libraries needed to compile my daily work!!!
And yes, I actually broke the build ... understanding, by experience, how much daily builds are useful.

So, don't be lazy (yes, I know how much hard may be this ...).... and take one or two minutes, at the end of the day, for daily testing your builds!

Wednesday, October 26, 2005

JavaZone 2005 ... online!

Hello all,

It has been a long time since the last post, but I'm very busy here at work, so please forgive me!

This is one of these news which really enjoy me ...

Javalobby has published on-line videos and MP3 podcasts of the JavaZone 2005 conferences ... take a look here: http://www.javalobby.org/av/javazone/.

Watching and listening to conferences held by great minds is always awesome, and you can learn a lot of things ... so have fun!

Tuesday, October 04, 2005

Talking about Cocoon

A recent post on Cocoon dev mailing list, by the Cocoon founder Stefano Mazzocchi, said that "Cocoon is obsolete" ... take a look at the full post for details.

My colleague Ugo Cei, a Cocoon committer, comments on in one of his blogs entry:


For a long time, I’ve been convinced that Cocoon must do less, much less than what it currently does if it wants to thrive and survive. Now it tries to be everything to everyone: a web publishing framework, a web application framework, a portal framework and possibly a business integration platform. I don’t think you can do all of this and at the same time be simple, lightweight and easy.


I'm a new Cocoon developer, but I've been fully involved with it in these last months, and being always in contact with a lot of experienced Cocoon developers I can say that I totally agree with this sort of thoughts.

Adding a lot of features makes maybe the product more powerful, but do we really need certain features used only by, say, a 20 per cent of people?

Like said above by Ugo, it adds a lot of weight and complexity, even if new features are developed in separeted blocks, because developers need to know HOW to manage these blocks, and because, maybe, the whole architecture could be simplified if some rarely used blocks would be discarded, while the most used better "integrated" with Cocoon core components.

And I must say that, with the raising and developing of some new very interesting frameworks, like Ruby on Rails for the non-Java world, or WebWork, or Tapestry, for the Java world, weight and complexity are IMHO a very bad thing.

I think that developer forces should be driven for consolidating and improving Cocoon existing and most used features, rather than adding new ones

These are my 2 cents thoughts about Cocoon present and future.