Should repositories have update/save/delete methods?
Asked Answered
C

1

7

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.

Charla answered 8/2, 2018 at 10:4 Comment(1)
Repository pattern is also (and probably mainly) related to persistence. You can get inspired by looking at how Spring Data JPA implemented that.Hounding
E
8

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.

Elsewhere answered 15/3, 2018 at 11:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.