Wednesday, 22 June 2011

Data Access Object ( DAO ) Pattern

A data access object (DAO) is an object that provides an abstract interface to some type of database or persistence mechanism, providing some specific operations without exposing details of the database. It provides a mapping from application calls to the persistence layer.

A typical DAO implementation has the following components:
  • A DAO interface
  • A concrete class that implements the DAO interface
  • Entities OR Data transfer objects (sometimes called value objects)
Seeing all the components with the Example

Entity

Order.java
public class Order{
private int id;
private String customerName;
private Date date;

public int getId() { return id; }
public void setId(int id) { this.id = id; }

public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) {  
          this.customerName = customerName;  
    }

public Date getDate() { return date; }
public void setDate(Date date) { this.date = date;}
}

DAO interface
OrderDao.java
Get the interface for Create Retrieve Update and Delete operations.

//holds all CRUD behaviours
public interface OrderDao {
void create(Order entity);
Order findById(int id) throws OrderDontExistException;
void update(Order entity);
void delete(Order entity);
}

DAO Implementation
OrderDaoImpl.java
This just takes the datasource object and stores all the queries related to Order object. I am just implementing finById method for simplicity.

public abstract class OrderDaoImpl implements OrderDao {

DataSource ds;
public OrderDaoImpl(DataSource ds_) {
ds = ds_;

}

public void create(Order entity) { //do something }

public E findById(int id) throws OrderDontExistException {
String sqlFindById = "select * from ORDERS where id=?";
Connection con = getConnectionFromDataSource(ds);
PreparedStatement ps= con.prepareStatement(sqlFindById);;
ps.setInt(1, id);
ResultSet rs = ps.execute();
//process result set
Order order = rs.getString("Name");
//... so on

return order;
}

public void update(Order entity) { //do something }

public void delete(Order entity) { //do something }

}

Exception class

package authordao;



public class OrderDontExistException extends Exception {


public OrderDontExistException() {

// TODO Auto-generated constructor stub

}


public OrderDontExistException(String message) {

super(message);

// TODO Auto-generated constructor stub

}


public OrderDontExistException(Throwable cause) {

super(cause);

// TODO Auto-generated constructor stub

}


public DAOException(String message, Throwable cause) {

super(message, cause);

// TODO Auto-generated constructor stub

}


}
Using the Dao

OrderDao dao = new OrderDaoImpl(ds);
Order order = dao.findById(id);
//Now do some business logic

Conclusion
As this article has shown, implementing the DAO pattern entails more than just writing low-level data access code. You can start building better DAOs today by choosing a transaction demarcation strategy that is appropriate for your application, by incorporating logging in your DAO classes, and by following a few simple guidelines for exception handling.

Exception transformer pattern

Checked exceptions are widespread in Java. Imagine the situation where you are calling numerous methods on a class (say for the sake of serving as an example: a service class) each of which throws a checked exception (say ServiceException).
class Service {

static class ServiceException extends Exception {}

void serviceMethod1() throws ServiceException {}
void serviceMethod2() throws ServiceException {}

}

Client with repetitive error handling logic
Your class as a client now has to deal with this exception every time you call a service method and also for every different method you call.
public class Client {

private Service service;

void callServiceMethod1Normally() {
try {
service.serviceMethod1();
} catch (ServiceException e) {
throw new RuntimeException("calling service method 1 failed", e);
}
}

void callServiceMethod2Normally() {
try {
service.serviceMethod2();
} catch (ServiceException e) {
throw new RuntimeException("calling service method 2 failed", e);
}
}

}


Exception transformer abstraction

However your exception handling strategy may be the same across your use of the service class only with a different message each time. Instead of repetitively duplicating your exception handling logic (try/catch) around every service call you can abstract this out as follows. The following class abstracts the logic out. Note that this class is only shown as a separate class for the purposes of incrementally describing the pattern. For best effect this class should ideally be contained within your client class as a static inner class.

public abstract class ExceptionTransformer {

abstract void call() throws ServiceException;

void transform(String message) {
try {
call();
} catch (ServiceException e) {
throw new RuntimeException(message, e);
}
}

}
New client using exception transformer

Now using the new exception transformer our exception handling logic is simplified to only the logic that differs between the client methods.

class ClientUsingExceptionTransformer {

private Service service;

void callServiceMethod1UsingTransformer() {
new ExceptionTransformer() {
@Override
void call() throws ServiceException {
service.serviceMethod1();
}
}.transform("calling service method 1 failed");
}

void callServiceMethod2UsingTransformer() {
new ExceptionTransformer() {
@Override
void call() throws ServiceException {
service.serviceMethod2();
}
}.transform("calling service method 2 failed");
}

}


Variation

This pattern can be easily varied to suit your personal exception handling styles. Here’s another variation where different checked exceptions are thrown by different service methods and handled by only logging them this time.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class ClientWithVariations {

static final Logger logger = LoggerFactory.getLogger(ClientWithVariations.class);

static class Service {

static class ServiceHungry extends Exception {}
static class ServiceSleepy extends Exception {}

void hungryMethod() throws ServiceHungry {}
void sleepyMethod() throws ServiceSleepy {}

}

private Service service;

void callHungryMethod() {
new ExceptionTransformer() {
@Override
void call() throws Exception {
service.hungryMethod();
}
}.transform("method was too hungry to respond :(");
}

void callSleepyMethod() {
new ExceptionTransformer() {
@Override
void call() throws Exception {
service.sleepyMethod();
}
}.transform("method was too sleepy to respond :(");
}

static abstract class ExceptionTransformer {

abstract void call() throws Exception;

void transform(String message) {
try {
call();
} catch (Exception e) {
logger.error(message, e);
}
}

}

}

This pattern really shows its value most effectively when you have numerous methods using it and also when there are multiple checked exceptions to handle resulting in multiple catch blocks all over the place.
Do you have any exception handling API patterns of your own? I know Joshua Bloch has suggested a few in Effective Java of which one comes to mind – an exception throwing method can be transformed into a boolean via another method which just returns false in the catch block and true elsewhere that can be quite useful if you don’t want to pollute the rest of the code with knowledge of this handling logic. By the way, before anyone mentions this I’m not suggesting converting checked exceptions to runtime exceptions or suppressing them by logging them is always the right thing to do. Thanks for reading.
P.S. This pattern will be particularly nice with closures in Java 8. And the multicatch in Java 7 will certainly also help make code more concise.

Monday, 20 June 2011

Fine grained and coarse grained objects

Some differences between fine grained and coarse grained objects:
  • If object composition is based on Object references (not one for one attribute) , then its Coarse grained . If object composition is based on attributes, then its fine-grained.
  • If there is one table to one object mapping, then its fine grained. If there is one object to more than one table, then its coarse grained.
  • If the object holds lot of information it is coarse grained. eg. Example: A single "Account" object holds the customer name, address, account balance, opening date, last change date, etc.

    Fine-grained: More objects each holding less data. Example: An Account object holds balance, a Customer object holds name and address, a AccountOpenings object holds opening date, etc. There are relationships defined between these objects.
     

Note:
May be I am wrong but what I was thinking, coarse object means a big object, that has much responsibility. For example, suppose we are designing a system and we have identified logical entities (business domain objects) (I am not sure, it is right term or not) and now we want to come up with java classes corresponding to those. So should we try to map one entity to one java class (coarse object) or try that one entity should include many classes (each one will be fine object). However if we have really big object, facade pattern do help by bringing infront the small object with which we have to deal with.

Tuesday, 14 June 2011

Repository pattern and the domain

http://blog.f12.no/wp/2009/02/02/repository-pattern/

Repositories vs DAOs

"Are Repository and DAOs the same thing with a different name?". The answer is not direct. Because they overlap a lot. Repositories and DAOs are two solution styles for approaching the same problem, with some small differences.
  1. DAOs are strictly tied to the underlying representation on a DBMS. The original specification is more generic, allowing for file-based persistence and the like. But the vast majority of DAOs are pointing to a DBMS. Moreover, commonly used persistence frameworks, such as Hibernate help a lot in managing database portability, so this is a smaller issue nowadays, than it used to be. As a result the DAO concept eventually downsized, to a "database access point" while Repositories are still intended to be generic.
  2. Repositories provide a more abstract view over the underlying data model, providing an interface strictly coherent with the domain. DAOs might be implemented basically in many ways, but frameworks and code generation tools tend to put the focus on the data structure rather than on the domain model. This is sometimes a tiny issue, sometimes just a matter of style, but in large systems can degenerate in a severe maintenance problem.
  3. Repositories enforce access to the persistence layer on a one-repository-per-aggregate basis, while DAOs are normally developed one-per-entity or one-per-table. So, repositories are more tied to the DDD concept of Aggregate Root and have a different granularity than DAOs. This definitely makes the most significant difference.
Somehow, the differences above are just a matter of taste, except for point 3. So objections are valid and discussion may result endless. But for now I'll just say that the two patterns are doing basically the same thing, although with different styles. There are differences, especially if approaching the matter from a DDD angle. What's left to say is if those differences are enough to make a choice between one pattern and another, or eventually to choose both.

Repository Pattern

Repository means storage location for safety and preservation.  Its a single place where you can find related items. This terminology is used by some frameworks like Spring. But whats the need of repository?

Example
Lets take an example. There is a big basket of toys. Toys contain Soft toys, wooden toys, miniature toys. If a kid wants miniature toys, he has to spill all the toys from the basket and separate the needed ones. Kid’s dad doesn’t want him to do that. He separates the miniature toys, that becomes a miniature toy repository, and gives it to child. Goal is never allow the kid to put hands on the basket.
 
Kid’s dad does the job of maintaining toy basket. Once the kid is done playing, he puts the toys back into the basket. When kid wants to play he gives the kid whatever toy he wants.  When dad brings a new toy for the kid, he is going to put that in the toy bag. In general, dad maintains the toy repository.

Implementation
Repository pattern, as described in Domain Driven Design, in a typical java environment backed by frameworks like Hibernate and Spring.

Child.java
public class Child   {
public void Play(ToyRepositoryBase toyRespository) {
//Gets all the toys seperated by Dad
List<Toy> toys = toyRespository.GetToys();
//Now child starts playing
System.out.println("Child is playing with " + toyRespository.GetType());
//Child is done playing. Now dad puts back the toy into the bag
toyRespository.PutToysBackIntoBasket(toys);
}
}


Get all the toys
//Toy is a abstraction of miniature toy or soft toy or wooden toy
public abstract class Toy
{

}

//Miniature toy is concrete class.
public class MiniatureToy extends Toy
{

}

Similarly we can have wooden toys, metallic toys and so on.
Get the toy repository

//This toy repository is abstract of miniature toy repository, wooden toy repository or soft toy repository
public abstract class ToyRepositoryBase {
//Child calls this to get toys before starting to play
public abstract List<Toy> GetToys();

//One child is done playing, dad puts the toys back into the basket
public abstract void PutToysBackIntoBasket(List<Toy> toys);
}

//Concrete class of miniature toy repository
public class MiniatureToyRepository : ToyRepositoryBase {
//Consider this as action performed by dad,
//who gives the miniature toys to child
@Override
public List<Toy> GetToys()
{
List<Toy> miniatureToys = new ArrayList<Toy>();
return miniatureToys;
}

//This is action performed by dad. Once child is done playing,
// he puts back the toys into bag
@Override
public void PutToysBackIntoBasket(List<Toy> toys)
{
//Here you can use cache or database
}
}
I have omitted other sub classes like WoodenToyRepository for brevity here.
We are not allowing the kid to put hands on the toy bag. Same way, business logic has no knowledge of database and  related implementation logic. All that business logic knows is how it can get the needed entity from repository, and how it can give the entity back to repository. It is the responsibility of repository to interact with the data source.
Advantage
This pattern has several advantages.
  1. No duplicate codes needed. If you got another child who wants wooden toys, same logic works.
  2. Business logic is simplified, since its interactions is only with repository and repository entities.
  3. Less scope for errors
  4. Strong typing, since Miniature toy repository gives miniature toys.
  5. Easy to test.

Respository and testing

http://xeon2k.wordpress.com/2010/12/14/repository-pattern-in-unit-testing/