3) i have functions for each item at the store
...
i have hundreds of lines of code for each item function.
|
Both of these are bad signs.
You should not repeat code for different data. You should learn to separate code and data appropriately.
If you are writing code that has fixed output, this is a bad design. It's much better to store data in a separate section, and just refer to it in one block of code.
Here's a simplistic example of what it sounds like you are doing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
// example of bad code
void PrintItemA()
{
cout << "You have item A";
}
void PrintItemB()
{
cout << "You have item B";
}
void PrintItemC()
{
cout << "You have item C";
}
void Master()
{
if(PlayerItem == ItemA) PrintItemA();
if(PlayerItem == ItemB) PrintItemB();
if(PlayerItem == ItemC) PrintItemC();
}
|
This is referred to as "hard coding" and is something that should be avoided. When you write a function that only works with one thing (in this case, PrintItemA only works with ItemA), it leads to tons of duplicate code and makes it very difficult to maintain and/or change behavior later. What happens if you want to change how your Print functions work? You'd have to remember to change all 3 of them (or more, depending on how many times you dup'd it)
A better way would be to store item information elsewhere and refer to it in a general Print function. This way your Print function will work with all items, not just one of them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// example of better code
struct Item
{
string name; // "Item A", "Item B", or whatever the item is named
};
void Print(const Item& item)
{
cout << "You have " << item.name;
}
void Master()
{
Print(PlayerItem);
}
|
Not only is Print simplified, but so is the code that calls it. You don't need to figure out which item you have and call whatever function is designated for that item. You just call a single do-everything function.
Another step forward would be to objectify it more:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
// an example of even better code
class Item
{
public:
void Print()
{
cout << "You have " << name;
}
private:
string name;
};
void Master()
{
PlayerItem.Print();
}
|
Now, "Print" is associated with the item itself, which keeps it more organized. Furthermore, objectifying like this opens the door to possible inheritance designs (if you want to derive more specialized classes from Item)
EDIT:
As for your actual question. Yes, I'd think a store probably should be a class. But again, make it generic. Don't have it sell a fixed set of items. Keep the items it sells stored as variables that can be changed. That way you can create several shops, each with varying inventory and you can use the same code for all of them.