BlueCP
BlueCP

Reputation: 71

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.

Upvotes: 1

Views: 93

Answers (1)

FilipRistic
FilipRistic

Reputation: 2821

There is nothing wrong with doing that. In Java that is only approach to achieve what you are looking for. Some languages with a more sophisticated types systems might have cleaner solutions but in the end there is always some need to check what class actual instance belongs to.

EDIT:

I wrote than in a hurry, so let me give a bit more explanation on that. Frequently we are faced with situations when we have container of some general type, and in some case we need to perform some class specific action to some of those elements.

Now there are 2 possible solutions to this, first is to separate them into 2 containers and lose that abstraction level, another one is what you have used, having more abstract container but when you need to use lower level class to simply check for which type it corresponds to.

Depending on situation one of those might be better than another, if you have to use instanceof in most places where you use that container then it is a sign that you should use 2 different containers each with specific class. On the other hand if you just have to use instanceof on 1 or 2 places then you should go with that.

Upvotes: 2

Related Questions