I'm struggling with how I might avoid using instanceof() in some of my code. This contrived example somewhat captures the problem.
Class Meat extends Food;
Class Plant extends Food;
Class Animal;
Class Herbivore extends Animal
{
void eat( Plant food);
}
Class Carnivore extends Animal
{
void eat( Meat food);
}
Class Omnivore extends Animal
{
void eat(Food food);
}
Class Zoo
{
List<Animals> animals;
void receiveFood( Food food)
{
// only feed Plants to Herbivores and Meat to Carnivores
// feed either to Omnivores
}
}
Herbivores are only interested in Plants, Carnivores only in Meat and Omnivores both. When the Zoo receives Food it only makes sense to try to feed food to animals that eat that type of food.
I've thought of a few solutions, but all seem to depend on the use of instanceof()
somewhere and my various refactorings just seem to move it around.
(1) I could implement eat( Food food)
in Animal and each subclass could choose to ignore food that it doesn't eat, but that is inefficient and would require that each Animal subclass use instanceof()
to test the type of food.
(2) I could keep three collections of animals in the Zoo based on the type of food they eat, but would still have to use instanceOf()
to test the type of food to see which collection to feed it to. At least this would be more efficient as I wouldn't be feeding food to Animals that won't eat it.
I've thought of some other approaches, but again, they just seem to pass the instanceof()
buck.
Any suggestions? Or would this (2, at least) be an acceptable use of instanceof()
?