ormdomain-driven-designmemento

Domain Model Snapshot for Mapping and Reconstitution using Factory


I've read in the Patterns, Principles and Practices of DDD book that if you want to fully encapsulate your domain model you can make its properties private and use the Memento pattern to read them. There was also an example that a Repository gets a Snapshot of the domain model, then maps to a database model and saves its changes to the db. Also it retrieves the database model from db, maps it to the Snapshot and then uses the Factory pattern to reconstitute the Domain model from the Snapshot and work with it.

  1. I am a bit confused about how much work is done here when you can just map the database model to the domain model, without using a factory or snapshots. Isn't this much easier?
  2. If we are going to follow the book, is it the correct way to return the Domain model snapshot from the service layer to the presentation layer and then map it to a View Model? Or to create the snapshot in the presentation layer and pass it to service layer, using the factory pattern to reconstitute it there and then pass the domain model to the repository where it will again take its snapshot to map to the database model and save to the db....

  3. Can you give some example when you need to use such complicated mapping architecture?

It really feels like you are writing complicated code when it can be done much simpler.

UPDATE

I can put code examples if it will be easier to understand what i am asking. ;)


Solution

    1. A Repository's job is just to save and rehydrate domain entities from a persistent store. Any design pattern beyond that is just technical details, usually a way to work around ORM flaws - but it is not part of Repository (i.e. DDD's fundamental means of storage) per se.

      I suppose the Memento pattern in that book is used to solve the "ORM / encapsulation conflict", i.e. an ORM needs write access to all of an entity's fields to be able to rehydrate it, which forces you to expose them and breaks encapsulation.

    2. No, the Memento or Snapshot is for persistence purposes only. Service (or Application) layer maps from the real Entities or uses precomputed read-specific models if you're under CQRS.