Created
January 17, 2020 09:27
-
-
Save igorwojda/c9db756ef861b430d21a74903b597e32 to your computer and use it in GitHub Desktop.
Evolution of the class property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// EVOLUTION OF CLASS PROPERTY | |
// The presented code is in Kotlin, but the problem itself is not language-specific | |
// Client usage | |
fun main() { | |
Evolution1().setName("Igor") | |
Evolution2().name = "Igor" | |
Evolution3().name = "Igor" | |
Evolution4().name = "Igor" | |
} | |
// Internal implementations of "name" property | |
// Before setters | |
class Evolution1 { | |
private var name: String = "" | |
fun setName(name: String) { | |
val changed = this.name != name | |
this.name = name | |
if(changed) { | |
notifyValueChanged() | |
} | |
} | |
private fun notifyValueChanged() { | |
Timber.d("value changed $name") | |
} | |
} | |
// Utilising setters | |
class Evolution2 { | |
var name: String = "" | |
set(value) { | |
field = value | |
Timber.d("value changed $value") | |
} | |
} | |
// Utilizing Kotlin builtin observable delegate | |
class Evolution3 { | |
var name by Delegates.observable("") { _, _, new -> | |
Timber.d("value changed $new") | |
} | |
} | |
// Utilizing custom observe delegate | |
class Evolution4 { | |
var name by observer("") { | |
Timber.d("value changed $it") | |
} | |
} | |
// Generic helper delegate | |
private inline fun <T> observer( | |
initialValue: T, | |
crossinline onChange: (newValue: T) -> Unit | |
): | |
ReadWriteProperty<Any?, T> = | |
object : ObservableProperty<T>(initialValue) { | |
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = | |
onChange(newValue) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment