Monday, September 29, 2008

IOC Design Pattern

  1. The basic jist of IoC is that if your class needs an object that is outside of its primary responsibilities, it should not instantiate it itself, but rather should accept that object either in a constructor or with a setter method.
  2. This form of IoC has been around for longer than the term IoC has been in use — many of you might have used such a form of IoC when using the EJB framework, for example. Here, your components extend and implement specified interfaces, which then get called by the framework itself.
[Src: http://www.devx.com/Java/Article/27583]
 ------------------------------------------------------------------------------------------------------
“Always expect to be called. If you ever need to call, never call direct. Always ask the framework. The framework knows.”
-------------------------------------------------------------------------------------------------------
Src: http://neelzone.wordpress.com/2007/04/04/injection-and-inversion/

Using object-oriented design principles and features such as interface, inheritance, and polymorphism, the IoC pattern enables better software design that facilitates reuse, loose coupling, and easy testing of software components.

Basis of Ioc Design Pattern
Assume Class A has a relationship with Class B: it wants to use the services of Class B. The usual way to establish this relationship is to instantiate Class B inside Class A. Though this approach works, it creates tight coupling between the classes. You can't easily change Class B without modifying Class A. To eliminate the coupling, you can have a Configurator inject the instance of Class B (Object "b") to the instance of Class A (Object "a"). If you want to change the implementation of Class B later on, you simply change the Configurator object. So, the control of how Object "a" gets the reference of Object "b" is inverted. Object "a" is not responsible for getting the reference to Object "b". Instead, the Configurator is responsible for it. This is the basis for the IoC design pattern.

Simple Example :


Figure 1. Object "a" Directly Creates Object "b"
To demonstrate the benefits of the Configurator object in this case, the following examples show a simple design without IoC and one with IoC (click here to download the sample code for this article).


public class A{
private B b;

public A(){
b=new B();
}

Listing 1. Class A Directly Refers Class B
Listing 1 assumes the following design decisions:
  1. Class A needs a reference to Class B.
  2. Class B is a concrete class that has a default constructor.
  3. Class A owns the instance of class B.
  4. No other class can access the instance of Class B.

Figure 2. Object "a" First Creates Object "c" and Then Object "b" by Passing Object "c"
If any one of the above design decisions change, then the code in Listing 1 must be modified. For example, if Class B changed to have a non-default constructor, which takes Class C (see Figure 2), then Listing 1 would change to Listing 2.

public class A{
private B b;

public A(){
C c=new C();
b=new B(c);
}

Listing 2. Class A Directly Refers Class B and Class C
Once again, Listing 2 assumes certain design decisions. Now Object "a" owns both Object "b" and Object "c". If Class B or Class C changes at all, then Class A needs to change as well. In essence, a simple design of a simple class with implicit design assumptions becomes a maintenance nightmare in the future. Consider how difficult making changes would be if you had this scenario in a typical application with several classes.
Alternatively, if you use a framework that uses the IoC pattern, the responsibility of creating Object "b" moves from Object "a" to the IoC framework, which creates and injects Object "b" into Object "a". This insulates Class A from the changes in Class B. Before Object "a" is used, it needs the reference to Object "b". The IoC framework will inject Object "b" into Object "a".

Figure 3. IoC Framework Creates Object "b" and Sets It to Object "a"
Listing 3 shows Class A from the previous listings modified to use the IoC pattern.

public class A{
private B b;

public A(){
}

public setB(B b){
this.b=b;
}

}

Listing 3. Class A Gets the Reference to Class B via setB
Listing 3 assumes the following design decisions:
  1. A needs a reference to B, and it doesn't need to know how B is instantiated.
  2. B can be an interface, an abstract class, or a concrete class.
  3. Before the instance of Class A is used, it needs a reference to the instance of Class B.
From the above design decisions, you can see that there is no tight coupling between Class A and Class B. Both can be changed independently without affecting each other. Of course, if there is any change in the public methods of Class B, Class A needs to change as well. But how Object "b" is created and managed is not decided in the implementation of Object "a". Instead, the IoC framework uses the setB() method in Object "a" to inject Object "b"

open source IoC frameworks like Spring, PicoContainer, and HiveMind support the IoC pattern.

  • The IoC pattern can be implemented in three ways:
1. setter based
2. constructor based
3. interface based.

Setter-Based IoC
This type of IoC uses a setter method to inject the referenced object into a referring object. This is the most common type of IoC, and both Spring and PicoContainer implement it.

+ Setter-based IoC is good for objects that take optional parameters and objects that need to change their properties many times during their lifecycles.

- Its main disadvantage is that you need to expose all the properties of an object to the outside world when using a setter method.
-This breaks one of the key OO principles: data encapsulation and information hiding.

Constructor-Based IoC

This type of IoC uses a constructor to set the reference of the object. A constructor-based IoC is the main type of implementation in Spring.

+ Its main advantage is that only the creator knows about the referenced object. Once the object is created, the client code that uses the object is unaware of the referenced object.

-This approach may not work in all types of applications, however. For example, if you use an external API that needs a default constructor, then you need to go with a setter-based IoC.

Interface-Based IoC

In this type of IoC, objects implement a specific interface from the IoC framework, which the IoC framework will use to properly inject the objects. Apache Avalon is based on this approach but this project has been closed.

+One of the main advantages of this type is that it doesn't need an external configuration file to configure the object references. Since you need to use the IoC framework's marker interface, the IoC framework knows how to glue the objects together.
Ex. It is similar to using EJB. Any EJB container knows how to instantiate your objects and hook them with itself.

-The main disadvantage of this approach is that the marker interface ties your application to a specific IoC framework.

Code with Example :
DataSource
First, design an interface (see Listing 4) and define common methods, which you will use to retrieve and store customer data. Both XMLDataSource and JDBCDataSource classes implement this interface.

public interface DataSource {
public Object retrieveObject();
public void setDataSourceName(String name);
public String getDataSourceName();
public void storeObject(Object object);
}

Listing 4. Common Interface to Customer Data
XMLDataSource
Listing 5 shows a class that implements DataSource and provides an implementation that uses an XML file to retrieve and store customer data.

public class XMLDataSource implements DataSource {
private String name;

/**
* Default Constructor
*/
public XMLDataSource() {
super();
}

/**
* Retrieve Customer data from XML Source and construct
* Customer object
*/
public Object retrieveObject() {
//get XML data, parse it and then  construct
//Customer object
return new Customer("XML",10);
}

/**
* Set the DataSource name
*/
public void setDataSourceName(String name) {
this.name=name;  
}

/**
* Return DataSource name
*/
public String getDataSourceName() {
return name;
}

/**
* Store Customer into XML file
*/
public void storeObject(Object object) {
//Retrieve customer data and store it in
//XML file

}

}

Listing 5. Class to Retrieve Customer Data from XML File
RelationalDataSource
The class in Listing 6 also implements DataSource and provides the same implementation as XMLDataSource with only one difference: this class retrieves and stores customer data using a relational database.

public class RelationalDataSource implements DataSource {
private String name;

/**
* Default constructor
*/
public RelationalDataSource() {
super();
}

/**
* Using the DataSource retrieve data for Customer and build a
* Customer object to return it to the caller
*/
public Object retrieveObject() {
//get data for Customer object from DB and create a
//Customer object
return new Customer("Relational",10);
}

/**
* Set the DataSource name
*/
public void setDataSourceName(String name) {
this.name=name;  
}

/**
* Return the name of the DataSource
*/
public String getDataSourceName() {
return name;
}

/**
* Store Customer into relational DB
*/
public void storeObject(Object object) {
//store the customer data into Relational DB

}

}


Listing 6. Class to Retrieve Customer Data from Relational DB
Customer
The simple class in Listing 7 holds customer data, which either the XMLDataSource or RelationalDatSource object will construct.

public class Customer {
private String name;
private int age;

/**
* Default Constructor
*/
public Customer(String name, int age) {
this.name=name;
this.age=age;

}

/**
* @return Returns the age.
*/
public int getAge() {
return age;
}
/**
* @param age The age to set.
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
}

Listing 7. Class That holds Customer Data

CustomerService
This class in Listing 8 has a reference to DataSource, which it uses to retrieve and store Customer objects. The actual implementation of DataSource will be either XMLDataSource or RelationalDataSource, which will be injected into the CustomerService object. The constructor of the CustomerService object accepts a concrete implementation of the DataSource object and uses it to retrieve and store customer data.

public class CustomerService {
private DataSource dataSource;
private Customer customer;

/**
* Constructor in which DataSource object is injected. Based on the
* ioc.properties this object can either refer to RelationlDataSource or
* XMLDataSource
*/
public CustomerService(DataSource dataSource) {
super();
this.dataSource=dataSource;
customer=(Customer)dataSource.retrieveObject();
}

/**
* Modify Customer name
* @param name
*/
public void updateCustomerName(String name) {
customer.setName(name);
}

/**
* Modify Customer age
* @param age
*/
public void updateCustomerAge(int age){
customer.setAge(age);
}

/**
*
* @return Customer name
*/
public String getCustomerName(){
return customer.getName();
}

/**
*
* @return Customer age
*/
public int getCustomerAge(){
return customer.getAge();
}
}
Listing 8. CustomerService Class That Gets DataSource Reference via ServiceConfigurator
Figure 4. IoC Using ServiceConfigurator
ServiceConfigurator
The ServiceConfigurator in Listing 9 is a main class that uses the IoC pattern to inject the concrete implementation of DataSource into the CustomerService object. It reads the configuration parameters (see Figure 4) from the ioc.properties file and decides to create either an XMLDataSource or a RelationalDataSource object. The DataSource object is created using its default Constructor, and the name of the DataSource is set using its setter method. The created DataSource object is injected into CustomerService using its constructor, which accepts a DataSource reference. The created CustomerService object is stored in the ServiceConfigurator registry so that it will be returned when a subsequent request comes for the CustomerService object.
Figure 4 shows the inner workings of ServiceConfigurator, and Figure 5 shows the UML diagram for all of the classes explained previously. You can switch between XMLDataSource and RelationalDataSource just by editing the ioc.properties file.
public class ServiceConfigurator {
public static final String IoC_CONFIG_FILE="ioc.properties";
private Properties props;
private HashMap serviceRegistery;
private static ServiceConfigurator thisObject;

/**
* This method first checks if there is a ServiceConfigurator instance
* exist, if not creates a one, stored it and returns it
* @return
*/
public static ServiceConfigurator createServiceConfigurator(){
if(thisObject==null){
thisObject=new ServiceConfigurator();
}
return thisObject;
}

/**
* Private Constructor makes this class singleton
*/
private ServiceConfigurator() {
props = new Properties();
serviceRegistery=new HashMap();  
loadIoCConfig();
createServices();
}

/**
* Load the IoC_CONFIG_FILE properties file
*
*/
public void loadIoCConfig(){
InputStream is = this.getClass().getClassLoader().getResourceAsStream(IoC_CONFIG_FILE);
try {
props.load(is);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Create the CustomerService by getting the DataSource name from the
* properties file. The CustomerService object is stored in the
* serviceRegistery so that it will be retrieved when requested.
* During the construction of CustomerService the DataSource object
* is injected into it. So the CustomerService can access the DataSource
* to retrieve the Customer.
*
*/
public void createServices(){
String dataSourceName=props.getProperty("dataSource");
DataSource dataSource=null;
if(dataSourceName!=null){
try {
dataSource=(DataSource)Class.forName(dataSourceName).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//name of the DataSource is retrieved from the properties file
dataSource.setDataSourceName(props.getProperty("name"));
CustomerService customerService=new CustomerService(dataSource);
serviceRegistery.put(CustomerService.class,customerService);
}
/**
* Stored Service is retrieved from serviceRegistery for the given
* Class object
*
* @param classObj
* @return
*/
public Object getService(Class classObj){
return serviceRegistery.get(classObj);
}

}
Listing 9. ServiceConfigurator that Uses IoC to Inject DataSource into CustomerService

The ServiceConfigurator is a simple class that supports the IoC pattern. You can modify it to add more features such as simultaneously
supporting multiple DataSource objects, dynamically injecting the DataSource into CustomerService, and life cycle management.



----------------------

Figure 5. ServiceConfigurator UML Class Diagram

Service Configurator vs. Service Locator
The implementation of ServiceConfigurator in Listing 9 may lead you to think that there is no difference between the ServiceConfigurator class that uses IoC and one that uses the Service Locator pattern. In fact, you can modify the CustomerService in Listing 8 to use a Service Locator, which will give the CustomerService class either an XMLDataSource or a RelationalDataSource object, based on the Service Locator's internal implementation. By changing the internal implementation of Service Locator, you can switch the DataSource from which CustomerService gets its Customer. In this context, both Service Locator and ServiceConfigurator provide the same functionality to CustomerService. The main difference is how CustomerService gets the DataSource reference. In Service Locator, CustomerService must get the DataSource reference directly from Service Locator, while in ServiceConfigurator, CustomerService gets the DataSource indirectly through ServiceConfigurator.

So, what is the advantage of using Service Locator instead of ServiceConfigurator? ServiceConfigurator frees CustomerService from either acquiring or instantiating the DataSource directly. This makes CustomerService easy to test: simply inject the appropriate DataSource into it. More over, as explained previously in Listing 1 and Listing 2, because you do not make any assumptions about how CustomerService will get the DataSource reference, you can reuse the CustomerService object in different applications. This is the main advantage of using Service Configurator over Service Locator.
                                                                                                                                                                

Some difference between Service Locator and Dependency Injection



As shown above, service locator will give the object and that is used to call the methods of that object, for that we need to write the jndi lookup and jndi registration .




In Dependency Injection, modules no longer look each other to make a call.  In java mostly metod parameters plays a role in calling the methods of the callable module( Using introspection).

In ServiceLocator  we have to write the code for communication between components, where as in DependencyInjection  framework will provide the wiring between the modules.

Monday, September 1, 2008

RDBMS

Inner Join

Definition: An inner join is a join that selects only those records from both database tables that have matching values. Records with values in the joined field that do not appear in both of the database tables will be excluded from the query. One or more fields can serve as the join fields.

  • The inner join is also known as an equi-join.

Conceptual diagram of the inner join

The above shows a conceptual diagram of the inner join between Customer data and Order data.

Analogy: Consider a business that employs both managers and engineers - and some employees that are both. An inner join is like a union of this set; it selects the set of people that are both managers and engineers and provides information about them in both roles.

Outer Join

Definition: An outer join selects all of the records from one database table and only those records in the second table that have matching values in the joined field. In a left outer join, the selected records will include all of the records in the first database table. In a right outer join, the selected records will include all records of the second database table. One or more fields can serve as the join fields.

Left Outer Join example:

Conceptual diagram details the Left Outer Join

The above conceptual diagram details the Left Outer Join between Customer data and Order data

Analogy: Consider again the business that employs both managers and engineers. A left outer join selects all of the managers, providing the information about them, but in the case of managers who are also engineers, it provides additional information about them.

Right Outer Join example:

Conceptual diagram of a Right Outer Join

The above shows a conceptual diagram of a Right Outer Join between the Customer data and the Order data.

Analogy: Consider again the business that employs both managers and engineers. A right outer join selects the set of all engineers, providing information about them, but in the case of engineers and also managers, if provides additional information about them.

(Src: www.databasedev.co.uk/query_joins.html)

Joins in Venn Diagrams

JOIN OPERATOR

The JOIN operator specifies how to relate tables in the query. The JOIN operator is one of the set operations available in relational databases.

The following join types of join are available in most relational databases:

INNER OUTER (LEFT. RIGHT, FULL) CROSS

Joins may be represented as Venn diagrams, as shown below along with other common set operations:

join types

Result of applying these joins in a query:

INNER JOIN: Select only those rows that have values in common in the columns specified in the ON clause.

LEFT, RIGHT, or FULL OUTER JOIN: Select all rows from the table on the left (or right, or both) regardless of whether the other table has values in common and (usually) enter NULL where data is missing. (Note: FULL OUTER JOIN not implemented in Access.)

CROSS JOIN (not illustrated - not exactly a set operation): Select all possible combinations of rows and columns from both tables (Cartesian product). Not available in Access but can "happen" by not specifying relationships between tables or not setting up the appropriate joins in a query. (Not A Good Thing - the query may run for a very long time and produce a huge, not very useful result set.)

Access uses the ANSI (American National Standards Institute) style, with the JOIN and ON keywords. Access, MySQL, and Oracle all use similar syntax, with more join types and options and other set operations in MySQL and Oracle (CROSS JOIN, FULL OUTER JOIN, INTERSECT, MINUS).

src: www.udel.edu/.../SQL-Class2/SQLclass2_Join.html

About Me

This Vamsi,Indian. When i was child, i use to think to become Detective, i dont know why, now iam Techie , future may be Farmer. I feel always Competition drives me.. Loves Challenging Jobs. Free Time Plays Cricket or Play Games in Computer. I like Characteristics of BagathSingh(Commitment),Chanakya(Strategist),Hitler(Manager,Initiater) . My Principle is follow the moto of the Rule , Not Rule. Newtons Formula applies to me :"Every object in a state of uniform motion tends to remain in that state of motion unless an external force is applied to it" , in other Words a bit Lazy.