Posts

Showing posts from March, 2018

DI on Android (Kotlin) using an SPI

Image
Most developers are intimately familiar with what an API is. However, mention SPI, and many will look like a question mark. This blog entry explains what it is, discusses its merits/shortcomings and shows how it can serve as a simple Inversion of Control or Dependency Injection pattern on Android for providing testing mocks.

So what is an SPI anyway? The term SPI is an abbreviation of Service Provider Interface, and it's nothing more than a contract (interface) with pluggable implementations (classes) discovered lazily at runtime. I have also seen this pattern referred to as Service Locator and Service Registry. It likely has a older history than I am aware of (you can use it if you have introspection and reflection available in your language) but I made its acquaintance with Java 1.3 which introduced these service providers as a way of facilitating loosely coupled modules. In Java 6 the pattern was embraced further by the addition of the SericeLoader class and whenever you use an…