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 inherit from Item
, for example ContainerItem
, DurableItem
or WeaponItem
.
Obviously it is very conveniant for me to just have List<Item>
. But when I get the players items, the only way for me to distinguish between what type of item is by using the instanceof
keyword. I'm sure I've read that reliaing on it is bad practice.
Is it ok to use it in this case? Or should I rethink all of my structure?
Let's say I am writing some inventory code:
That will compile and work just fine. But it misses out on a key idea of object oriented design: You can define parent classes to do general useful things, and have child classes fill in specific, important details.
Alternate approach to above:
Now we have one place to look, the
show()
method, in all our child classes for inventory display logic. How do we access it? Easy!We are keeping all the item-specific logic inside specific Item subclasses. This makes your codebase easier to maintain and extend. It reduces the cognitive strain of the long for-each loop in the first code sample. And it readies
show()
to be reusable in places you haven't even designed yet.