Which is better Java programming practice: stacking enums and enum constructors, or subclassing?
Posted
by Arvanem
on Stack Overflow
See other posts from Stack Overflow
or by Arvanem
Published on 2010-04-21T07:28:02Z
Indexed on
2010/04/21
8:03 UTC
Read the original article
Hit count: 248
Hi folks,
Given a finite number of items which differ in kind, is it better to represent them with stacked enums and enum constructors, or to subclass them? Or is there a better approach altogether?
To give you some context, in my small RPG program (which ironically is supposed to be simple), a character has different kinds of items in his or her inventory. Items differ based on their type and use and effect.
For example, one item of inventory is a spell scroll called Gremlin that adjusts the Utility attribute. Another item might be a sword called Mort that is used in combat and inflicts damage.
In my RPG code, I now have tried two ways of representing inventory items. One way was subclassing (for example, InventoryItem -> Spell -> AdjustingAttributes; InventoryItem -> Weapon -> Sword) and instantiating each subclass when needed, and assigning values such as names like Gremlin and Mort.
The other way was by stacking enums and enum constructors. For example, I created enums for itemCategory and itemSpellTypes and itemWeaponTypes, and the InventoryItem enum was like this:
public enum InventoryItem {
GREMLIN(itemType.SPELL, itemSpellTypes.ATTRIBUTE, Attribute.UTILITY),
MORT(itemType.WEAPON, itemWeaponTypes.SWORD, 30);
InventoryItem(itemType typeOfItem, itemSpellTypes spellType, Attribute attAdjusted) {
// snip, enum logic here
}
InventoryItem(itemType typeOfItem, itemWeaponTypes weaponType, int dmg) {
// snip, enum logic here
}
// and so on, for all the permutations of items.
}
Is there a better Java programming practice than these two approaches? Or if these are the only ways, which of the two is better? Thanks in advance for your suggestions.
© Stack Overflow or respective owner