Leverage kotlin properties and become independant of the android framework
Closed this issue · 3 comments
This stuff should really encourage you to become independant of the android framework and be trivially ready for testing without any mocking non-sense
interface UserSettings {
var notificationsEnabled: Boolean
var loginCount: Int
var nickname: String
companion object
}
fun UserSettings.Companion.fromSharedPreferences(context: Context): UserSettings {
return object : UserSettings, SimpleKrate(context) {
override var notificationsEnabled by booleanPref("notifications_enabled", false)
override var loginCount by intPref("login_count", 0)
override var nickname by stringPref("nickname", "")
}
}
data class TestUserSettings(
override var notificationsEnabled: Boolean = false,
override var loginCount: Int = 0,
override var nickname: String = ""
) : UserSettings
Usage:
// application code
val settings = UserSettings.fromSharedPreferences(context)
settings.loginCount = 10
Log.d("LOGIN_COUNT", "Count: ${settings.loginCount}")
// testing code
val settings = TestUserSettings()
settings.loginCount = 10
Log.d("LOGIN_COUNT", "Count: ${settings.loginCount}")
This seems like a valid usage of the library, have you ran into an issue while doing this?
I have not used it with Krate specifically but I've used it this pattern a lot with great success in the app I am developping professionally.
There is no reason to depend on the android framework for what is simply a bag of properties.
That's the ideas of ports and adapters
. What you need to write your logic is the UserSettings interface (port), you write the adapter for SharedPreferences with Krate and you have a trivial fake implementation for your units tests.
http://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters/
That's a legitimate comment, but it's not an issue.