Denis' Micro Blog

Welcome! ๐Ÿ‘‹

Design | Development | General
Guides | Life | Tips

Injecting Dependencies

July 22, 2023 | Development


So the origin of this one is me, using this concept way too much than usual, and I felt like writing. ๐Ÿ˜…

While looking around on the web, I found a really funny quote from James Shore, which describes it pretty well if you think about it.

"Dependency Injection" is a 25-dollar term for a 5-cent concept. [...]
It means giving an object its instance variables.

Well, the only thing that you told me by now is that the marketing department was successful in its daily business. Tell me something new.

OKAY OKAY... Just wait for a moment. Let me explain it in a bit more detail.

Let's say we got an interface for a pen. IPen

We use that interface in all of the places where we execute our different pen operations. whatever that may be...

Generally, that's a pretty good idea since that implementation doesn't need to change just because we switched from a ballpoint pen to a pencil if we stay in our metaphor.

Now we can use dependency injection to automatically supply a concrete object from that interface to our program.

But how can we supply our implementation?

Good question. For this, we can use a so-called injector, another object which provides the concrete implementations. This can be done with things like...

In the end, they all achieve our desired goals in a more or less elegant way.ย 

Okay. Now we have this way of supplying instances dynamically and then using them in a polymorphic way. But why should we put in the effort though?

We can supply instances dynamically to a statically remaining implementation. That means we could also supply instances of test objects super easily. You don't know how satisfying this is when that works out absolutelyย smoothly.

There's also the argument of decoupling everything all together... but yeaaaah....ย ๐Ÿ˜…๐Ÿ˜‚

That isn't something for every type of project, especially smaller ones. That would increase the boilerplate for "something quick and dirty" way too much. For larger projects though that story looks a bit different.

So yeah. Paint your own picture. I think my point stays clear. ๐Ÿ˜‚

See ya.