Wednesday, 24 September 2008

Truncate table irrespective of constraints

Today while doing my work I faced this problem and Iam very happy that I came to know new thing.

I was trying to truncate the table irrespective of the constraints.

Many times developers find it difficult to delete records from parent tables when child records reference those tables through foreign key (referential integrity) constraints.

Constraints validate the data; without constraints, we are just storing invalid data.

For a developer to identify and disable foreign key constraints is a difficult task. Most of the time, the application’s ER diagrams are not available to the developers.

A brief description on the foreign key (referential integrity) constraints will go a long way in identifying and disabling these constraints.

Let us have 4 tables ...

APPLICATION (Parent)

MESSAGE (Child)

DOCUMENT (Child)

-- Creating primary key index on the parent table APPLICATION(ID).

SQL> ALTER TABLE APPLICATION ADD CONSTRAINT "APP_PK" PRIMARY KEY ("ID")

-- Creating Unique constraint on APPLICATION.APPLICATION_NUMBER

SQL> ALTER TABLE APPLICATION ADD CONSTRAINT "APP_UK" UNIQUE ("APPLICATION_NUMBER")

-- Creating reference on itself .

SQL> ALTER TABLE APPLICATION ADD CONSTRAINT "APP_APP_FK" FOREIGN KEY ("APP_ID")
REFERENCES "CAJR_DEV3"."APPLICATION" ("ID")


-- Creating foreign key(referential integrity) constraint on the DOCUMENT table.


SQL> ALTER TABLE DOCUMENT ADD CONSTRAINT "DOC_APP_FK" FOREIGN KEY ("APP_ID")
REFERENCES "CAJR_DEV3"."APPLICATION" ("ID")


-- Creating foreign key(referential integrity) constraint on the MESSAGE table.


SQL> ALTER TABLE MESSAGE ADD CONSTRAINT "MSG_APP_FK" FOREIGN KEY ("APP_ID")
REFERENCES "CAJR_DEV3"."APPLICATION" ("ID")


Now let us remove the records from the parent table APPLICATION.


SQL> truncate table APPLICATION;
truncate table APPLICATION
*
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys


The parent table can not be truncated when foreign key(referential integrity) constraints are referencing it.

So How can we truncate the table irrespective of constraints?

Here is the way...

The data dictionary view for all_constrains...


SQL> desc all_constraints
























NameNull?Type
-------------
OWNER NOT NULL VARCHAR2(30)
CONSTRAINT_NAMENOT NULL VARCHAR2(30)
CONSTRAINT_TYPEVARCHAR2(1)
TABLE_NAMENOT NULL VARCHAR2(30)
SEARCH_CONDITIONLONG
R_OWNERVARCHAR2(30)
R_CONSTRAINT_NAMEVARCHAR2(30)
DELETE_RULEVARCHAR2(9)
STATUSVARCHAR2(8)
DEFERRABLE VARCHAR2(14)
DEFERRED VARCHAR2(9)
VALIDATED VARCHAR2(13)
GENERATED VARCHAR2(14)
BADVARCHAR2(3)
RELYVARCHAR2(4)
LAST_CHANGEDATE
INDEX_OWNERVARCHAR2(30)
INDEX_NAMEVARCHAR2(30)
INVALID VARCHAR2(7)
VIEW_RELATEDVARCHAR2(14)



Remember, when we tried to truncate the table APPLICATION, we received an error that said:

“ORA-02266: unique/primary keys in table referenced by enabled foreign keys”

Let us find out which constraints are enabled on our parent table APPLICATION.


SQL> select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
from all_constraints where constraint_type in ('P','U') and table_name='APPLICATION';








OWNERCONSTRAINT_NAMECTABLE_NAMER_OWNERR_CONSTRAINT_NAME
--------------------------------------------------------
DEVAPP_PKPAPPLICATION
DEVAPP_UKUAPPLICATION



Now we know the primary/unique key constraints enabled on our parent table, APPLICATION.

The r_constraint_name( primary/unique constraint name in the parent table) column in the all_constraints view is referenced by the constraint_name (foreign key(referential integrity) constraint in the child table), when the constraint_type is ‘R’.
Using this definition, let us find out all the foreign key(referential integrity) constraints referencing the APPLICATION table


SQL> select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
from all_constraints
where constraint_type='R'
and r_constraint_name in (select constraint_name from all_constraints
where constraint_type in ('P','U') and table_name='APPLICATION');












OWNERCONSTRAINT_NAMECTABLE_NAMER_OWNERR_CONSTRAINT_NAME
--------------------------------------------------------
DEVMSG_APP_FKRMESSAGEDEVAPP_PK
DEVDOC_APP_FKRDOCUMENTDEVAPP_PK
DEVAPP_APP_FKRAPPLICATIONDEVAPP_PK



Here in this sub-query, I am supplying ONLY the primary and unique key constraint types with the qualifier “where constraint_type in (‘P’,’U’) “, as we had seen earlier, that foreign key constraints can only be enabled on a child table, when a PRIMARY/UNIQUE KEY constraint is enabled on the parent table.

We had identified the foreign key constraints that are referencing the parent table
APPLICATION.

As long as the foreign key constraints are enabled on the child tables, the data in the parent table is protected.

if we need to manipulate the data in the parent table, APPLICATION, first disable the foreign key(referential integrity) constraints on the child tables that are referencing the parent table.

Now let us disable the foreign key(referential integrity) constraints on the child tables, identified from our earlier query.


SQL> alter table MESSAGE disable constraint MSG_APP_FK;
Table altered.

SQL> alter table DOCUMENT disable constraint DOC_APP_FK;
Table altered.

SQL> alter table APPLICATION disable constraint APP_APP_FK;
Table altered.

SQL> truncate table APPLICATION;
Table truncated.


We could successfully truncate the parent table, after disabling the foreign key
constraints on the child tables, that were referencing the parent table.

A ready built script (dynamic) to identify and disable/enable foreign key constraints on child tables


SQL> select 'alter table 'a.owner'.'a.table_name
' disable constraint 'a.constraint_name';'
from all_constraints a, all_constraints b
where a.constraint_type = 'R'
and a.r_constraint_name = b.constraint_name
and a.r_owner = b.owner
and b.table_name = 'APPLICATION';

'ALTERTABLE'A.OWNER'.'A.TABLE_NAME'DISABLECONSTRAINT'A.CONSTRAINT_NAME
--------------------------------------------------------------------------------
alter table MESSAGE disable constraint MSG_APP_FK;
alter table DOCUMENT disable constraint DOC_APP_FK;
alter table APPLICATION disable constraint APP_APP_FK;


Note:
Once you are done with the truncation of the parent table APPLICATION do not forget to enable back the constraints (In the similar way as we have disabled). So that the incoming data will be validated.


SQL> alter table MESSAGE enable constraint MSG_APP_FK;
Table altered.

SQL> alter table DOCUMENT enable constraint DOC_APP_FK;
Table altered.

SQL> alter table APPLICATION enable constraint APP_APP_FK;
Table altered.



Hope this explanation helps...

Tuesday, 23 September 2008

Proxy Pattern

Proxy Pattern provides a surrogate or placeholder for another object to control the access. There are number of ways it can manage the access.

It means we are representing a complex object with a simpler one.

Structure







-> A RemoteProxy manages interaction between a client and a remote object.

-> A Virtual Proxy controls access to an object that is expensive to instantiate.

-> A Protection Proxy controls access to the methods of an object based on the caller.

-> A smart proxy interposes additional actions when an object is accessed. Typical uses include:

1. Counting the number of references to the real object so that it can be freed automatically when there are no more references

2. Loading a persistent object into memory when it's first referenced

3. Checking that the real object is locked before it is accessed to ensure that no other object can change it.

Even many other variants of Proxy Pattern exists.


When to use:

1. Use the proxy Pattern in situations where client does not or can not reference an
object directly, but wants to still interact with the object

2. Use the proxy Pattern to create a representative object that controls access to another object, which may be remote, expensive to create or in need of securing.

-> The proxy object has the same interface as the target object

-> The proxy holds a reference to the target object and can forward requests to
the target as required (delegation!)

-> In effect, the proxy object has the authority the act on behalf of the client to
interact with the target object

To make clients use Proxy rather than the Real One, provide a factory that instantiates and returns the subject. Because this happens in a factory method we can then wrap the real one with a proxy before returning it. The client never knows or cares that it's using a proxy instead of the real thing.

Let us take a real time use of Proxy Pattern as an example.

By the way this code bit is from my Personal Project...

This is an example of static Proxy.


public interface EmployeeLoginI {
public EmployeeTO findByLoginDetails(String userName,String password);
public void registerEmployee(EmployeeTO employeeTO);
public EmployeeTO checkForUserNameAvailability(String userName);
}

/* This is the real subject where the business logic exists.
* All the required classes are not provided. if you
* think those will be useful,
* I can provide them also
*/




public class EmployeeLoginImpl implements EmployeeLoginI{

public EmployeeTO findByLoginDetails(String userName,String password){
EmployeeHome home = new EmployeeHome();
Employee src = home.findByLoginDetails(userName,password);
EmployeeTO dest = null;
if(src != null){
dest = new EmployeeTO();
EmployeeAssembler.assembleEmployee(src,dest);
EmployeeAssembler.assembleOtherEmployeeDetails(src,dest);
}
return dest;
}

public EmployeeTO checkForUserNameAvailability(String userName){
EmployeeHome home = new EmployeeHome();
Employee src = home.findByUserName(userName);
EmployeeTO dest = null;
if(src != null){
dest = new EmployeeTO();
EmployeeAssembler.assembleEmployee(src,dest);
EmployeeAssembler.assembleOtherEmployeeDetails(src,dest);
}
return dest;
}

public void registerEmployee(EmployeeTO employeeTO){
Session session=HibernateUtil.getInstance().currentSession();
session.beginTransaction();
insertEmployeeDetails(employeeTO);
}
}



// Factory that instantiates and returns the subject.
public class EmployeeLoginFactory {
private static EmployeeLoginFactory instance;
private String implClass = null;
private String mode = null;

static {
instance = new EmployeeLoginFactory();
}

private EmployeeLoginFactory() {
ResourceHandler resourceHandler = ResourceHandler.getInstance();
// get the mode we're running in, remote, local or pojo
mode = resourceHandler.getValue(getClass(),"mode", "pojo");
// get the impl class - defaults to ErrorServiceImpl if not overridden
implClass = resourceHandler.getValue(getClass(), "impl", "EmployeeLoginImpl");
}

public static EmployeeLoginFactory getInstance() {
return instance;
}

public EmployeeLoginI newEmployeeLogin() {
EmployeeLoginI facade = (EmployeeLoginI) create();
return facade;
}

protected Object create() {
if ("pojo".equalsIgnoreCase(mode))
{
try
{
return Class.forName(implClass).newInstance();
}
catch (ClassNotFoundException cnfe)
{
throw new RuntimeException("Impl class:" + implClass + "not found", cnfe);
}
catch (IllegalAccessException iae)
{
throw new RuntimeException("Can't access class:" + implClass, iae);
}
catch (InstantiationException ie)
{
throw new RuntimeException("Can't create class:" + implClass, ie);
}
}
else
throw new RuntimeException("Incorrect mode specified:" + mode);
}
}



// Proxy

public class LoginBD {
private EmployeeLoginI employeeLoginI;
private LoginI loginI;

public LoginBD() {
employeeLoginI = EmployeeLoginFactory.getInstance().newEmployeeLogin();
}

public EmployeeTO checkForAvailability(String userName){
return employeeLoginI.checkForUserNameAvailability(userName);
}

public EmployeeTO validateEmployee(String userName,String password) {
return employeeLoginI.findByLoginDetails(userName,password);
}

public void confirmRegister(EmployeeTO employeeTO){
employeeLoginI.registerEmployee(employeeTO);
}
}



public class EmployeeLoginController {
public static void main(String[] args){

LoginBD loginBD = new LoginBD();

// check whether the username is available
EmployeeTO availableEmployeeTO = loginBD.checkForAvailability("xxx");

// if no users found with the username allow employee to register
if(availableEmployeeTO == null)
loginBD.confirmRegister(employeeTO);

// Validate login details when employee tries to login
loginBD.validateEmployee(userName,password);
}
}






Java's built-in support for Proxy can build a dynamic proxy class on demand and dispatch all calls on it to a handler of your choosing.

Like any wrapper, proxy will increase the number of classes and objects in your designs.


Rules of thumb

1. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface. [GoF. p216]

2. Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests. [GoF, p220]

3. Proxy controls access to objects . But Decorator decorates the objects by adding behaviour to them.


Hope this explanation helps.

Wednesday, 10 September 2008

Template Method Pattern

Template method defines the skeleton of Algorithm(steps of algorithm) in a method, differing some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

The objective is to ensure that algorithm's structure stays unchanged, while subclasses provide some part of implementation.



This pattern is all about creating a template for an algorithm. Here Template is nothing but a method; more specifically it is a method that defines an algorithm as a set of steps.

Let us look at an example


abstract class Generalization {

// 1. Standardize the skeleton of an algorithm in a "template" method
public final void findSolution() {
stepOne();
stepTwo();
stepThr();
hook();
}

// 2. Common implementations of individual steps are defined in base class
protected void stepOne() { System.out.println( "Generalization.stepOne (Common)" ); }

// 3. Steps requiring particular impls are "placeholders" in the base class
abstract protected void stepTwo();
abstract protected void stepThr();

// 4. This is hook method (concrete method) which provides default implementation, but
// allows subclasses to override if necessary.
protected void hook() {
System.out.println( "This is default implementation of hook method");
}
}

class SpecializationOne extends Generalization {

// 5. Derived classes can override placeholder methods
protected void stepThr() {
System.out.println( "SpecializationOne.stepThr" );
}

protected void stepTwo() {
System.out.println( "SpecializationOne.stepTwo" );
}
}

class SpecializationTwo extends Generalization{

// 5. Derived classes can override placeholder methods
protected void stepTwo() {
System.out.println( "SpecializationTwo .stepTwo" );
}

protected void stepThr() {
System.out.println( "SpecializationTwo.stepThr" );
}

protected void hook() {
System.out.println( "SpecializationTwo .hook" );

}
}


Hook is a method that is declared in abstract class, but only given empty or default implementation. This gives the subclasses the ability to hook into the algorithm at various points, if they wish. Subclass is also free to ignore the hook method.

When to use abstract method and when to use hooks?
Use abstract methods when your subclass must provide the implementation. Choose hook when it is optional for subclasses to implement it.


Hollywood Priciple:

Don't call us we will call you.

Hollywood Priciple allows us to prevent dependency rot.

With the hollywood priciple, we allow low level components to hook themselves into a system. But high level components decide when they are needed and how... In other words high level components give 'don't call us, we will call you' treatment to low level components.

The connection between Hollywood Principle and Template Method Pattern is probably somewhat apparent.

In our above example Generalization is our high-level component. It has control over the sequence of methods to be called and calls on the subclasses only when they are needed for implementation of a method.

Client will depend on Generalization rather than concrete SpecializationOne or SpecializationTwo which reduces dependencies in overall system.

The subclasses never call abstract class directly without being 'called' first.

Difference between Dependency Inversion Principle and Hollywood Principle

Dependency Inversion principle tells us to avoid use of concrete classes and instead work as much as possible with abstractions.
The Hollywood princple is a technique for building frameworks or components so that lower level components can be hooked into computation but without creating dependencies between lower level components and higher level layers.

So they both have goal of decoupling but Dependency Inversion Principle makes a strong and general statement about how to avoid dependencies in design.

The Hollywood principle gives us a technique for creating designs that allow low level structures to interoperate while preventing other classes from becoming too dependent on them.


Advantages of Using The Template Method Design Pattern


1. No code duplication between the classes

2. Inheritance and Not Composition
Whenever a design pattern uses inheritance as a key element instead of composition, you need to consider the reason. To understand the reason, you need to fully understand the principle of favoring composition over inheritance as a general principle in good OOP. The principle's established because of certain advantages of composition over inheritance, especially the composition advantage of not breaking encapsulation. However, Gamma, Helm, Johnson and Vlissides (GoF) note that inheritance also has certain advantages. One such advantage is that when using subclasses where some but not all operations are overridden, modifying the reused implementation is easier. Because the Template Method design pattern does exactly that—uses some but not all operations that can be overridden to achieve flexibility—it incorporates a key advantage of inheritance over composition.

3. By taking advantage of polymorphism the superclass automatically calls the methods of the correct subclasses.

Comparision of different Patterns:

Template Method Pattern : Subclasses decide how to implement steps in an algorithm.

Strategy Pattern : Encapsulates interchangable behaviours and use delegation to decide which behaviour to use.

Factory Method: Subclasses decide which concrete classes to create.


Hope this explanation helps...

Friday, 5 September 2008

Facade Pattern and Principle of Least Knowledge

Facade provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easy to use.

A Facade not only simplifies an interface, it also decouples a client from subsytem of components.

Using Facade Pattern you can take a complex subsystem and make it easier to use by implementing a Facade class that provides resonable interface.

For Example,Let us think we have subsytem containing Gate, GarageDoors, CarLock, Lights etc..

Now we will be having a single iterface which will do simplify the subsystem for us.


public class HomeFacade{
Gate gate;
GarageDoor garageDoor;
CarLock carLock;
Lights lights;
MainDoor door;

public HomeFacade(Gate gate,GarageDoor garageDoor,CarLock carLock,Lights lights,MainDoor door){
this.gate = gate;
this.garageDoor = garageDoor;
this.carLock = carLock;
this.lights = lights;
this.door = door;
}

public void reachHome(){
gate.open();
garageDoor.open();
carLock.lock();
door.open();
lights.on();
gate.close();
garageDoor.close();
door.close();
}

public void leaveHome(){
door.open();
lights.off();
door.close();
garageDoor.open();
carLock.unlock();
gate.open();
garageDoor.close();
gate.close();

}
}


The Facade still leaves the subsystem accessible to be used directly. If you need the advanced functionality of the subsystem classes, they are avilable for your use. (As Facade doesn't encapsulate the subsystem classes, but it provides a simplified interface)

Facade is free to add its own specialization in addition to making use of subsystem.

For a subsystem, we can have number of Facades.

Design Principle behind Facade pattern :

Priciple of least knowledge : When you are designing a system, for any object be careful of the number of classes it interacts with and also how it interacts with those classes. Also known as law of Demeter.

This principle prevents us from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade to other parts. when you build a lot of dependencies between many classes, you are building a fragile system that is costly to maintain and complex for others to understand.


But how to implement this design priciple?

Take any object. Now from any method in that object, we should only invoke methods that belong to

1. The Object itself
2. Objects passed in as a parameter to the methods
3. Any object that method creates and instantiates.
4. Any components of objects. (Has-A relationship)
(Dont call methods on objects that were returned from calling other methods)

Example :

Without principle :


public float applyForJob(){
Agency agency = company.getAgency();
return agency.searchJob();
}


Here we are dependent on Agency Class also

With principle:


public float applyForJob(){
return company.searchJob();
}


This reduces the number of classes we are dependent on.

Primary benifit is that the calling method doesn't need to understand structural makeup of the object it's invoking methods upon.

The obvious disadvantage of using this principle is that we must create many methods that only forward method calls to the containing classes internal components. This can contribute to a large and cumbersome public interface.

An alternative to this principle or variation on its implementation, is to obtain a reference to an object via a method call, with the restriction that any time this is done, the type of reference obtained is always an interface datatype. As we are binding ourselves with directly to the concrete implementation of a complex object, but instead we are depending on abstractions of which the complex object is composed.

A very nice example of the above approach is java.sql.ResultSet interface.

After an SQL statement has been executed, Java stores results in a ResultSet Object. One of our options at this point is to query this resultset object and obtain metainformation pertaining to this set of data. The class that contains this metadata is ResultSetMetaData class and it's contained with resultset class. We cant directly obtain reference of this class, but instead would call methods on the ResultSet which subsequently forward these requests to ResultSetMetaData Class. This would results in explosion of methods on ResultSet class. Therefore getResultSetMetaData() method on ResultSet would does return a reference to ResultSetMetaData. However as ResultSetMetaData is an interface we are not bound to any concrete implementation contained within resultset.

Difference between Adapter pattern and facade Pattern:

Adapter Pattern changes the interface of one or more classes into one interface that a client is expecting while a Facade may provide a simplified interface to a single class with a very complex interface.

Facade and Adapter may wrap multiple classes but facade's intent is to simplify and adapter's intent is to convert the interface to something different.

Hope it will be useful.