A programmer's tale

Wednesday, May 31, 2006

Adapting Adapter and building Bridge

Adapter and Bridge patterns are tow structural patterns described in GoF.
Adapter pattern basically converts one type of interface to another type of interface. Say you have an existing interface with the behaviors defined by you and your client is expecting another interface. Now how do you convert your existing interface into the interface your client expecting? Adapter pattern provides you the solution.

Bridge pattern decouple your abstraction and your implementation so that you can vary both your abstraction and implementation over time. Here implementation means designing a specific object with specific behavior and attributes, abstraction means abstracting the behaviors of the same said object. Without bridge the Abstraction and implementation are in same design hierarchy and bridge pattern separates the hierarchy of the two.

Example:
Suppose you have an interface called Pencil within which there is a method writeWithPencil() as:
public interface Pencil {

void writeWithPencil();
}

But your client has their interface Pen with the method write() as:
public interface Pen {

void write()
}

Now you want to give your client same transperncy without modifiying your existing interface. Actually you want to conert your Pencil into client's Pen. Here Pen is our target interface and Pencil is our adaptee.





It's time to write our adapter:

public class PencilAdapter implements Pen {

private Pencil pencil;

public PencilAdapter(Pencil pencil) {
this.pencil = pencil;
}

public void write() {
pencil.writeWithPencil();
}
}

Now client code :
public class Main {

public static void main(String[] args) {
Pen p1 = new LinkPen();
Pen p2 = new PencilAdapter(new WrozPencil());

p1.write();
p2.write();
}
}

For bridge let us consider that we have Car interface as our abstraction and we are implementing different CarDriver. Without bridge we write

public class ConcreteCat implements CarDriver {
// code
}

It's not flexible as it the abstraction depends upon implementation via inheritance. But with bridge pattern we have our design like:




Client code:
public class Main() {
public static void main(String[] args) {
Car lCar = new LuxuryCar(new FordDrive());
lCar.start();
}
}

My drive to design destiny

When I first started to learn design pattern, I was very much fascinated by the book Design Patterns by GoF(Gang of Four). No I was not very much comfortable with reading and comprehending this book, I headed the book because it is the best ever book of design pattern aka the bible of design pattern. During my reading many times I got frustrated for not getting anything from this book for the first time. Then I started reading this book ad-hoc manner. It took several iterations to go through the whole text. Now I'm planning my further journey into this kingdom.
Now where to go?

GoF describes the classification of design pattern depending on two factors:
  1. Purpose: Creational, Structural, Behavioral.
  2. Scope: a) Class-static, compile time binding b) Object-dynamic, run time binding.
In this book there are 23 basic design patterns, GoF categorised these design patterns from these two views. There are also broader classification of design patterns according to their applicability to different domains such as:
  1. Basic design patterns-GoF patterns
  2. UI design patterns-patterns for designing user interface
  3. Network design patterns-patterns for networks
  4. Enterprise design patterns-patterns for enterprise application
  5. Game design patterns-patterns for game development.
Some design patterns are just variations of another design patterns and many evolved design patterns use basic design patterns of GoF.

If you as a learner just go through design pattern catalog book, then it is very difficult to put them into your brain. Some general books that describes more explanation, real application, UML to design patterns, use cases and general discussion can help you a lot. You should also have crystal clear concepts about UML for learning design patterns.

Here I'm jotting down names of some useful books and little about them:
1. Head First Design Pattern - Written in very friendly manner, detail explanation and discussion with it's unique style of writing.
2. Design Patterns by GoF - The bible of design patterns describes original basic design patterns.
3. Applying UML and Patterns by Craig Larman - Written in very practical way of applying UML and patterns. It also describes the details of software development from SRS, use cases to design and development along with Agile development. It has GRASP patterns.
4. Patterns in Java, Vol 1-3 by Mark Grand.
5. Designing Interfaces by Jenifer Tidwell - very good book for designing user interface in patttern oriented manner.
6. Patterns of enterprise application architecture by Martin Fowler - Great book for enterprise application design mainly in J2EE.
7. UML distilled by Martin Fowler - learning UML.
8. Other books by Martin Fowler.

What next?

  1. Framework design
  2. Software Architecture

Wednesday, May 24, 2006

class, interface and method-How do I address you?

In java or java like OOP language, all we need to create new classes, interfaces and methods
inside them. Now a days I am suffering from naming phobia of class, interface and methods.
How do I name a class, interface or a method so that it's intuitive and easy to understand and
use. I've gone through Joshua Bloch's Good API design guidelines which is available in JavaPolis2005 archive. It's damn useful to realize the importance of designing good API and how it can affect or effect company's clients. But the less-experienced programmers like me frequently face a very fundamental problems - how to give a meaningful name to them.

Once in our office meeting we, juniors are advised some good naming conventions. It was very
much helpful to me as a fresher. Now I am trying to remember some of them and also sharing my ideas about the same.

The rule of thump is that:

1. interface name - should be Adjective like words like Readable, Appendable etc
2. class name - should be Noun like words like Reader, Writer, Printer, ReportWriter etc.
3. method name - should be Verb like save(), print, edit(), createIcon() etc.

The basic idea behind these types of naming convention is ease of use of the APIs that are
easily understood without documentation or a little documentation. That's a way of increasing
the productivity also. If a developer has to read all the documentation to understand the intention of your API, he/she will be definitely less productive. Here lies the importance of good naming of APIs.

Let us consider a simple example, if I have a class named XML2TextConverter then I will expect a method like convert() inside the class. If I cannao find the method I expected then I have to browse through the documentation which is always if-avoidable like thing to a rapid developer.

The most critical naming problem I frequently face is name of a method. Leys say I'm building a
GUI component like JTable that has also a header, now inside my MyTable class I'm planning to provide a method to attach a header to my MyTable. Now what should be the name of this method setHeader(), setTableHeader(), addHeader(), or addTableHeader(). If I take setter methods then the user of my API natuarally expect a argument like setHeader(Header header). So if the class MyTable internally add the table header, it's more appropriate to use addXXX methods. If you want to give your API user the previleage to add header externally, then setXXX methods are more appropriate here.

In design pattern some very good naming convention is used in developer's community. if your
application or your indivisula falls in these category, then it is better to use the pattern
convention.

During my reding through the book Effective Java: Programming Langueage Guide(Joshua Bloch) I found a very good discussion over naming convention , especialy in item25, 38. This book is a
masterpiece and must-have book for all professional java developer. It's also winner of prestizious
Jozt award.

Wednesday, May 17, 2006

Finding field of array:

Which class contains the length field of an array in java? Let me elaborate the thing:

My code is:

public class ArrayLenghtTest {

static int[] a = {1, 2, 3, 4};

public static void main(String[] args) {

System.out.println("Length of the arrary:" + a.length);

            System.out.println(ia.getClass());
         
         System.out.println(ia.getClass().getSuperclass());

}

}

Here I’m accessing a field “lenght” of “a”. Now what is “a”? Here if “a” is not a class, how can I get a field from it? Then what is “a”? If “a” is a class then it must be implemented and instantiated somewhere. If you go through Lava Language Specification http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html), you will find that there are primarily two kind of types in java: 1. primitive type and 2. reference type. In our case “a” is definitely not a primitive type , hence it’s a reference type. Again reference type is divided into three sub-types: a) class type, b) interface type and c) array types. Now we have got that “a” is a array type.

If we go little further in JLS3.0 http://java.sun.com/docs/books/jls/third_edition/html/arrays.html we can find that

“In the Java programming language arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n-1, inclusive.

All the components of an array have the same type, called the component type of the array. If the component type of an array is T, then the type of the array itself is written T[].

And for the members of array object we find here:

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array (length may be positive or zero).
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

But you cannot find the public final field length field anywhere in java SDK code.

The output of the above program is:
4
class [I
class java.lang.Object

Class [I is created by the native implementation of java.lang.reflect.Array; which is totally taken care by the JVM, the field length exists in that class i.e. [I. We cannot inatatiated or subclass that.

Here is a beautiful usecase for java array:

http://www.artima.com/legacy/answers/Aug2000/messages/149.html

Tuesday, May 16, 2006

My First Meeting with Mac

Recently we have our Mac machine for testing of our project. Being 100% java, our project should run on any OS seamlessly. Thats give me the opportunity. First thing about the Machine is that it's design make me speel-bound. Just around 1.5 inch depth of the monitor and everything including CD-ROM, CPU etc. is behing your screen. White is my favorate color and the totall screen is sober white colored.
The display and graphics of Mac is just stunning, while I am on the machine it seems I'm watching HDTV. Ohh, yes, the machine is remote controlled but I have not use that. The best feature I have ever seen is incremental search in every window. When you type any thing in this search field the items resembling got highlighted and other items shaded.


Every project should have good coding convention

As a programmer the most annoying problem I've ever faced is the lacking of good coding convention of the projects. I thing every project should have some good coding convention. This convention should be followed by every member of that particular project. Trere are so many advantages of having this. I'll be that point soon, but the first thing first. What do we mean by good coding convention? A coding convention defines and describe some set of rules and coding template for a particular project. Say, how do you declare the global variables in your class. For example:
int globalVar;
int _globalVar;
int m_globalVar;

These are the various way of declaring variables, but your project should follow just one convention not mix of any two or more. This is just an example for variable declaration, but your project should have some template for wring class, interface etc.
Most of the time this kind of standard follow some industry standard proposed by different leading vendor like Sun, Microsoft.
This conding standard should be fixed before starting the coding phase of the project and by the project manager.
The main advantage of having such thing is that integration of different code becomes easier. Moreover the reading and using of code becomes convinient for different people working at that project.