Sunday, August 26, 2007

Cool way to create new Class in Eclipse

Recently I was amazed in how I could create a new class inside eclipse. All I needed to do was copy the source code for a class and paste, using Ctrl + V, into a selected package in eclipse. It automatically created a new java class and added the code to the file. I tired this same technique with another ide but failed to see the support there. I think this is a really cool feature provided by eclipse.

--

Maven Plugin to generate code using Eclipse JDT

Recently we were facing troubles with the generated sources for our project. The problem was that the java sources generated for our web service client using cxf did not have a proper toString() or equals() method both of which we needed.

We were using maven for building our project and manage dependencies. The idea struck me why not have a maven plugin to modify the generated sources. So we decided on creating a maven plugin to do just that. I had previous experience with eclipse and knew it had something called JDT to form a syntax tree from java source text. In addition, maven build life cycle has a process-sources phase just after the generate-sources phase which was just perfect for us.

Now we have to plugin which generates the toString(), equals() and hashCode() methods and relieved us a lot of debugging effort.

Below is sample code generated using the plugin on a class:

@Override public boolean equals( final Object pOtherObject){
if (pOtherObject == null) {
return false;
}
if
(this.getClass().equals(pOtherObject.getClass())) {
return id ==
((Event)pOtherObject).id;
}
return super.equals(pOtherObject);
}

@Override public int hashCode(){
return this.getId();
}

@Override public String toString(){
StringBuilder eStringBuilder;
eStringBuilder=new StringBuilder();
eStringBuilder.append("Class");
eStringBuilder.append(" : ");
eStringBuilder.append(getClass());
eStringBuilder.append(" , ");
eStringBuilder.append("Id");
eStringBuilder.append(" : ");
eStringBuilder.append(id);
eStringBuilder.append(" , ");
eStringBuilder.append("Artists");
eStringBuilder.append(" : ");
if (artists != null) {
eStringBuilder.append(" [ ");
for ( Artist eArtist : artists) {
if
(eArtist != null) {
eStringBuilder.append(eArtist);
} else {
eStringBuilder.append("null");
}
eStringBuilder.append(" , ");
}
eStringBuilder.append(" ] ");
} else {
eStringBuilder.append("null");
}
eStringBuilder.append(" , ");
eStringBuilder.append("Name");
eStringBuilder.append(" : ");
eStringBuilder.append(name);
eStringBuilder.append(" , ");
return
eStringBuilder.toString();
}


--

Sunday, August 12, 2007

Abstract Factory Pattern

Consider now that the Client changes her requirements further. (These clients are really clever bunch of people. They keep changing their requirements again and again and expect us engineers to meet the deadlines. Fortunately we have design patterns to come to our rescue). The client now wants to have specific glasses and straws for the drinks from the different fountains.

We are already aware of two previous design pattern suggestions:

"Encapsulate what varies"

"Depend on Abstractions, not on Concretions"

Its time to familiarize ourselves with yet another one:

"Favor Object composition over inheritance"

We will be using this set of suggestions to solve our problem.

Firstly we realize that we will need three methods inside our Factory now. Previously there was only createDrink() but now we need createGlass() and createStraw(). Both our Factories will have these methods so it would be a nice idea to abstract our Factories. As a result we will no longer keep our methods static in
the FountainFactories.




Notice that the methods inside the Factory are actually Factory Methods.

Implementing the Fountain is now a simple issue. All we need is to compose the FountainFactory inside the Fountain and our problem will be solved. Since we have managed to abstract our Factory we are using what is known as the Asbtract Factory design pattern. Our fountain class is now completely oblivious of the Drinks, Glasses and Straws being created. Our factories have grouped together the products that need to be created which we can consider as a family, e.g. Pepsi Drinks, Pepsi Glass and Pepsi Straw. The Factory also ensures that there is consistency amongst objects. In our current implementation it will be almost impossible to generate a Cocacola with a Pepsi
Glass.


Formally we may define the Abstract Factory as follows:

The Abstract Factory pattern is one level of abstraction higher than the ‘factory pattern’. You can use this pattern when you want to return one of several related classes of objects, each of which can return several different objects on request. In other words, the Abstract Factory is a factory object that returns one of several factories.

There are other mechanisms of using the AbstractFactory inside the Fountain class. I'll leave that discussion for a later time.

With all the advantages including abstraction and localization of information provided by the Abstract Factory pattern it is easy to get carried away. One should be careful in choosing this pattern over the Simple Factory or Factory Method pattern. For one extending the abstract factory is not easy because the AbstractFactory abstraction fixes the set of products that can be created. So adding new products, for example Toppings on Drinks, requires adding methods in the abstract factory which involves changing the AbstractFactory class and all its subclasses. Secondly, if the client needs to know of the subclasses, for example the actual drinks created, explicit down casting is required of drinks created from the concrete factories. Thirdly it is very difficult to add a new type of family of products in the abstract factory as the child class then needs to implement all the methods defined in the abstract class. For example if we wish to add a third type of fountain for RC-Cola and the RC-Cola does not have its own Straw it will be impossible to fit this RCColaFountainFactory as a child of the AbstractFountainFactory.

There are ways of getting around the third problem in two main ways. One is by making the AbstractFactory provide default implementations for some of the products (i.e. Drinks, Straws, Glasses). A second not so frequently used technique (and I think a very poor one) would be handling for null return values from the factory methods.

Class Diagram of Abstract Factory Pattern

--

Factory Method Pattern

Consider now that the Client changes her requirements. She previously wanted us to make a software for a Pepsi Fountain machine that serves Pepsi, 7UP and Mirinda. She now also wants a Coke Fountain to serve Cocacola, Sprite and Fanta.

The requirement is only a small overhead, but if we want to keep the Simple Factory we created previously we need to do a whole bunch of copy-paste and minor modifications here and there.



This seems to be a fairly good solution, but the two fountain classes are doing almost the same thing, except
during the initialization of the drinks. We educate ourselves with another important suggestion of using design patterns:

"Depend on Abstractions, not on Concretions"



Notice how we have introduced a level of abstraction into our Fountains. We can use the AbstractFountain
reference for the two distinct fountains and initialize the reference with the
PepsiFountain or CocacolaFountain as required in our program. Also notice how the common algorithm of getting a drink remains in the AbstractFountain while we have created the abstract method createDrink() inside our abstract class whose responsibility is to create the Drink. This method behaves like a factory and is aptly called the 'Factory Method'. We have indeed used the Factory method pattern here. The AbstractFountain is using its subclasses to specify which objects it creates and hence has no knowledge of which particular drink is being created. This knowledge of which drink is being created is localized at the concrete Fountain implementations namely PepsiFountain and CocacolaFountain.

More formally we may define the Factory Method as follows:

The Factory Method provides a simple decision making class that returns one of several possible subclasses of an abstract base class depending on the data that are provided.

Class Diagram of Factory Method Pattern

--

Simple Factory

Today we will be understanding the Simple Factory.

So let's first have a simple program to make where we will use the Factory Method pattern.

The requirements of our program are fairly simple:

We have a client and she wants us to make a software for a Pepsi Fountain machine that serves Pepsi, 7UP and Mirinda.

This is really a simple program and we can provide the solution very quickly:


Notice the segment in bold. If we have to add another drink, say Diet Pepsi, to this Fountain we have created we would need to add another if-else block and another constant (if we wanted to maintain a minimum
standard of good practice :) ).

It is time to get familiar with one of the more important suggestions while using design patterns:

"Encapsulate what varies"

We notice that the bold block in the PepsiFountain class is the one likely to vary when the client changes her
requirements. So it is best to remove that block from the execution block in the method.There are quite a few alternatives for us. One of the more commonly chosen techniques is to remove that segment and move it to a utility class with a static method as follows:



What we've just created is known as a 'Simple Factory'. It really isn't a design pattern and is very often confused with the Factory Method Pattern. Simple Factories are very commonly used techniques and should be used when as the name suggests requirements are fairly simple :).

--