Is it poor design to have a class containing a collection of itself like in a List<> for C#? Why is this and what is a better approach and why?
EDIT: More specifically, I have a class called Product and a method in the class called GetProducts() that returns a List collection. It good be grabbing the products from a database, flat file, or xml... not sure yet.
Thanks!
A class is a collection of objects. Each class represents a collection of objects with common attributes and a set of operations. 3. An object is a specific instance of a class.
The code for a class constitutes a description of what it means for an object to belong to a class. So yes, a class is absolutely a categorisation of objects, or a collection of objects.
A collection is a class, so you must declare an instance of the class before you can add elements to that collection. If your collection contains elements of only one data type, you can use one of the classes in the System. Collections. Generic namespace.
With the Product and GetProducts() update I think this might not be such a good thing.
I use a rule of thumb kind of a principle here that relies on the logic that is domain, not language, specific. So in your case I would ask myself: "Does my product contain other actual products?" If the answer is yes then the collection of products is a perfectly legit thing to have in the Product class. If not ask what actually contains these products. A store maybe?
There is an exception to this rule with static methods. If GetProducts() is static then the upper reasoning does not apply and is usually perfectly fine to have it in the Product class.
Personally, I'd use the repository pattern:
public class IProductRepository
{
IEnumerable<Product> GetAll();
}
Then write an implementation:
public class ProductRepository
{
public IEnumerable<Product> GetAll()
{
// Database logic or read from an xml file... etc.
}
}
Pass an IProductRepository
to the caller (using an IoC container like Ninject or Castle Windsor). Then, if necessary, you can easily mock IProductRepository
for testing with the caller.
This way you're keeping the actual model (Product
) separate from "what you can do" with products.
But, if Product
s also needed to have Products
(example: SubProducts
), you could have an ICollection<Product>
on Product
as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With