Do I really need a service layer?
You don't need a service layer. However it helps you to
- Decouple your components
- You can enforce specific business rules in your service layer which should be agnostic to your repository
- Let a service facade one or more repositories. Let's consider the following sample
class Service { private DatabaseBarRepo barRepo; private DatabaseFooRepo fooRepo; @Transactional public void serviceRoutine() { barRepo.doStuff(); fooRepo.doStuff(); }}
Here we let two separate repositories take part in the same transaction. This is specific for databases albeit the principles are valid for other systems as well.
The key is the transactional behavior. If you don't have a service layer, where will you demarcate transactions?
- in the presentation layer: that's not where transaction demarcation belongs, and you wouldn't be able to use declarative transaction demarcation
- in the DAO layer: you would not be able to create a customer and its contact (for example) in a single transaction, because it would use two different DAOs
Moreover, you want your UI layer as simple as possible, and the business code (which sometimes is much more complex than sinply calling a DAO method) isolated in specific components. This allows
- unit testing the UI layer by mocking the service layer
- unit testing the service layer (the business code) by mocking the DAO layer