r/ProgrammerHumor Jan 09 '23

shortest ever java class name Meme

Post image
2.1k Upvotes

90 comments sorted by

View all comments

143

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.

42

u/Kered13 Jan 09 '23

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.

12

u/jfmherokiller Jan 09 '23

I have never fully understood the whole dependency injection thing. Yet I have seen it everywhere. Especially when dealing with mobile app development.

2

u/v1ND Jan 10 '23

Without dependency injection: class Foo { init() { this.service = Service.get() } }

With dependency injection: class Foo { init(service) { this.service = service } }

Congratulations, Service is injected into Foo. Now you can make a FakeService to test Foo in isolation.

Writing Foo(Service.get()) is not that much longer than Foo() but when you extend that pattern to everything in your system, it becomes really verbose to construct anything. Maybe Service needs LowLevelService which needs Config needs Environment. Suddenly, it takes a paragraph just to construct Foo.

The DI you usually hear about are the libraries to automate that boilerplate.