July 22, 2023 3 minutes minutes read Admin

Injecting Dependencies

Okay.

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...

  • Plainly creating the new object "statically"
  • Using a configuration file or database which references the correct objects that you need.
  • Something like Java's reflection API.
  • Or the good ol' 5km long if-else statement.

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.