I have the following basic entities:
public class Basket
{
public List<Product> Products {get;set;}
}
public class Product
{
public string Name {get;set;}
public decimal Price {get;set;}
}
And I want to get a list of all products in a basket that are below a fixed price. Should the logic for this go in the Basket, like so:
public class Basket
{
public List<Product> Products {get;set;}
public List<Product> CheapProducts
{
get { return Products.Where(p => p.Price < 5).ToList(); }
}
}
Or should it go in a service class, ProductFilterer, which would take the entire list of products as a parameter and would return a filtered list of products. Or maybe it should just go straight into the method of the calling class?
Or something else? What is the best practice for this?
What I would do is see with a domain expert if the notion of “cheap product” is a first class domain concept and has to be introduced in the ubiquitous language.
If this is the case, Steve’s Specification solution solves your problem in an elegant way.
If cheapness is unimportant or not as clearly defined as that (for instance if the cheapness threshold varies across the application), I wouldn’t bother creating a specific entity for it and just filter Basket.Products with the relevant criteria when needed in calling code.