Magic of Abstraction in Kotlin
This article will define how to use abstraction in the modern world precisely in the Kotlin world.
This article will define how to use abstraction in the modern world precisely in the Kotlin world.
When we hide actual code behind abstractions like functions or classes, we not only protect users from those details, but we also give ourselves the freedom to change this code later.
Constant
Literal constants are problematic when they are widely used, to avoid we should use abstraction.
Let's take an example for isNameValid function that returns true if the name has desired length.
The number 10 is easy to understand but it will be good if we declared it as constant like:
Now we can change this value without understanding the logic of the isNameValid function. As you can see, extracting constant:
Give a proper name.
It helps us change its importance in the future.
Function
Imagine that you are developing an application and you noticed that you often need to display a toast message to a user. This is how you do it programmatically:
Toast.makeText(this,message,Toast.LENGTH_LONG).show()
Now we can create an extension function to display this toast :
Now, this looks perfect but what If we change the implementation of this function from Toast -> SnackBar, for this we are not prepared though.
The simple Solution is to rename this function from toast -> Snackbar
fun Fragment.snackbar(message: String, duration: Int =
...
}
This solution looks perfect but it is dangerous while other modules are dependent on this function, their functionality will be impacted especially when the parameter also changes.
As Developers, we can create a higher-level function with the name showMessage that can hold the complexity of displaying Toast or SnackBar.
Everything is hidden in the showMessage function, but functions can not hold a state.
Class
Here is how we can abstract message display into a class:
We can inject context into the class and it can hold the state as well.
val message = ShowMessage(context)
message.showMessage("Test")
Interface
Hiding logic behind the class is an awesome idea but we can hide class behind an Interface, Which gives more freedom to add features in class.
interface IMessageInterface {
fun showMessage(msg: String)
}
now we have more freedom, we can display platform-specific Dialog/Messages by providing a different implementation.
That's it. Thanks for reading don't forget to clap and subscribe.
Stay tuned for another article.
Get an email whenever Dev Soni publishes.
Get an email whenever Dev Soni publishes. By signing up, you will create a Medium account if you don't already have…medium.com
Don’t forget to Clap….. Amazon Fashion