Active Records vs. Repository - pros and cons?

♀尐吖头ヾ 提交于 2019-11-30 13:01:24

It really depends on how complex your domain logic is. For example if I was writing a simple blog then active record will be fine, mostly the application is saving and loading data. Its simple and active record pattern is the right tool for the job.

However if I was writing software for a shipping company in which there are many complex business rules and processes then using the repository pattern, along with other Domain Driven Design patterns will provide at much more maintainable code in the long run.

Using domain driven design you would use the specification pattern to achieve your validation.

Both approaches has their pros and cons.

Pretend, you're passing Active Record-styled object to somewhere (deep inside BL). You can read it, you can changed it, you can SAVE it. In this case, that piece of BL is only coupled with you entity's interface. With layered architecture you then have to somehow pass repository to that code. You'd either pass it explicitly or use IoC-container - up to you.

The other point is that when you have the concept of repository, you can easily define concepts like we-have-a-new-object-in-repository, or one-object-has-been-deleted-from-repository which are basically quite useful notifications if you're working with distributed environment.

This article seems like a good and succinct description of both: https://hashnode.com/post/which-design-pattern-do-you-prefer-active-record-or-repository-cilozoaa5016o6t53mhsdu6nu

One thing I would like to add is it isn't just "active record is good when your persistence needs are simple and repository is good when your persistence needs are complex". The choice of pattern here has a lot more to do with how you feel about the Law of Demeter. If you want different parts of your architecture to be completely separated so that someone can understand one part without understanding another then you want the Law of Demeter. That said I think, especially early on in a project when the spec is likely to change, it is VERY dangerous to get too obsessive about these sorts of abstraction. Don't second guess your project's future maintainers, they might be smart and they should be able to think about more than one thing at a time and if they can't then you might have larger problems that cannot be prevented by using the Repository pattern.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!