17.4 Dependency injection
Although I try not to add much complexity to the code regarding architectures, clean testable code
or good practices, I thought it’d be a good idea to show another way to simplify our code using
Kotlin. If you want to know a little more about topics like dependency inversion or injection, you
17 Creating an SQLiteOpenHelper
69
can check my set of articles about
dependency injection in Android using Dagger²¹
. The first article
covers a simple explanation about these terms.
In a simple way, if we want to have classes that are independent of other classes, way more testable,
and write code that is easy to extend and maintain, we need to make use of dependency inversion.
Instead of instantiating the collaborators inside the class, we provide them (usually via constructor)
and instantiate them somewhere else. That way, we can substitute them by other objects that, for
instance, implement the same interface, or make use of mocks in tests.
But now those dependencies must be provided from somewhere, so the dependency injection
consists of providing the collaborators required by the classes. This is usually done by using a
dependency injector.
Dagger²²
is probably the most popular dependency injector in Android. It is,
of course, a very good alternative when we need some complexity to provide those dependencies.
But a simpler alternative is to make use of the default values in a constructor. We can provide the
dependency by assigning a default value to the constructor parameters, and then provide a different
instance if we need it in other situations. For example, in our
ForecastDbHelper
we can provide the
context in a smarter way:
1
class ForecastDbHelper(ctx: Context = App.instance) :
2
ManagedSQLiteOpenHelper(ctx, ForecastDbHelper.DB_NAME, null,
3
ForecastDbHelper.DB_VERSION) {
4
...
5
}
Now we have two ways to create this class:
1
val dbHelper1 = ForecastDbHelper()
// It will use App.instance
2
val dbHelper2 = ForecastDbHelper(mockedContext) // For tests, for example
I’ll be using this mechanism here and there, so I didn’t want to continue without explaining the
reason. We already have the tables, so it’s time to start adding and requesting data from them. But
before that, I want to talk about collections and functional operations. Don’t forget checking the
repository to find latest changes.
²¹
http://antonioleiva.com/dependency-injection-android-dagger-part-1/
²²
http://square.github.io/dagger/
Do'stlaringiz bilan baham: |