Boris
Posted on September 25, 2022
We are 80% reading the code and 20% writing the code. That's why we should take care about cognitive load which our code reproduce. One way is to write intuitive and readable code.
A very useful Kotlin feature are Extensions functions. Let's see what extensions are and how to use it in your code to make it more readable.
"Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class."
If we want to check if some money amount is valid for transaction we can create simple check function that return a Boolean like this
fun isValidAmount(amount: BigDecimal) = amount > ZERO && amount < PAYMENT_MAX_AMOUNT
or we should disable / enable some view from the screen
fun hide(amountView: View) {
amountView.visibility = View.GONE
}
fun show(amountView: View) {
amountView.visibility = View.VISIBLE
}
These two functions are absolutely correct but we can go even further with Kotlin extensions in order to make code a bit more intuitive and readable. Now let's see how these two functions will look like
fun BigDecimal.isValidAmount() = this in ZERO..PAYMENT_MAX_AMOUNT
//and applied in code
val amount = BigDecimal(1000)
if(amount.isValidAmount()) {
// make a payment
} else {
//show message to the user
}
and hiding the view function will look like this
// Hides the view
fun View.hide() {
visibility = View.GONE
}
// Shows the view
fun View.show() {
visibility = View.VISIBLE
}
// Hides or show the view based on the flag
fun shouldShow(show: Boolean) {
if(show) visibility.VISIBLE else visibility.GONE
}
// when applied
if(amount.isValidAmount()) {
amountView.show()
} else {
amountView.hide()
}
// or even further with one liner
amountView.shouldShow(amount.isValidAmount())
You can see how this improves readability in our code.
Under the hood there is nothing special. If we decompile the Kotlin bytecode into Java source file we can see nothing but regular methods with passed arguments.
So there is no performance benefit, it's just a pure Kotlin synthetic sugar!
You can play with them and use it everywhere inside the app where you think that is necessary to improve readability. They are excellent for Utility classes where you need a lot of checks and validations.
Posted on September 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.