Is passing specification object is overkill in Repository
I am asking this because, if we pass specification object in method like FindCustomersCreatedToday,
class CustomerRepository
{
public List<Customer> FindCustomersCreatedToday(ISpecification ISCreatedToday)
{
List<Customer> customers= Load all customers from db;
List<Customer> newList=new List<>();
foreach(var customer in customers)
{
if(ISCreatedToday.SatisfiedBy(customer)
{
newList.Add(customer);
}
}
}
}
I above implementation in most of the sites i saw that, they fetch all entities from database and loop over them and pass each of them in to specification, but i don’t like the idea of loading all entities at once and then create a new filtered list.
Suppose if i have 10000 customers and only 10 passes this criteria.
Is that not over kill to pass specification ?
Yes it is definitely an overkill if you expect a lot of customers. You can use information in the instance of your specification to generate appropriate SQL/HQL or ICreteria (assuming you use NHibernate).
This code is bit less expressive than the one you posted but it still good at capturing some domain information in Specification.
One thing to keep in mind when you work with Specification is that it is a domain concept. It belongs to domain layer and should be free of data access technologies. Technicalities of getting the data are important they just not important in domain layer, they belong to data access layer. Things like
Expression<Func<Customer, bool>>are to ‘infrastructural’ for domain code in my opinion. In addition, Linq-based specification tend to require domain objects to expose their data as properties which sometimes breaks their encapsulation. So the whole thing may turn into “Linq over Anemic Model“.I highly recommend you to read DDD book. It has a chapter dedicated to Specification pattern and all the tradeoffs that you are dealing with.