tags:

views:

132

answers:

4

I have two table with parent child relationship and still confuse how to map it into class from tables. Simple class which encapsulate methods and not using Business Object / Value Object. The tables are category and product.

When a webform list product from a category, what approach I should do?

Create Category object and call GetProductsByGroup(int groupId)

or

create Product object and call GetProductsByGroup(int groupId)

Which class should own the method?

+2  A: 

What's the primary relationship of the method - Products. Thus I'd put it inside the Products class, since it'll handle everything related to products. Likewise the Category class may have a multitude of methods for handling, querying & modifying categories.

Mark S. Rasmussen
A: 

It's pretty much up to you, but I'd make the following distinction:

If the method is on the Product class, make it a static method.

If the method is on the Category class, don't make it static.

If it's something you're going to access frequently, you may consider making it a property on your Category object that lazy-loads the Products for that category. I.e. the first time you access the property it retrieves the Products from the database and stores them on your Category object; subsequent calls then just return that list without having to visit the database again.

teedyay
A: 

short answer: neither. You need a collection class instead.

in general, a class will represent one row in a table, and a collection will represent the table or a subset thereof.

if you don't want to use business or data-layer objects (which would be appropriate, by the way), then either class can own the method in practice, but as a static method. It might make slightly more sense for the production class to own it, though, since it should return a collection of products

Steven A. Lowe
+3  A: 

None of them.

Why?

Category: A category makes sense on its own, it shouldn't have to know any product exist.

Product: A product has a category, but has no knowledge about the other products in that same category.

Where then?

In a service which offers methods to retrieve products (could be called a product repository) depending on specifications.

Example:

public static class ProductRepository
{
    public static Collection<Product> GetProductsByGroup(int groupID)
    {
         ...
    }
}
GoodEnough