Repository pattern vs. “smart” business objects [closed]

元气小坏坏 提交于 2019-12-02 14:06:22

I use the repository pattern because of the Single Responsibility Principle. I don't want each individual object to have to know how to save, update, delete itself, when this can be handled by one single generic repository

The repository pattern doesn't necessary lead to dumb objects. If the objects have no logic outside Save/Update, you're probably doing too much outside the object.

Idealy, you should never use properties to get data from your object, compute things, and put data back in the object. This is a break of encapsulation.

So the objects should not be anemic except if you use simple DTO objects with CRUD operations.

Then separating the persistence concerns from your object concerns is a good way to have Single Responsibility.

ashraf

Here are two interesting articles I came across

Repository-is-the-new-singleton

The DAL should go all the way to UI

I think the most important side-effect of using the Repository pattern vs. the ActiveRecord pattern is testing and extensibility.

Without having your ActiveRecord object contain a repository itself how would you isolate data retrieval in your test cases? You can't really fake or mock it easily.

Besides testing it would also be much more difficult to swap out data access technologies, for example from Linq-to-SQL to NHibernate or EntityFramework (though this doesn't happen often admittedly).

It really depends on the needs of the application, but when dealing with a complex business model, I prefer ActiveRecord. I can encapsulate (and test) the business logic all in one place.

Most ORM's (EF, nHibernate, etc...) serve as your Repository. Many people consider a layer on top of an ORM that encapsulates all data interaction as a Repository, which I believe to be incorrect. According to Martin Fowler, a Repository encapsulates data access as a collection. So having individual methods for all data retrieval/mutation might be using a Data Mapper or a Data Access Object.

Using ActiveRecord, I like to have an "Entity" base class. I typically use an ORM (repository) with this base class, so all of my entities have a GetById, AsQueryable, Save and Delete methods.

If I'm using more of a Service Oriented Architecture, I'll use a repository (one that masks direct data access or an ORM) and call it directly in my services.

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