Best practice for DAO pattern?

Sawyer picture Sawyer · Mar 18, 2010 · Viewed 11.4k times · Source

I've seen a lot of codes use a service-dao pattern , I don't know the origin of this pattern . It force the front layer call service , then delegates some of the service task to dao.

I want to ask :

  1. Does DAO layer do purely data access related task ? What about things like exception encapsulation?
  2. Is there any other pattern can be used to replace this or better than this ?
  3. I think pojo domain models and transaction scripts make even simple problem became complicated , is it possible to completely eliminate dao layer ?

Answer

Ronald Wildenberg picture Ronald Wildenberg · Mar 18, 2010

Ideally, your DAO layer 'abstracts away' the access to some data storage system (database, file system, LDAP directory, ...). So in that sense it is used only for data access related tasks. However, you could also have a DAO layer that accesses a web service or some other component external to your application. That's the key point, it provides access to some external component.

The main idea is that there are no implementation details of your DAO layer that escape to higher layers (isolation). A good starting point for thinking about this is: what would I need to do if I plan to replace the component (a database for example) that my DAO layer provides access to? For example, you have some data inside XML files and you plan to migrate the data to a database.

Suppose you have all kinds of XML-related exceptions that escape your DAO layer. Then it becomes quite hard to migrate your XML layer to a database layer. However, if you've encapsulated all implementation details of your DAO layer, this will become a lot easier.

In the end, it's about maintainability of your code. The less dependencies you have on implementation details of a specific layer (services, DAO, ...), the better maintainable your code is.