Monday, June 23, 2008

IoC (Inversion Of Control) and Dependency injection (DI)


Introduction:

Lots of us hear this word and also hear that this container is using IoC (inversion of control) so what is it all about and what does this mean? we will be working using Spring IoC through this article so lets start by checking the formal definition of the Dependency injection:“Dependency injection (DI) in Computer programming refers to the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.”Ho ho sounds little bit confusing, so lets make it more simple so first we need to know what is IoC and what is DI .Well we can say that IoC is a generic term and the DI is a more specific term so this mean that Dependency injection is more specific term than the IoC but still don't understand the IoC thing.

Life Without IoC and DI

In a standard component container,the component themselves ask the container for the resources they want for example lets check this segment of code (which you can find in most of EE application):

Context context=new InitialContext();
DataSoruce dataSource=(DataSource)context.lookup("jdbc/TestingDS");
Connection connection=dataSource.getConnection("yourUser","yourPassword");
Statement statement=connection.CreateStatment();
ResultSet results=statement.executeQuery("select * from users");
.
.
. //i didnt include all the code just the important thing

so in the above code we just initialize a context (JNDI)
and perform a lookup for a resource bounded at jdbc/TestingDS and then get the results and cast it as a DataSource after that we use it and continue with our processing.

oh yea so every time i want to do so i will have to make the lookup thingy to get the data source or any resource i might need.
mmm so i will keep asking my container to give me what i want? yup you will.
well lets see how would the container and the component interact with each other (without IOC)

A Day in the Container's Life !

Component: Hi Mr.Container.
Container:Hi Component.

Component:how is your day?
Container :oh i have been busy serving all other components and don't have time for myself :( .

Component:oh poor you Mr.Component.
Container:ahh what can i do this is my job :) , so how can i serve you ?
Component :oh yea i forgot , i want to you to serve me the resource bounded at bla bla bla
Container:ok sure no problem, just a min. here you are (hehehe now we got what we want :D )
Component:oh many thanks MR.Container, have a nice day.
Container:you too component bye.

so in here as we can see the component keeps asking the container to provide the needed resources.

Hollywood and IoC:

IoC as most of people say it apples Hollywood principle which is :

Component: Hello Mr.Container !Container :don't call Me, I will call you.TEET TEET TEET (the container hanged the phone :S )
Component : Shocked :|

This is what they call: don't call us , we will call you principle.

yup it is what you are thinking in , yes the container will take control over the resources for the
component but without involving the component in that, in other words the control of the resource will be inverted from component to container and its configuration(through XML as most of people do and as i do)


Life With IoC:


what if we want to apply IoC on the previous example?

Ok, so we will just need to modify some stuff (adding a property for the DataSource and also using spring framework)

//class that contains the code for spring IOC
private DataSource dataSource;

public void setDataSource(DataSource ds)
{
dataSource=da;
}

public static void man(String[] args)
{
//so now dataSource is set by Spring IOC
Connection connection=dataSource.getConnection("yourUser","yourPassword");
Statement statement=connection.CreateStatment();
ResultSet results=statement.executeQuery("select * from users");
. . . //i didnt include all the code just the important thing
}

//segments from XML configuration file

<%bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<%property name="driverClassName" value="youDriverClassName" />

<%property name="url" value="DBUrl" />

<%property name="username" value="yourUsername" />

<%property name="password" value="youPassword" />

<%bean name"ourComponent" class="com.springIoC.IoCTesting">

<%property name="dataSource" ref="dataSource">

<%/bean>


as we can see in the above XML we just stated that we have a bean from class bla bla which has a property named dataSource so spring IoC will just think like that :

mmm (spring IoC thinking...)
oh yea i have a bean named ourComponent .
wait a minute this bean have a property named dataSource! .
this property refers to another bean named dataSource which have some property (url,username,password,driverclassname) .
oh great so now what i need to do is inject this bean property (data source property in the ourComponent ) with the Datasource ,TA DA now it is done.

so we can see here that we didn't make any lookup , so there is zero times component did ask the container about the DataSource.
in this case the control over deciding which DataSource to use is in the container not the component so once the container gets a DataSource it will pass it to the component by calling the setter (SetDataSource).when spring IoC container loads at runtime it will inject the dependency into our component (this is done at runtime by XML configuration as we can see above) so the Data Source will be injected into ourComponent and now we can make anything with this data source (with zero component to container call).

below is a diagram that shows the interaction in case we are using IoC or non IoC Container.

in the first we can see that the component ask the container to provide the resource it need (data source in our case ) but in the second image the container creates and inject the resource into the component



























Types Of Injection:
We have seen in the previous sample that spring do the injection through setter (property) thats one way of injection , another way it to inject through the constructor (which spring also support)
this mean that i can inject all resource in the component through a constructor (and that constructor takes all the needed resource through arguments supplied)


so now we know what is Dependency injection and also the IoC concept , there are also some IoC containers other than spring IoC container for example :Pico container and also Avalon framework

Read more!

Wednesday, June 18, 2008

DOM,SAX,StAX,TrAX !!!

Difference between the following guys (we are talking about xml here :D ):

1-DOM
2-SAX
3-StAX
4-TrAX

Guess that all of us knows what is DOM and some might know what is SAX but the major don’t know what is StAX and TrAX(most of ppl don’t know what is that)

As expected from the mighty JAVA it supports more things than the humble .NET :D as we can see in .NET 2003 it only supports DOM and don’t support any other

thing than DOM (I worked with .net 2003 I was .net develoepr at 1st but didn’t used 2005 extensivly so am not sure if MS supports it now or no but SAX was not

supported in the 1st palce in .NET )

So lets start with defining each of them :

DOM:
DOM creates XML tree that is represented in the memory (for the document). It provides a very flexible API for creating, reading, updating, and deleting nodes within the tree, in general, an memory representation of the document is required; this is bad if we looked at the performance. This means that the DOM loads all the xml document into the memory so if we have 1 MB of xml then 1 MB of memory will be reserved for this document which is not good choice in large documents but note here that it is good in CRUD operations (we will know why later)

SAX:
SAX is a "push"(take care from this we will see it later) type that provides an event callback interface. There is only a reading. SAX requires that an entire XML document be read. But , it doesn't require the entire document to be held in memory at any point in time. SAX is a very low level, efficient for parsing XML documents. this is a good choice if you have large Documents either with events or without events!!!(SAX is used for processing xml for events meaning that you can find an event in the xml that tells the code snippet that will handle the event to do something)

PUSH!!! So there must be a PULL then!!! Yup that’s right there is PULL and PUSH and the different is next time :p

StAX:
StAX is a "pull" type o. there are a Cursor and an Event Iterator API. There are both reading and writing sides of the API. It is more developer friendly than SAX. StAX doesn't require an entire document to be held in memory. But you won’t need to read the whole document (the best part). Portions can be skipped. This improves the performance of StAx more than SAX.

TrAX:
TrAX is for transforming source documents into result documents using XSLT, rule-based language. A TrAX source document may be created via SAX or DOM. TrAX needs both Java and XSLT skills. Optimizing TrAX takes more time (to transform from one xml into another)


After that we can say that:

1-
SAX and StAX are better in the performance issue and the memory thing
But in case of DOM and TrAX it depends (on how large the document is and on what you are doing)
2-
Dom is the only one that supports CRUD operations

3-
SAX and StAX are forward only but DOM and TrAX can be both ways (forward and backward)

Read more!