samedi 18 août 2018

Is using instanceof to check for a specific subclass a good design practice?

So I have a base class Item. There are two classes which extend from Item; Weapon and Armour. Although Weapon and Armour share some attributes from Item, such as name and rarity, they also each have attributes specific to them, for example damage for Weapon and defense for Armour.

I wanted to have all Item objects in the same list, so I upcasted all Weapon and Armour objects to Item objects, then added them to the list. To access the Weapon or Armour-specific attributes, I would simply check whether the Item object was an instance of Weapon or Armour and downcast accordingly.

So my question is:
Is this a good design practice?
If not, can you recommend better ones to solve my problem?
I wasn't able to find any info online about it since I figured it out myself and have no idea what it's called.

Aucun commentaire:

Enregistrer un commentaire