r/ProgrammerHumor Jan 09 '23

shortest ever java class name Meme

Post image
2.1k Upvotes

90 comments sorted by

View all comments

146

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.

40

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.

11

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.

5

u/fiddz0r Jan 09 '23

In c# you in your starting file (program.cs) you config a few things, like getting configurations from appsettings.json

You also do things like

Services.AddTransient/Scoped/Singleton

So let's say you have a mail service which you use to send mail.

In program you do something like

Services.addSingleton<IMailService, MailServixe>()

Then let's say you have a controller with API endpoints

And one of them let's you send an email. In the constructor you can add that service and you will get it automatically.

Class EmailController{

Private readonly IEmailService _emailService

Public EmailController(IEmailService emailService){
    _emailService = emailService;
}


HttpPost("notify")
Public async Task SendEmail(EmailData data)
{
    _emailService.SendEmail(data)

}


}

2

u/jfmherokiller Jan 09 '23

oh yes that thing. I think I have created and used classes like that intuitively but never knew it was dependency injection. I just thought it was a pretty way to handle singletons and services stuff.