Monday, December 1, 2008

Interface vs Abstract Classes

In the JDC Tech Tips for October 9, 2001, there was an item about using an abstract class hierarchy to implement the Java equivalent of a C union. The code looked something like this:

abstract class Time {
public abstract int getMinutes();
}

class Days extends Time {
private int days;
public int getMinutes() {
return days * 24 * 60;
}
}

class HoursMinutes extends Time {
private int hours;
private int minutes;
public int getMinutes() {
return hours * 60 + minutes;
}
}


A reader asked why an interface could not be used instead of an abstract class, with the code written as follows:

interface Time {
int getMinutes();
}

class Days implements Time {
private final int days;
public Days(int days) {
this.days = days;
}
public int getMinutes() {
return days * 24 * 60;
}
}

class HoursMinutes implements Time {
private final int hours;
private final int minutes;
public HoursMinutes(int hours, int minutes) {
this.hours = hours;
this.minutes = minutes;
}
public int getMinutes() {
return hours * 60 + minutes;
}
}

public class AIDemo1 {
public static void main(String args[]) {
Time t1 = new Days(10);
Time t2 = new HoursMinutes(15, 59);
System.out.println(t1.getMinutes());
System.out.println(t2.getMinutes());
}
}


In fact, the interface approach does work. However, there are a series of tradeoffs between the use of abstract classes and interfaces. This tip examines some of those tradeoffs.

Both of these mechanisms define a contract, that is, required behavior that another class must implement. If you have the following definitions:

abstract class A {
abstract void f();
}

interface B {
void f();
}


then a concrete class that extends A must define f. A class that implements B must define f.

Beyond this common feature, the two mechanisms are quite different. Interfaces provide a form of multiple inheritance ("interface inheritance"), because you can implement multiple interfaces. A class, by comparison, can only extend ("implementation inheritance") one other class. An abstract class can have static methods, protected parts, and a partial implementation. Interfaces are limited to public methods and constants with no implementation allowed.

So what's the difference between using abstract classes and interfaces in the example above? One difference is that an abstract class is easier to evolve over time. Suppose that you want to add a method:

public int getSeconds();

to the Time contract. If you use an abstract class, you can say:

public int getSeconds() {
return getMinutes() * 60;
}

In other words, you provide a partial implementation of the abstract class. Doing it this way means that subclasses of the abstract class do not need to provide their own implementation of getSeconds unless they want to override the default version.

If Time is an interface, you can say:

interface Time {
int getMinutes();
int getSeconds();
}

But you're not allowed to implement getSeconds within the interface. This means that all classes that implement Time are now broken, unless they are fixed to define a getSeconds method. So if you want to use an interface in this situation, you need to be absolutely sure that you've got it right the first time. That way you don't have to add to the interface at a later time, thereby invalidating all the classes that use the interface.

Another issue with this example is that you might want to factor out common data into the abstract class. There is no equivalent to this functionality for interfaces. For example, if you say:

interface A {
int x = 7;
}

class B implements A {
void f() {
int i = x; // OK
x = 37; // error
}
}


all is well if you want to declare a constant in the interface, but it's not possible to declare a mutable data field this way.

Let's look at another example:

import java.io.*;

interface Distance {
double getDistance(Object o);
}

interface Composite extends Comparable,
Distance, Serializable {}

class MyPoint implements Comparable, Distance,
Serializable {
//class MyPoint implements Composite {

private final int x;
private final int y;

public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}

public int getX() {
return x;
}
public int getY() {
return y;
}

public int compareTo(Object o) {
MyPoint obj = (MyPoint)o;
if (x != obj.x) {
return x < obj.x ? -1 : 1;
}
return y < obj.y ? -1 : (y == obj.y ? 0 : 1);
}

public double getdistance(object o) {
mypoint obj = (mypoint)o;
int sum = (x - obj.x) * (x - obj.x) +
(y - obj.y) * (y - obj.y);
return math.sqrt(sum);
}
}

public class aidemo2 {
public static void main(string args[]) {
mypoint mp1 = new mypoint(1, 1);
mypoint mp2 = new mypoint(2, 2);

double d = mp1.getdistance(mp2);
system.out.println(d);

int cmp = mp1.compareto(mp2);
if (cmp < 0) {
system.out.println("mp1 < mp2");
}
else if (cmp == 0) {
system.out.println("mp1 == mp2");
}
else {
system.out.println("mp1 > mp2");
}
}
}


MyPoint is a class that represents geometric X,Y points, with the usual constructor and accessor methods defined. The class implements three interfaces. One interface is used to compare one point to another, one is used to compute the Euclidean distance between points, and the last declares that MyPoint objects are serializable.

An alternate approach would be to define a new interface Composite (called a "subinterface") that extends the three interfaces, and then implement Composite in MyPoint. This is an example of a "nonhierarchical type framework".

The output of the program is:

1.4142135623730951
mp1 < mp2

It's easy to retrofit an existing class to implement a new interface. Doing this is sometimes called a "mixin." In a mixin, a class declares that it provides some optional, side behavior in addition to its primary function. Comparable is an example of a mixin.

Note that it would be awkward to implement the AIDemo2 example using abstract classes. Implementing several unrelated interfaces in a class is hard to duplicate using abstract classes.

It's often desirable to combine interfaces and abstract classes. For example, part of the design of the Collections Framework looks roughly like this:

interface List {
int size();
boolean isEmpty();
}

abstract class AbstractList implements List {
public abstract int size();
public boolean isEmpty() {
return size() == 0;
}
}

class ArrayList extends AbstractList {
public int size() {
return 0; // placeholder
}
}


At the top of the hierarchy are interfaces, such as Collection and List, that describe a contract, that is, a specification of required behavior. At the next level are abstract classes, such as AbstractList, that provide a partial implementation. Note that size is not defined in AbstractList, but that isEmpty is defined in terms of size. If a list has zero size, it is empty by definition. A concrete class, such as ArrayList, then defines any abstract methods not already defined.

If you use this scheme, and program in terms of interface types (List instead of ArrayList), there are several benefits:

* Much of the implementation work is already done for you in the abstract classes.
* You can easily switch from one implementation to another (LinkedList instead of ArrayList).
* If ArrayList or LinkedList are not satisfactory, you can develop your own class that implements List.
* If you cannot extend a given class, because you're already extending another class, you can instead implement the interface for the desired class and then forward method calls to a private instance of the desired class.

Interfaces tend to be a better choice than abstract classes in many cases, though you need to get the interface right the first time. Changing the interface after the fact will break a lot of code. Abstract classes are useful when you're providing a partial implementation. In this case, you should also define an interface as illustrated above, and implement the interface in the abstract class.

Monday, June 30, 2008

iBATIS Training - Day 2

Abstract factory Design Pattern

This provides an interface for creating Objects ( or families of related or dependent Objects) without specifying the concrete class for implementation

Aspect Oriented Programming(AOP) is based on Decorative Design Pattern and Strategy Design Pattern

CLASSIC Example of Singelton Design Pattern is Use of ApplicationResource.properties in Struts Framework.

At DAO Layer, Spring provides many templates like
1. Jdbc Template - By EXTENDING this SpringJDBC Integration is done
2. Sql Template - By EXTENDING this SpringiBATIS Integration is done
3. Hibernate Temmplate - By EXTENDING this SpringHibernate Integration is done


Steps for integrating Struts with Spring
1. Define applicatiobnContext.xml
2. In Web.xml sprcify the context path
3. Specify the servlet,context parameter and the listener

* Listeners in the Web.xml are loaded at the Startup of Server

Friday, June 27, 2008

iBATIS

Framework - Some of the common things found in all j2ee frameworks like iBATIS, spring, struts and others are
a. Builtin Classes
b. Configuration Files

iBATIS is Persistance layer framework which has Data Mapping


iBATIS supports inline SQL statements, dynamic SQL statements, ORM (Object Relational Framework). Even HIBERNATE is an ORM framework.

In HIBERBATE, Java Class and Database Table Mapping is done.

iBATIS supports SQL. We can write pseudo SQL statements in sql-map-config.xml

** iBATIS supports Aggregation with the help of ResultMap

For E.g

Class UserDetails{

String address;
String contact
}


Class User
{
String userId;
String passwd;
UserDetails userDetails;

}

Insertions,Updations of User Object is handled in a normal way.

For Retrieving User
UserDetails.xml would contain normal

For User.xml





LazyLoading Feature in iBATIS

Suppose if there are 1000 Master records and 1000 Detail records for each Master AND say we need to display a Detail Record on selection of given Master Record...

By implementing Lazy Loading DetailsRecord is fetched only once Master Record id selected.

RowHandler concept is similar to this.. What is the exact difference ?


Using #value# in<> for inline sql is sql injection PROOF.. where as $value is not



mainly 2 Types of Transactions

1. Flat Transaction - If there are 5 events in a transaction and one of them fails, all others are ROLLED BACK

2. Nested Transaction - If one of the 5 events fails, it is not ROLLED BACK. Here events are ordered in TREE fashion


Different Transaction Managers in iBATIS

1 JDBC - Transactions will be managed by JDBC

2 JTA - App Server Transaction Management details are used

3 EXTERNAL - Your Own Transaction Manager

Sunday, April 13, 2008

Sayings in Sanskrit

Where there is Duality, there is Confusion