The scenario. I\'m writting game-related code. In that game a Player
(its also a class) has a list of Item
. There are other types of items that inhe
I don't necessarily think instanceof is bad for coders who know what they are doing and use it to avoid having to write more complicated code to get around it. There is a use for everything, and also a mis-use.
With that said, the description you provide does not require instanceof. There are various ways you can implement this without instanceof, and (the most important thing) the alternate solution must be better than using instanceof. Don't just go with a non-instanceof solution to avoid instanceof because you heard it is bad.
I think that for your scenario an non-instanceof solution has benefits in making the solution more easily extensible.
for (Item i: items) {
if (ItemTypes.WEAPON_ITEM.equals(i.getType)) {
processWeaponType(i);
}
}
or
for (Item i: items) {
if (WeaponItem.class.equals(i.getType)) {
processWeaponType(i);
}
}