I am running a zoo application.
My zoo includes an abstract class of ‘animal’, and several deriving classes – ‘zebra’, ‘elephant’, ‘orangutan’, ‘baboon’ and so on. Of each class I have several instances.
My question is: I want to check out if two animal instances can mate.
The business logic is divided to two parts:
- I want to check if each mating partner is fit for mating, e.g. not too young or too old or sick etc.
- I want to check if the two partners match – e.g. a zebra cannot mate an elephant, but an orangutan can mate with a baboon.
I assume the first requirement would be implemented by an abstract function which would reside under the animal baseclass. But what about the second requirement?
How would you design the classes in the most general matter that adding new types of animals would not require much of an overhead?
13
According to Uncle Bob in Clean Code this is a typical example of when to write more procedural code and less object oriented. You want the flexibility to add “data structures”, so you need to put the logic elsewhere.
Data/Object Anti-Symmetry
- Procedural code (code using data structures) makes it easy to add new functions without changing the existing data structures.
- OO code makes it easy to add new classes without changing existing functions.
- Procedural code makes it hard to add new data structures because all the functions must change.
- OO code makes it hard to add new functions because all the classes must change.
That’s why Michael instinctively advised to have a function determine if 2 animals can mate.
Depends on the actual requirements… What do you mean with ‘not require much of an overhead’?
Do you want to be able to add animals dynamically, at runtime (in a plugin)?
Add an abstract method to Animal:
bool acceptsMate(Animal);
When checking for possible mates, if one them accepts the other as mate, they can go at it.
Added a new animal in a plugin library means implementing this method, and the other existing animals need not know of this new species to mate with them.
If you do not have this requirement, I would use a lookup table, where pairs of compatible animals are listed.
If this is a school question, I guess they are hinting at the visitor pattern, which imho is a bad fit for this problem. You would need to duplicate code for each match, because there are 2 ways to query if they can mate.
AnimalA->visitCanMateWith(AnimalB)
or
AnimalB->visitCanMateWith(AnimalA)
1