Is it good way to inject common class with dependency injection?

681 views Asked by At

I inject viewModels,repositories,fragments,Utils and ... but Is it good way to inject common class with dependency injection Koin or Dagger-hilt?

Suppose that we want to use StringBuilder() class in fragment

First approach :

We can inject it

val otherModule= module {
   single { StringBuilder() }
}

And use it in fragment like this :

class Fragment : BaseFragment(){
  private val mPassword : StringBuilder by inject()
}

Second approach :

We can create new instance without injection

class Fragment : BaseFragment(){
    private var mPassword = StringBuilder()
 }

My question is the first approach is common way for us ?

2

There are 2 answers

0
Andrew On BEST ANSWER

I'd say that it depends. The main goal / concept behind Di is to fulfil the firth principle of S.O.L.I.D, or as freecodecamp.org says:

It is the fifth principle of S.O.L.I.D — the five basic principles of object-oriented programming and design by Uncle Bob — which states that a class should depend on abstraction and not upon concretions (in simple terms, hard-coded).

According to the principles, a class should concentrate on fulfilling its responsibilities and not on creating objects that it requires to fulfill those responsibilities. And that’s where dependency injection comes into play: it provides the class with the required objects.

Another good answer is provided here, as it is already discussed when not to use dependency injection.

And now my opinion: If possible, try to inject those dependencies that you have to use quite often and if possible, inject them via constructor injection. With this, you can easily see, which dependencies are used by your class. Try not to inject classes that are used once or common language classes.

0
zOqvxf On

No, you wouldn't inject common language classes at all. There's no benefit to it. We inject classes when they need additional dependencies that we don't want to be creating ourselves, so we let the DI framework create them.