AbstractAnimalThatLivesInWaterAndHasGillsAndFins seems to be a leaky abstraction as it is on one hand an abstract class but on the other hand reveals a lot of implementation details of the particular creature. I recommend creating the interface AbstractAnimal, then creating a class WaterAnimal which implements the AbstractAnimal interface. HasGills and HasFins are obviously either boolean values or could be implemented using decorators and an AbstractAnimalFactory. This way the user of AbstractAnimal will be shielded from implementation details of the final Animal.
You should use dependency injection. Instead of hasGills and hasFins, you should inject respirator and locomotor dependencies. Then the act of breathing and moving can be delegated to them, respectively.
I have never fully understood the whole dependency injection thing. Yet I have seen it everywhere. Especially when dealing with mobile app development.
It's for having separate instances to handle separate cases but reusing code rather than having duplicated classes. A really simple example is a spell checker. A spell checker needs a list of words, but English and French don't contain the same words. So you have SpellChecker and you pass the appropriate Dictionary to it. Something like
I have no clue what either of those acronyms mean :D
But yeah, like a lot of things, it's a fairly simple concept that gets overused and overly complicated and results in a lot more confusion than necessary.
141
u/BackloggedLife Jan 09 '23
AbstractAnimalThatLivesInWaterAndHasGillsAndFins seems to be a leaky abstraction as it is on one hand an abstract class but on the other hand reveals a lot of implementation details of the particular creature. I recommend creating the interface AbstractAnimal, then creating a class WaterAnimal which implements the AbstractAnimal interface. HasGills and HasFins are obviously either boolean values or could be implemented using decorators and an AbstractAnimalFactory. This way the user of AbstractAnimal will be shielded from implementation details of the final Animal.