Why use service layer?

Having the service layer be a wrapper around the DAO is a common anti-pattern. In the example you give it is certainly not very useful. Using a service layer means you get several benefits:

  • you get to make a clear distinction between web type activity best done in the controller and generic business logic that is not web-related. You can test service-related business logic separately from controller logic.

  • you get to specify transaction behavior so if you have calls to multiple data access objects you can specify that they occur within the same transaction. In your example there’s an initial call to a dao followed by a loop, which could presumably contain more dao calls. Keeping those calls within one transaction means that the database does less work (it doesn’t have to create a new transaction for every call to a Dao) but more importantly it means the data retrieved is going to be more consistent.

  • you can nest services so that if one has different transactional behavior (requires its own transaction) you can enforce that.

  • you can use the postCommit interceptor to do notification stuff like sending emails, so that doesn’t junk up the controller.

Typically I have services that encompass use cases for a single type of user, each method on the service is a single action (work to be done in a single request-response cycle) that that user would be performing, and unlike your example there is typically more than a simple data access object call going on in there.

Leave a Comment