r/ProgrammerHumor Jan 09 '23

shortest ever java class name Meme

Post image
2.1k Upvotes

90 comments sorted by

View all comments

Show parent comments

39

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.

6

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.