views:

39

answers:

2

This is a followup to the question I asked here:

http://stackoverflow.com/questions/3445398/class-hierarchy-data-design-in-an-rpg-game-vb-net

I understand the answer in the post above, which is absolutely amazing, by the way. It's about implementing interfaces with a class. However, what if a class needs to share features with another class?

Yes, that class can an Interface. However, let's use this sample definition.

An ITEM can be USED or EQUIPPED
An EQUIPPED ITEM can be either ARMOR or a WEAPON
A USED ITEM either heals the team, casts MAGIC, or damage the opposing team.
Certain EQUIPPED ITEMS can function as a USED ITEM.
Certain EQUIPPED ITEMS can cast magic.

Or, in other words:
An equippable item can perform acts outside of its typical usage of a shield or weapon. But not all items can act as a sheid or weapon.

I mean, I could create a class that implements IWeapon, IShield, IMagic, IUseableItem, etc. But there should be a better way than returning NULL when those interfaces are called.

+1  A: 

But there should be a better way than returning NULL when those interfaces are called.

It's called "not implementing them on objects that don't support them". Or so I would have thought.

One option is to have IEquippable, and IUsable, and any item that can be both equipped and used implements both, while other items only implement the applicable interface.

Anon.
But wouldn't I have to have three classes then? One class that implements/inherits IEquippable, one that implements/inherits IUsable, and one that inherits both to implement both? Or let's say a class uses Magic, Equippable, and Useable?
Jeffrey Kern
@Jeffrey: Yes, you will need to use different classes for different classes of objects. That's roughly the idea of an object-oriented design. If you were going to lump everything into one "Item" class, there would be no point in defining those interfaces in the first place.
Anon.
@Anon. Ok, thank you. :)
Jeffrey Kern
A: 

To be honest, I would choose to use a single Item class here. You're going to have lots of permutations of functionality and are going to end up having to query manually for interface existence or the object type anyway. So trying to fix the permutations at design-time seems like the wrong thing to do.

Kylotan
What I considered doing was having a single base object that would return values TRUE if a subobject was instantiated and false if it wasn't....
Jeffrey Kern
If you have to check every single piece of functionality before you attempt to use it the code is going to get ugly pretty quickly. It would be better to have a system that allows you to attempt to use the functionality with safe error handling if the functionality isn't available.
Kylotan