Tugrul
Tugrul

Reputation: 1808

Service layer return object types

You know that for an API project there are many patterns to retrieve and serve data to client. Controller <-> Service <-> Dao pattern is one of the these patterns.

Is it good to return any type of object from service layer or service layer return objects must be related entity?

For example, we have User, UserService, UserDao. Should UserService return types be User or any type of object is suitable?

Having logical operations in service layer force me to use other objects as return type.

What is the best practice for that case?

Upvotes: 8

Views: 2940

Answers (2)

Lee Gunn
Lee Gunn

Reputation: 8656

I've found that I need 3 types of objects to keep things manageable (I'm still in a battle trying to come up with a decent naming strategy). It's sometimes beneficial to have:

  1. Objects returned from your data layer - These objects will be dictated by your data implementation. For example, they could change if you decide to store your data differently. Perhaps you decide to serialise an object and store it as JSON rather than storing it in a separate table, or you move from SQL to NOSQL.
  2. Objects returned from your domain layer - These are application objects and should model your domain. They shouldn't contain anything that is specific to your data implementation.
  3. Objects sent to and from you API - It's useful to have separate serialisation objects to shape your API. It means you can tweak your API without having to touch the business logic. On some projects, I have multiple versions of the API objects for v1, v2 etc.

Upvotes: 3

Praneeth Ramesh
Praneeth Ramesh

Reputation: 3564

The widely accepted practise involve the service to have all business logic in it and return the Data Transfer Object(DTO)/ Business Object like User in your case. The Service may call DAO, any other datasources to fetch the entities, and a mapper/converter util can be used to convert the entities to DTO objects.

The DTO objects returned from Service can be embedded in a ResponseEntity(In the case of Spring MVC) and returned from the controller.

This makes your application into 3 separated layers like web, service, dataaccess. This supports design principles like Separation of Concerns, Single Responsibility. This also makes your unit testing and code management easier.

Upvotes: 2

Related Questions