views:

49

answers:

2

How should I implement items that are normalized in the Database, in Object Oriented classes?

In the database I have a big table of items and a smaller of groups. Each item belong to one group.

This is how my database design look like:

+----------------------------------------+
| Inventory                              |
+----+------+-------+----------+---------+
| Id | Name | Price | Quantity | GroupId |
+----+------+-------+----------+---------+
| 43 | Box  | 34.00 |     456  |     4   |
| 56 | Ball | 56.50 |       3  |     6   |
| 66 | Tin  | 23.00 |      14  |     4   |
+----+------+-------+----------+---------+
Totally 3000 lines

+----------------------+
| Groups               |
+---------+------+-----+
| GroupId | Name | VAT |
+---------+------+-----+
|     4   | Mini | 0.2 |
|     6   | Big  | 0.3 |
+---------+------+-----+
Totally 10 lines

I will use the OOP classes in a GUI, where the user can edit Items and Groups in the inventory. It should also be easy to do calculations with a bunch of items. The group information like VAT are needed for the calculations.

I will write an Item class, but do I need a Group class? and if I need it, should I keep them in a global location or how do I access it when I need it for Item-calculations? Is there any design pattern for this case?

+1  A: 

Yes, you need a Group class. It looks like it has a 1:many relationship with Inventory, where Group is the parent. Group will have a reference to a collection or set of Inventory.

duffymo
The `Group` has a 1:M relationship with `Item`, many items can be in the same group.
Jonas
Agreed - I'll correct my answer.
duffymo
+2  A: 

First of all, the most common practice is to use an ORM (object-relational mapping) tool. These are available to most any modern OO language, and they take care of generating the classes needed to interact with the database, managing retrieval and updating, and managing connection lifetime.

That aside, yes, you need a Group class that has a collection of Items, and (ideally) a reference from Item to its parent Group. This is one of the areas where an ORM can help, since it can ensure that these two references (the collection of children and the parent reference) stay in sync.

Adam Robinson
But if I keep all `Item` **in** a `Group` class, then I have to have all my `Item`s in memory? That sounds tricky, because I don't need all the 3000 items at the same time. Or maybe that is the best solution anyway.. have to think about it, thanks.
Jonas
There's no way to model this with groups without keeping all of a particular group's items in memory (or, at least, something that represents the item, if not the item itself). Don't optimize prematurely; 3000 instances is not unreasonable.
Adam Robinson
You can just keep the IDs in the list and lazy load them as needed if memory is a real issue. ORM tools have sorted this out better than you will.
duffymo