Monday, January 31, 2011

Composition Vs Inheritance 1

One of the fundamental activities of any software system design is establishing relationships between classes. Two fundamental ways to relate classes are inheritance and composition. Although the compiler and Java virtual machine (JVM) will do a lot of work for you when you use inheritance, you can also get at the functionality of inheritance when you use composition. This article will compare these two approaches to relating classes and will provide guidelines on their use.
First, some background on the meaning of inheritance and composition.
About inheritance
In this article, I'll be talking about single inheritance through class extension, as in:

class Fruit {

    //...
}

class Apple extends Fruit {

    //...
}
In this simple example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this example, Fruit is the superclass and Apple is the subclass.
I won't be talking about multiple inheritance of interfaces through interface extension. That topic I'll save for next month's Design Techniques article, which will be focused on designing with interfaces.
Here's a UML diagram showing the inheritance relationship between Apple and Fruit:



Inheritance relationship
Figure 1. The inheritance relationship
About composition
By composition, I simply mean using instance variables that are references to other objects. For example:

class Fruit {

    //...
}

class Apple {

    private Fruit fruit = new Fruit();
    //...
}
In the example above, class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object. In this example, Apple is what I will call the front-end class and Fruit is what I will call the back-end class. In a composition relationship, the front-end class holds a reference in one of its instance variables to a back-end class.
The UML diagram showing the composition relationship has a darkened diamond, as in:


Composition relationship
Figure 2. The composition relationship

Friday, January 28, 2011

Type erasure with generics

Type-safety checking of generic types is only performed at compile time. Type information is then removed and will not appear in the byte code. Consequently, a generic type like ArrayList<String> is translated to its ArrayList equivalent...

List<String> strings = new ArrayList<String>();
List<Integer> nums = new ArrayList<Integer>();
System.out.println(strings.getClass());
System.out.println(nums.getClass());

Both will print java.util.ArrayList. Type erasure means generic type information will not be available at runtime, and the following attempt to create an array of a generic type will not compile...
TreeSet<String>[] families = new TreeSet<String>[5];

The wildcard type is an exception to this :
List<?>[] info = new List<?>[5];

The ? stands for an unknown type that matches anything.

There is however, an upside to type erasure – there will be interoperability between generic type and raw types...

TreeSet<String> names = new TreeSet<String>();
TreeSet rawTree = names; //names is widened to raw type

Type-safety checking can be defeated, typically for backward compatibility. The following will compile, but with an “unchecked cast” warning...



This also works...

import java.lang.reflect.*;
...
TreeSet<String>[] people = (TreeSet<String>[])Array.newInstance(TreeSet.class,5);


But the way is now open for ClassCastException at runtime...
TreeSet rawTree = people[0];
oldTree.add(new Integer(1)); //compiles, but runtime error
Compile-time type-safety check warnings can be suppressed if needed...
@SuppressWarnings("unchecked")
 public static void main (String[] args) { 
      ...

}

Runtime operations such as instanceof are not permitted again, because of type erasure.

Similarly, a cast such as...
TreeSet<String> handles = (TreeSet<String>)name;
would produce an unchecked compiler warning because it is not something the run-time system can safely perform.

But why java uses Type erasures?
Type erasure is not a fault, rather it was clever step taken by java designers.
The reason why Java uses type erasure is to maintain backwards compatibility. Let's assume you wrote some code a few years back which used Java Lists, before generics was introduced in the language. Obviously your code had no mention of generics. Now, when engineers at Sun decided to introduce generics, they did not want to break code which people had already written.
One possible way was to ensure that client code which uses generics in the classes they invoke, never carries any information about generics in the compiled code. So the above class when compiled should not carry any information about generics. Because compiled client code never carries information about generics anyways, library implementers are free to add generics to their code without the worry of breaking anyone's old code.

Generic types are not covariant : Generics allow you to use only one type

All the Object-based collection types (known as raw types) in classic Java are now retrofitted as generic types and accept type parameters. Generic types allow you to express your intent as being restricted to a particular type when creating and using it...

TreeSet<String> names = new TreeSet<String>();
names.add("Fred");
names.add("Wilma");
names.add("Pebbles");

SortedSet<String> is called the parameterized type and String is the actual type argument. Type-safety checking will be performed at compile time...
names.add(new Integer(100)); //compilation error

The compiler will also reject the following...
TreeSet<Object> names = new TreeSet<String>();
TreeSet<Object> alias = (TreeSet<Object>)names;


This is because generic types are not covariant – a TreeSet of String references is not a TreeSet of Object references.
With generic types, retrieved elements do not require explicit conversion...

Thursday, January 13, 2011

Factory pattern example in java

If you want to read about factory pattern, please refer this link - Factory Pattern.

Consider the following Button class, which has a single draw() method. Since this class is a generic class, we have made it as abstract.
Button.java

package tips.pattern.factory;

public abstract class Button {

public abstract void draw();

}

Given below are the concrete implementations of the Button class, WindowsButton and LinuxButton, each providing a much simplified implementation for the draw() method.
WindowsButton.java

package tips.pattern.factory;

public class WindowsButton extends Button{

@Override
public void draw() {
System.out.println("Drawing Windows Button");
}

}
LinuxButton.java

package tips.pattern.factory;

public class LinuxButton extends Button{

@Override
public void draw() {
System.out.println("Drawing Linux Button");
}

}

Now let us come to the core implementation, the Factory class itself. The ButtonFactory class has one static method called createButton() which the clients can invoke to get the Button object. Note the return type of the method, it is neither WindowsButton nor LinuxButton, but the super type of the both, i.e, Button. Whether the return type of method is WindowsButton or LinuxButton is decided based on the input operating system.
ButtonFactory.java

package tips.pattern.factory;

public class ButtonFactory {

public static Button createButton(String os){
if (os.equals("Windows")){
return new WindowsButton();
}else if (os.equals("Linux")){
return new LinuxButton();
}
return null;
}
}

Given below is the client Application that makes use of the above ButtonFactory class. The client is un-aware of the fact there is multiple implementations of the Button class. It accesses the draw() operation through a single unified type Button.
FactoryClient.java

package tips.pattern.factory;

public class FactoryClient {

public static void main(String[] args) {
Button windowsButton = 
ButtonFactory.createButton("Windows");
windowsButton.draw();

Button linuxButton = 
ButtonFactory.createButton("Linux");
linuxButton.draw();
}
}

So it is clear, that factory class fetches the client the corresponding class depending on the information provided by the client.

Chitika