This text will outline easy methods to use abstraction within the fashionable world exactly within the Kotlin world.
After we conceal precise code behind abstractions like features or lessons, we not solely shield customers from these particulars, however we additionally give ourselves the liberty to vary this code later.
Fixed
Literal constants are problematic when they’re extensively used, to keep away from we should always use abstraction.
Let’s take an instance for isNameValid perform that returns true if the title has desired size.
The quantity 10 is straightforward to know however it will likely be good if we declared it as fixed like:
Now we are able to change this worth with out understanding the logic of the isNameValid perform. As you may see, extracting fixed:
- Give a correct title.
- It helps us change its significance sooner or later.
Perform
Think about that you’re growing an software and also you observed that you simply typically have to show a toast message to a consumer. That is the way you do it programmatically:
Toast.makeText(this,message,Toast.LENGTH_LONG).present()
Now we are able to create an extension perform to show this toast :
Now, this seems good however what If we modify the implementation of this perform from Toast -> SnackBar, for this we aren’t ready although.
The easy Resolution is to rename this perform from toast -> Snackbar
enjoyable Fragment.snackbar(message: String, length: Int =
...}
This answer seems good however it’s harmful whereas different modules are depending on this perform, their performance will probably be impacted particularly when the parameter additionally modifications.
As Builders, we are able to create a higher-level perform with the title showMessage that may maintain the complexity of displaying Toast or SnackBar.
Every thing is hidden within the showMessage perform, however features can’t maintain a state.
Class
Right here is how we are able to summary message show into a category:
We are able to inject context into the category and it could actually maintain the state as properly.
val message = ShowMessage(context)
message.showMessage("Check")
Interface
Hiding logic behind the category is an superior concept however we are able to conceal class behind an Interface, Which supplies extra freedom so as to add options in school.
interface IMessageInterface {
enjoyable showMessage(msg: String)
}
now we have now extra freedom, we are able to show platform-specific Dialog/Messages by offering a unique implementation.
That is it. Thanks for studying remember to clap and subscribe.
Keep tuned for one more article.
Do not forget to Clap…..