Balancing separation of concerns, implementation hiding and data transfer objects

234 Views Asked by At

Implementation hiding demands us to hide the internal structure of a class from the user. Let's state for the sake of simplicity: reduce the number of getters/setters to a minimum.

Separation of concerns demands that there should be only one reason for a class to change. Thus, one must not let a class of the service layer do service layer things and save data to the data storage, for instance.

Data transfer objects (DTO) are used to transport data from the service layer to the data access layer.

In order to build a DTO, I need to, in the worst case, read all members of the service layer class. This would require a maximum number of getters, which violates implementation hiding.

Deriving classes which should be transformed to DTOs from a common Storable abstract base class with a virtual method Dto buildDto() would violate separation of concerns.

Can you recommend strategies coping with this? Or is there actually a common practice in this regard?

1

There are 1 best solutions below

1
On

there are a few things that are not quite right in your definitions:

  • DTOs are "property bags". Classes without behaviour, generally used to exchange data between different Services. You might use them to define the payload for REST endpoints in a WebAPI or the shape of your responses.
  • Implementation hiding doesn't necessarily mean reducing getters/setters. It's about abstracting the internals of a class, data and behaviour.
  • Communication between Service layer and the Data layer could be done (and it's actually adviceable) using Domain Models instead of simple POCO classes.

The last point is probably what you're looking for. Try to properly define your Domain Models: they should not be simple "property bags", otherwise you'll end up having what is generally defined "Anemic Models".

Also, if you give us more details about your general architecture, we might be able to give you better advice :)