Reputation: 33
I am trying to understand the Single-Responsibility Principle (SRP). It says a class should have only one responsibility and reason to change. This is a typical Repository below. Does that mean, each item should be its own class? Currently Insert, Delete, Search, are all in 1 class? If that's the case, why don't people separate all the items into multiple classes?
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext _dbContext;
public BaseRepository(DbContext dbContext)
{
_dbContext = dbContext;
}
public void Insert(TEntity entity)
{
_dbContext.Set<TEntity>().Add(entity);
_dbContext.SaveChanges();
}
public void Delete(TEntity entity)
{
_dbContext.Set<TEntity>().Remove(entity);
_dbContext.SaveChanges();
}
public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate)
{
return _dbContext.Set<TEntity>().Where(predicate);
}
public IQueryable<TEntity> GetAll()
{
return _dbContext.Set<TEntity>();
}
public TEntity GetById(int id)
{
return _dbContext.Set<TEntity>().Find(id);
}
}
Upvotes: 1
Views: 509
Reputation: 33
"I would rephrase what you said about SRP into being. A class should have only ONE reason to change. The responsibility of the Repository class would be to execute operations against a database (CRUD operations for example). Many people get confused thinking that a class should only contain one method, but that's not what Robert Martin describes...There are plenty of ways, if its just the 4 crud methods, leave them in one and that's fine. if you have update/insert/delete and many (5+) read operations, consider splitting that into a read and write repository. If you have a lot more read/write operations, consider applying CQRS with Command Handlers for each writing (insert, update, delete, bulk delete etc) operation and Query handlers for each read operation –"
Upvotes: 2
Reputation: 5801
question: what are the responsibilities of this repository class?
answer : to execute operations against a database (CRUD)
further reading: http://pragmaticcraftsman.com/2006/07/single-responsibility-principle
Upvotes: 1