Having a different interact-method for each possible other animal will work when you have only three classes, but when you add mice, rabbits, tigers, rats, enchiladas, wombats, dolphins, armadillos and zebras, it will quickly get unwieldy, because whenever you add a new animal you need to edit every existing class to add a new interact-method. This is not how object-oriented programming should be. The purpose of OOP is that you can simply add a new class and all other classes can work with it immediately without requiring any modification.
For that reason you should handle the interactions in a more generalized way. Why does a cat hunt a mouse or a bird, but not a dog? What would happen when I would confront a cat with a smibblat? (A smibblat is a small, fluffy, four-legged, herbivorous mammal about 5 centimeters long which I just made up and wrote a class Smibblat: public Animal
for). Even when the cat has never seen a Smibblat before, it would try to hunt it, because it fits into its prey-pattern. Cats are a danger to all animals which are 1. smaller and 2. slower than themself.
When you would add an abstract getSize()
and an abstract getSpeed()
method to class Animal, you could have a method like this:
void Cat::interact(const Animal & other) {
if (other.getSpeed() < this.getSpeed() &&
other.getSize() < this.getSize()) {
this.eat(other);
}
}
which can be applied to any new animal you create. The Cat class would no longer have a dependency on every other Animal sub-class there is. It only depends on Animal which provides all the methods which matter for making the decision whether or not to eat the other Animal.
No comments:
Post a Comment