Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving domain entities changes

here's real example that will lead to my question: I have an AddCommentToArticleCommand, which has an ArticleId, comment text and email address. This command:

  • uses the article repository to get the article (which is the domain entity)
  • if article exists, it calls article.AddComment(commentText, emailAddress), which adds the comment to the article and throws exception when it can't (due to invalid email format, article was closed, comment not filled in or too long etc...)
  • but now I don't know what the best way is to save the added comment?

Should I do something like articleRepository.Save(article)? But then, why should I save the article if only a comment was added? Or can I do something like articleRepository.SaveComment(comment), that will only save the comment? Or what approach would you take here?

Thanks!

like image 361
L-Four Avatar asked Sep 21 '11 07:09

L-Four


1 Answers

As MattDavey points out, in DDD you usually think about Aggregate life cycle, not about CRUD persistence issues. The middle and end of life of the Aggregate is handled by a corresponding Repository. Regarding your specific question:

but now I don't know what the best way is to save the added comment?

The best way to handle this is to find a reliable ORM and implement your

articles.MakePersistent(article)

repository method using this ORM. Good ORM will implement UnitOfWork, will include dirty tracking, lazy loading and other persistence related issues without constraining your domain objects. ORM knows how to avoid not needed SQL INSERT/UPDATEs when saving the Aggregate. Your domain objects should be as persistent ignorant as possible. The only constraint that NHibernate, for example, puts on your objects is that they should have private default constructor. Other than that they can be simple POCO objects unaware of all the persistence issues. Just to clear, domain objects should not have IsTransient or IsDirty flags. And if you find yourself writing code that uses these flags you are reinveting the wheel.

like image 120
Dmitry Avatar answered Sep 20 '22 13:09

Dmitry