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

--

Sunday, July 29, 2007

Comfortable Introduction to Design Patterns

Design Pattern

Over the last few days we have been having design pattern sessions for everyone at our firm. So I thought it would be an opportune time to let everyone know about my understanding of design patterns. Over the course of time I also intend to write about a couple of design patterns.

So what actually is a pattern and what actually is a design pattern. The dictionary definition of a ‘pattern’ is as follows:

Pattern (noun): model/example which
you should copy.

We apply patterns in many facets of our life. It is only but obvious then that we should apply patterns even in software development. We may apply patterns while designing a solution to a particular problem we have. These patterns are what we call Design Patterns in software development. More formally a design pattern can be defined as follows:

Design patterns are language-independent strategies for solving common object-oriented design problems. Hence they should be equally applicable no matter which object-oriented language you use. Design patterns are not idioms or algorithms or components.

Before beginning to read more on the various design patterns I think we should realize that these patterns as such are not really invented by anyone in particular. They have just evolved over time by different people (software engineers) who faced various problem and come up with solutions to them. In fact it is possible that we have been using many design patterns without knowing their names. For example I had been using singletons, strategy and facades even before we had started the sessions in my firm.

Though I was applying some design patterns without knowing them I actually found benefits from a formal study of them. For one having these discussions helped me better understand what these design patterns actually are and how best to apply them. It has also helped improve out vocabulary and communication between team members. In fact we even use the
names of many of the design patterns in our everyday vocabulary in the office, for e.g. delegating responsibilities and giving proxies. Most importantly, a design pattern facilitates change requests from your client, a given during the life cycle of any software.

At first reading through design patterns and actually applying those in our designs and solutions might seem like a lot of hassle. But in the long run they really pay off. In fact one of the goals of design patterns is to make our software design reusable. Using the right design pattern in our solution results in the final product being more flexible and the inner components being reusable. Notice that I used the word ‘right’ because there are so many design patterns and it is easy to misapply them.

Hence while reading on a design pattern one should be careful to note the following:
Name of the pattern:
One should definitely know the design pattern he is going to be using to avoid miscommunication with others

Scenario when to use the pattern:
As I said there are so many patterns and it is easy to misuse them. A clear understanding of the problem scenario and when to use them is critical to gaining the maximum benefit of using a particular pattern. Often there are many variations/multiple ways to implement a particular pattern. A good understanding of the problem scenario helps one take the correct decision
while facing these choices.

Consequence of using the pattern:
One should also realize the advantages and disadvantages of using a particular pattern. Often a clear understanding of these help eliminate choices when we are faced with choices amongst multiple design patterns for a particular problem.

Design patterns can be classified in two ways mainly:

1) What the Pattern does

Creational Patterns:
They deal with various mechanisms of object creation. Examples include Abstract Factory, Factory Method, Singleton, Prototype and Builder patterns.

Structural Patterns:
They deal with the structure i.e. composition of classes and objects. Common examples include Adapter, Composite, Bridge, Decorator, and Proxy patterns.

Behavioral Patterns:
They deal with means of communication between objects. Common examples include Strategy, Observer, and Visitor patterns.

2) What kind of relationships it focuses on

Class Patterns:
They deal with inheritance, i.e. the ‘is a’ relationship of classes. Examples include Factory Method pattern.

Object Patterns:
They deal with relationships between objects, i.e. the ‘has a’ relationship of objects. Examples include the Abstract Factory

Just another point before ending today is that one needs to read as many design patterns as possible. It is because design patterns are rarely used in isolation. More commonly they are always used in conjunction with other design patterns.

Check back again soon. I hope to write on the Abstract Factory and Factory Method patterns soon.

--