DTO can be considered as Business objects (with behavior)

design-patternsdomain-modelspringspring-mvc

Based on this Question and its answer :

Object in Business layer same as DTO with logic?

I want to ask :

What if instead of DAL, I'm getting data from a remote service (API) through DTOs. My DTOs here represent prettymuch the business objects with all the relationships in between. Although there is BOs in the API that I'm calling I cannot put the behavior that I need there as it is specific for me. How can I deal with this ?

if no behavior on DTO so what ? This look crappy

(API) <–DTO–> (mappingService) <–Domain object–> (domainService) <–DTO–> (UI) ??

Best Answer

There are several architectural patterns for your choice:

  • The DTO is a distribution pattern and aims to transfer data between processes and remote services. The goal is to reduce the number of interprocess function/method calls that are inefficient when crossing the boundaries of a single process.
  • The domain model object leaves transfer and persistance to a data gateway or a mapper.
  • The active record is a mix between both. It aims at encapsulating data access together with domain logic.

Basically, combining your DTO with domain logic looks pretty much like an active record. It's a viable solution if your domain model is simple and if the domain object is very close to the DTO.

However, be aware of its major drawbacks :

  • you no longer benefit from the decoupling offered by the DTO. A DTO isolates your internal domain model, from the back-end implementation, and let each of it evolve at its own pace.
  • it's not really aligned with the clean design principle of single responsibility

And attention: use it only if the domain model is simple. It's not a good idea if one object is simple but the whole model would be rather complex, because active records raise a lot of issues if you'd need to combine it with unit of work, an identity map or other patterns of enterprise application architecture.

Related Topic