Why use service layer?

joe martinez picture joe martinez · Sep 11, 2010 · Viewed 31.6k times · Source

I looked at the example on http://solitarygeek.com/java/developing-a-simple-java-application-with-spring/comment-page-1#comment-1639

I'm trying to figure out why the service layer is needed in the first place in the example he provides. If you took it out, then in your client, you could just do:

UserDao userDao = new UserDaoImpl();
Iterator users = userDao.getUsers();
while (…) {
…
}

It seems like the service layer is simply a wrapper around the DAO. Can someone give me a case where things could get messy if the service layer were removed? I just don’t see the point in having the service layer to begin with.

Answer

Nathan Hughes picture Nathan Hughes · Sep 11, 2010

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.