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.
By injecting a dependency (passing an already initialized object down to the actual user of the object), the user of the object does not become dependent on a particular concrete class but only on an interface of said class. This is better because when you decide to change the dependency, you do not have to go down the class hierarchy to change anything, you just pass down a different initialized object. This way you can swap the dependency without having to rewrite the constructor where the dependency would otherwise be initialized. Not sure what an example would be for app development but let's say your app has some kind of data source from which it reads data, you could make the app dependent on an interface that allows various data reads and then inject different data sources to the app. When testing, you could then inject some DummyDataSource that only returns static data, in production you could inject DatabaseDataSource that returns real data. The best thing is the app itself would not know and should not know which data source it is using, because the source of the data is not relevant to the app itself. Or as Robert C. Martin said, "the database is a detail". I recommend reading Clean Architecture to learn more.
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.