How should I implement items that are normalized in the database in object oriented classes? In the database I have a table of items and Groups. Each item belongs to one group:
+----------------------------------------+
| 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. Group information like VAT is needed for calculations.
I will write an Item class, but do I need a Group class? If so, should I keep them in a global location or how do I access them when I need it for item calculations? Is there any design pattern for this case?
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
Groupclass that has a collection ofItems, and (ideally) a reference fromItemto its parentGroup. 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.