Item - Inventory -relationship, which one should know the other one?

Coding an inventory that can contain 6 items would probably look something like this:

class Inventory {
    private:
        Item[6] m_items;
};

Now on the other hand an item would look like this:

class Item {
    private:
        Inventory* m_parent;
};

However, obviously both classes cannot know each other. One solution would be a common base class, but the two classes don't have anything in common and it would lead into more problems, such as: I wouldn't be able to call m_parent->addItem(this); from Item's constructor.

Answers


An item is logically complete in and of itself. Items would be worth modelling in a system that didn't have a concept of inventory at all. An item may not even be in an inventory. It may even theoretically be in more than one inventory, depending on what kinds of items and inventories you're modelling.

An inventory, on the other hand, exists solely for the purpose of containing items. It may not have any items in it at the moment, but that in itself is a core property of the inventory.

The above considerations lead me to conclude that an inventory should know the concept of items and about the particular items it holds. While items should be implemented to be completely oblivious not just to which inventory(ies) they are in, but to the concept of inventories.


Need Your Help

link an old app user to a facebook account using parse always fail

swift parse.com iso

I am trying to link an existing account in my app to a facebook account, but the parameter succeed in the parse API always return false (no error) I am able to use the API to create a new user, pos...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.