Dependency Injection vs Service Location
You are likely already using a form of dependency inversion to make your code more flexible, readable, and testable, but have you considered the pattern of inversion of control you are using and why it could matter? The two major approaches are Dependency Injection and Service Location and choosing between these two could matter more than you realize.
Dependency Injection #
In a Dependency Injection scheme, like Dagger/Hilt, you provide your dependencies to the graph and at compile time the object creation logic is generated. This step is critical because you will find out at that moment if you forgot to provide a dependency and can resolve the error. This means that at run time, you won't have an unexpected crash from failing to resolve a dependency.
Service Location #
In a Service Location scheme, like Koin*, you provide your dependencies and at run time they are put into an inversion of control container (IoC container). Then you request objects from the IoC container as needed. Due to the runtime resolution, it is not guaranteed that the object you request will exist in the container and can cause crashes at run time. Additionally, in a Service Location framework, the objects must be created and stored in the container which can lead to additional overhead if there is no mechanism to lazy load or cache instances.
Conclusion #
In my experience, the trade-offs that come with the simplicity and easy setup of Service Location seldom pay off in the long run when compared to the compile time safety of Dependency Injection. There is no feeling worse than having your app crash because you had to assume that an object was going to be there and it wasn't. Until next time, thanks!
Footnotes #
- Koin is noted as a Dependency Injection framework on their website. While it does handle object wiring and creation, it still does the location at run time if you use the
module
andget()
strategy. I'll concede it rides the line, but I leave it in juxtaposition to Hilt. - In an exciting turn of events, Koin just last month released Koin-Annotations version 1.3.0 which adds compile time safety checks which when used moves it fully into the realm of dependency injection, an exciting development!
Did you find this content helpful?
Please share this post and be sure to subscribe to the RSS feed to be notified of all future articles!
Want to go above and beyond? Help me out by sending me $1 on Ko-fi. It goes a long way in helping run this site and keeping it advertisement free. Thank you in advance!
- Previous: Dev Diary - September 2023
- Next: Baseball is a State Machine