Wednesday, June 28, 2006

DAO access in Struts Action?

In quite a few projects in the past, I have directly accessed the DAO methods from the Struts Action classes. This strategy makes a lot of sense when we are only retrieving data from the database and populating beans that would be binded to the JSP page.

But there are many who consider including any persistance code or business logic code in the Action classes as 'sacrilege'. Many prefer having a business service layer (aka business delegate) layer that encapsulates all persistance and business-logic.

But for simple CRUD operations, the service layer just becomes a thin layer around the DAO layer. But nevertheless, there are advantages of adding this business service layer.
  1. Consolidates the data access layer to all clients. Every method in the DAO need not be present in the ServiceLayer. You see only the methods that we wish to expose to the rest of the world.
  2. Serves as an attachment point for other services, such as transaction support. For e.g. using Spring.
  3. Presents a single common interface for other applications to use. For e.g. exposing the business functionality as a WebService.

Another reason this extra layer can be helpful is in a real-life scenario- For e.g. A more complex application there are often other business operations you might want to perform besides just calling you DAO. For example, maybe when an "update" is done you need to call some process that sends out an e-mail or some kind of notification. If you don't use a Service class you are stuck now between coding this business logic either in your Action class or in the DAO. Neither of those places is really a good place for that kind of logic - hence we provide an extra service class to handle business rules that shouldn't be in the Action and don't belong in a DAO. Of course for rapid development, you could possibly skip the Service classes and just use the DAOs directly within your Action.

But there is no absolute right or wrong answer. This reminds me of a quote:

"I'm always wary of absolutes. Know the rules, know the reasons behind the rules, know when and why to break the rules, proceed accordingly."