BaseActivity and BaseFragment are monsters
An old tale of composition over inheritance, sort of! One of the good practices when writing code is “Reusability”. Instead of writing the same code multiple times, we should write it once and use it wherever we need to. Simple as that!
Pretty clean, right? Well maybe now but not in a month. Specially when you introduced a ton of callbacks, implemented a lot of interfaces and added a big deal of logic! Your base activity is going to look eventually like:
If you don’t want to read this code, you’re not alone!
You see what I mean? Have fun extending this class, let alone refactoring or bug fixing it! No need to mention migrating to new technologies is going to be extra troublesome if your base activity is dependent on old tech. OK, so how can we go about fixing it?
Layout inflationIf you are only worried about layout inflation for your activities and don’t want to repeat
Setting up toolbarTo setup toolbar just use extension functions on activities and/or fragments.
And then call this from your child Activities with toolbar you want!
This way only the activities who actively want to setup a toolbar would use it! And if some activities have a particular way of setting up their toolbar, then they can use another method or just write it their own way!
Activity/Permission resultsThis shouldn’t be something that make people use base classes but if you are using a base class to handle these stuff, maybe take a look at
AnalyticsTo send tracks and do analytics stuff based on activity/fragment callbacks you can just use When to use Inheritance then?As discussed, when it comes to addressing duplications and code reusability, it seems that Inheritance isn’t the right approach. Instead we should try to use functions or compose smaller classes! We should also acknowledge that there isn’t a fine line that determines when to use what approach! TL;DRTo make your code reusable don’t try putting everything in a giant base activity or fragment (inheritance), instead introduce composition with the help of extension functions or dividing logic into different classes. Because:
TBH, I couldn’t find a use case or a good reason for using base activities or base fragments. Let me know if you know of a good one!
Android News
droidcon News
Tech Showcases, Developer Resources & Partners
EmployerBrandingHeader
jobs.droidcon.com
![]() Latest Android Jobs
Kotlin Weekly
![]() Your weekly dose of Kotlin
ProAndroidDev
![]() Android Tech Blogs, Case Studies and Step-by-Step Coding
Zalando
![]() Meet one of Berlin's top employers
Academy for App Success
![]() Google Play resources tailored for the global droidcon community |
Droidcon is a registered trademark of Mobile Seasons GmbH Copyright © 2020. All rights reserved.