Hi folks, not really a kotlin specifc question but...
# codereview
g
Hi folks, not really a kotlin specifc question but i would like if possible some input on this.
Copy code
class Service1

class Service2(val service1: Service1)

class Service3(private val service2: Service2) {
    val service1 = service2.service1
}
In this example do i break DI(dependency-injection), if so why? Thanks in advance for any help!
r
With dependency inversion, one of the principles is that you depend on abstractions instead of implementation details. In that way, any implementation is free to change, as long as its contract (the abstraction) remains the same. In your example, the fact that Service2 depends on having an instance of Service1 can (should?) be seen as an implementation detail. Because, if in the future we decide to refactor Service2 to use Service8 instead of Service1 to achieve the same result, we should be free to do so, as long as the 'contract'/abstraction stays the same. In Service3 you now rely on this implementation detail, creating a dependency to the implementation of Service2 instead of the abstraction, making these services more tightly coupled than they should be.
g
So im breaking dependency-inversion. Cool thanks for the help 🙂
k
Unless you want to regard service1 as part of the abstraction of Service2.
r
true, but in which case would you want that? Typically in OOP you depend on other objects because they define some behaviour that you need. Having a dependency on something is not a "behaviour" in that sense. So yes, if you cannot directly access Service1 from Service3, 'injecting' it via Service2 would work, but feels a lot like a hack...