This content originally appeared on Level Up Coding - Medium and was authored by Giuseppe Giacoppo
Android Nightmares đ± | Base classes
When I started working as Android Developer there werenât Fragments, RecyclerViews, ViewModels, and Coroutines. Everything changed in these ten years, everything except one thing: Base classesđ„¶.
If you never met a BaseActivity, BaseFragment or BaseViewModel consider yourself luckyđ.
These classes are the wrong consequence of a correct principle in software development: Donât Repeat Yourself
âDonât repeat yourselfâ (DRY) is a principle of software development aimed at reducing repetition of software patterns,replacing it with abstractions or using data normalization to avoid redundancy. (Source)
A common scenario is when you need to trace analytics along your application, or maybe register a BroadcastReceiver on each activity.
It seems ok, now every Activity that extends BaseActivity will trace and logout without any new line of code.
But what if you need an Activity that automatically logs out without tracing logs? And what if you need an Activity that trace logs without an auto logout?
No, the answer is not Feature Flagsđ
Kotlin (even Java, with some additional line of codes) and Android Lifecycle components can save you from this nightmare with Delegation
Delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance. (Source)
You can implement an interface and delegate the actual code to another class. Also, thanks to Lifecycle components, we can bind our logic to lifecycle.
You only need
- Interface & Implementation for each feature (Single Responsibility principle đ)
- Your Activity/Fragment that implements the interface, delegates to Impl and attaches the lifecycle.
Final result:
Your delegates will look like these:
Have you ever used Delegation before? Tell me in the comments your worse experience with Base classes!đ
Android Nightmaresđ± | Base classes was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Giuseppe Giacoppo
Giuseppe Giacoppo | Sciencx (2022-02-20T13:20:23+00:00) Android Nightmares | Base classes. Retrieved from https://www.scien.cx/2022/02/20/android-nightmares-base-classes/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.