Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a class contain a collection of itself? [closed]

Tags:

c#

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!

like image 890
user204588 Avatar asked Nov 25 '10 18:11

user204588


People also ask

Is a class A collection of objects?

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.

Is that class is a collection of objects in Java?

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.

Is a collection of classes in C#?

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.


2 Answers

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.

like image 88
gligoran Avatar answered Sep 24 '22 06:09

gligoran


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 Products also needed to have Products (example: SubProducts), you could have an ICollection<Product> on Product as well.

like image 24
TheCloudlessSky Avatar answered Sep 21 '22 06:09

TheCloudlessSky