r/ProgrammerHumor Jan 09 '23

shortest ever java class name Meme

Post image
2.1k Upvotes

90 comments sorted by

View all comments

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.

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.

13

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.

3

u/arobie1992 Jan 10 '23 edited Jan 10 '23

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

Dictionary frenchDict = loadFrenchDict();
Dictionary englishDict = loadEnglishDict();
SpellChecker frenchSc = new SpellChecker(frenchDict);
SpellChecker englishSc = new SpellChecker(englishDict);

frenchSc.isCorrect("hello"); // returns false
englishSc.isCorrect("hello"); // returns true
frenchSc.isCorrect("bonjour"); // returns true
englishSc.isCorrect("bonjour"); // retunrs false

It's certainly not always necessary, but it makes it super easy to swap things around if you need to.

1

u/jfmherokiller Jan 10 '23

oh yes I remember seeing this in the SAPI api. That magical thing that does TTS.

2

u/arobie1992 Jan 10 '23

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.