After reading several articles, I am starting to understand the difference between DAO and Repositories, but I find myself in trouble trying to understand the difference between Repositories and Services.
For putting in short terms, in the OO paradigm:
DAO : Class that contains the basic CRUD operations
for one entity class. It has the necessary code to get or retrieve things of the underlying persistent storage system. Generally speaking, the methods receive object entities as parameters, except in the retrieve
method where using a type of the Identifier is valid.
Repositories : In a higher level of abstraction.. as generally I have read is a kind of place where put code that handle operations over aggregate objects (objects that have child objects). It uses the DAO
s to retrieve objects from the database, and in the end it exposes an interface in the domain "business" language. (But again, I think it is very valid to use data types of ids). Example : A very simple addSomething
where something
is a child object of the parent whose instances, btw, are managed as a whole by the Repository.
Services : Again, it is in a higher level of abstraction. To my humble point of view they are a good place to connect two classes that do not share parent-child relation, but is as far (in abstraction terms) as Repository. Example : The method transferCash
between two bank accounts
.
So, that's are my readings about, but I am asking here the above thoughts are right or not. Or how I should think. Or something that points me to really understand the difference of all this concepts.
Some of the sources :
Repositories are - like you say - an abstraction. They originate from Martin Fowler's Object Query Pattern. Both Repositories and DTOs can simplify database persistence by mapping persisted data to equivalent collection of entity objects. However, Repositories are more coarse-grained than DAOs by providing control of an entire Aggregate Root (AG) often hiding a lot of internal state from the client. DAO's on the other hand can be as fine-grained as being dedicated to a single entity object. For both Repositories and DAOs it is common to use Hibernate or other Object/Relational Mapping (ORM) Frameworks instead of writing your own implementation.
Typically, services can reside in a Service Layer and can act both as a functionality facade, anti-corruption layer and coordinator for caching & transaction. They are often a good place to conduct logging. Services coarse-grained and usecase-oriented, e.g. Service.updateCustomerAdress()
or Service.sendOrder()
. Repositories can be too fine-grained for clients to consume, e.g. Customer.add(…)
, Order.modify(…)
.
Repositories and DAOs have the same purpose - to persist data permanently. Services on the other hand should be ignorant of persistence and have no knowledge about your database. They usually work tightly together with domain services, repositories, domain core.