I was reading on this SESE page about using a variable to indicate the object type, more specifically, an enum.
The accepted answer states:
When your weapon types enum just mirrors the class hierarchy, then this is a blatant violation of the DRY principle - you encode the same information, the type of a weapon redundantly in two places - one place is the class name itself, one place the enum. That's definitely not just a code smell, that is bad code.
As suggested in the comments of the OP, a Collection
containing specific attributes might be better. I like this approach because I could query it to find out more about the object and proceed accordingly.
For example:
public enum GameObjectAttributes{
Replenishable
Destructable
Health
LongBlade
ShortBlade
Mana
Health
Potion
Indestructible
}
Weapon:
public abstract class Weapon
{
private List<GameObjectAttributes> gOAttributes;
// imagine a constructor :D.
public final boolean containsAttribute(GameObjectAttributes attribute)
{
// determine if weapon contains a specific attribute.
}
}
Suppose I had a Sword
object, and the level of detail allows a Sword
to be damaged and broken if hit hard enough, so my Sword
object might contain Destructable
and LongBlade
as attributes.
Question:
Does my code suffer from what the answer in the link warns against, that I'm using a variable to map my class hierarchy? Although it might contain an enum
about what the object is, it also contains details that for obvious reasons one enum
won't be able to tell you, in my Sword
example, that it's Destructable
.