Using IoC in DAO Development
The basics behind DAO design are rather simple and in fact is mostly just well applied “Interface Driven Design.” However, where many DAO implementation go awry is in either not completely separating concerns (that is, not completely isolating the data storage implementation from the data access logic) and in improperly “wiring” together the DAO interfaces from the DAO implementations. It just so happens that these problems are very well solved by the design patterns and concepts of Inversion of Control (IoC).
The purpose of Inversion of Control is to isolate control which in turn makes a system more stable and controls complexity. In our case, that means a components such as a DAO implementation does not control its own lifecycle and dependencies (such as creating database connections) but that these are instead handled by a central agent usually called a container. Within the DAO pattern the role of container is usually one or more DAO Factory or Manager classes but they are often not recognized as a container and consequently often do a very bad job of managing component control.
By replacing the specific DAO Factories and Managers with a single IoC Container you retain all the benefits of the DAO pattern and add the benefits of IoC: better separation of concerns and proper component (DAO) management. Additionally, you end up with a generic DAO framework of sorts, that is, you have a single consistent API for accessing DAOs via the container. The result? Better separation of concerns, proper inversion of control, a cleaner, simpler use of the DAO pattern.
So, how to you actually implement IoC into DAO? Thankfully you don’t need to write your own IoC container or framework since there are <a href=”http://lsd.student.utwente.nl/componentplanet/ContainerDatabase”>many available. My recommendation is something very lightweight such as <a href=”http://www.picocontainer.org”>PicoContainer. In fact, having once been fed up with all the existing DAO frameworks out there, I wrote my own, JingDAO, which is based on Pico and Avalon. I’m still fiddling with it and have no idea where it will end up, but it’s rather small and simple and hopefully will give you some ideas on how to improve your own use of the DAO pattern.




§Commentary