I want to implement Repository design pattern for my project but it's not clear to use CRUD operations in repositories or not. Some resources say you shouldn't use update/save/delete methods because the repository is only for saving objects in memory and you should services for other actions.
Which one is the best way?
Thanks.
Persistence-oriented repositories are aware that an object needs to be explicitly “saved” after any changes, so you can call the entity. save() method when an object is created or modified.
The repository would contain all CRUD operations to be performed on the database, accepting and returning business layer entities. This means that the repository will reside in the business layer, because only the business layer can reference the data layer, not the other way round.
In most cases, it suffices to have a single entity-DTO conversion, which tends to happen in the business layer (BLL), which is one layer above the repository layer (DAL). In that sense, your repositories should not return a DTO.
The Repository pattern makes it easier to test your application logic. The Repository pattern allows you to easily test your application with unit tests. Remember that unit tests only test your code, not infrastructure, so the repository abstractions make it easier to achieve that goal.
A summary of Martin Fowler’s definition of the Repository pattern:
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
So if we have both add
and update
methods, I could claim it’s not a collection-like interface, right? I shouldn’t need to bother checking if an object’s already there when adding to a set-like collection.
There are two common approaches about add
/update
:
Collection-oriented repositories try to mimic an in-memory collection, so you shouldn’t need to re-add an object if it was updated and already in the collection. The repository (or layers hidden below it, such as an ORM) should handle the changes to an entity and track them. You just add
an object when you first create it and then no more methods are needed after the entity is changed.
Persistence-oriented repositories are aware that an object needs to be explicitly “saved”
after any changes, so you can call the entity.save()
method when an object is created or modified.
(Those are my interpretations of the definitions by Vaughn Vernon in Implementing Domain-Driven Design.)
delete
is fine, but perhaps remove
would be a better name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With