Skip to content

Lightweight BaseFragment - boilerplate reduction #105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
IvanToplak opened this issue Oct 14, 2021 · 1 comment · Fixed by #106
Closed

Lightweight BaseFragment - boilerplate reduction #105

IvanToplak opened this issue Oct 14, 2021 · 1 comment · Fixed by #106
Assignees

Comments

@IvanToplak
Copy link
Contributor

IvanToplak commented Oct 14, 2021

I've noticed boilerplate code when overriding lifecycle methods: we have to call parent method for each override (call to super).
Some developers don't follow best practices for when to call super (i.e. is it before or after setup/cleanup code).
It's possible to enforce those rules and remove call to super from Fragments by creating BaseFragment that would:

  • extend Fragment and override lifecycle methods,
  • make overrides final so that they can't be overridden in Fragments,
  • declare setup/cleanup methods: protected open fun do[lifecycleMethodName] that we can override in Fragments,
  • call setup/cleanup methods at correct locations in overrides.

This is inspired by template method design pattern.

Correct locations of setup/cleanup method calls:

  • onCreate, onViewCreated, onStart, onResume - after call to super
  • onPause, onStop, onDestroy, onDestroyView - before call to super.

Example of that kind of method in BaseFragment:

    final override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        doOnViewCreated(view, savedInstanceState)
    }

    protected open fun doOnViewCreated(view: View, savedInstanceState: Bundle?) {}

For example when we want to override onViewCreated in a Fragment we would override doOnViewCreated instead.

Add clear warning to Kdoc of BaseFragment that it should be lightweight and it's not intended to hold methods that could be extension functions. We don't want another View superclass.

@IvanToplak IvanToplak self-assigned this Oct 14, 2021
@julianfalcionelli
Copy link
Contributor

I think what you propose is good! I am also one of those who use a BaseFragment/BaseActivity to reduce the boilerplate code.
We just need to be careful to not add too many things in the Base classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants