I am reading this article on EJB 3.0, where the author describes an architecture where the service layer talks to the Entities through a DAO implemented as a stateless session bean.
I am trying to understand why do we need this additional layer.Why can the service layer not talk directly to the entities ? One thought that comes to my mind is – ease of testability. We can test the service layer easily by mocking the DAO’s.
Is this the only reason, or are there other reasons as well ?
DAO is an abstraction over how to access database using objects. In the original practice of DAO, first there comes an interface defining the operations that you expect from your database:
Which can be generic or in any way that suits your design. Apart from the high degree of testability of interfaces, DAO pattern adds another advantage that now you can have different technologies implementing the same DAO pattern. Through time, you may need to switch from EJB to Spring JDBC or any other changes.
While all this happens, the service layer still and only sees the data layer through DAO interface. The implementation is always encapsulated from service layer. Additionally, it also increases the testability of service layer through mechanisms such as mocking.
If service layer directly starts to deal with data layer, it means that service layer becomes implementation specific which reduces modularity and coupling of concerns apart from making it harder to test the service layer only for the business logic.
Last but not least, although it’s always the best to stick to the original practice, it depends on the size and intentions of your product/project to adopt the approach.