Search code examples
androidkotlindagger-2dagger

Don't Dagger broke an encapsulation principle?


On the one hand, DI (in my case it is Dagger2) is a helpful/useful tool, however, on the other hand, I just can't stop thinking that it broke the incapsulating principle and I don't know how to live with that:)

Example:

Old-school approach

class A(private val objectB: B)

So here the object B has a private access modifier, which means that anyone who is going to use object A, has no access to the object B (nor set either get)

Dagger example

class A {
    @Inject lateinit var objectB: B
}

So now everyone who is going to use object A has a direct access to B (get and set)

What am I missing here?


Solution

  • You are welcome to use your "old-school approach" with Dagger/Hilt through constructor injection.

    class A @Inject constructor(private val objectB: B)
    

    See also: