3
\$\begingroup\$

When onSaveInstanceState() is customized it should always call the same method on the super instance first.

I usually write:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveState(outState);
}

private void saveState(Bundle outState) {
    outState.putParcelable("item1", item1);
    outState.putParcelable("item2", item2);
    // ...
    outState.putParcelable("item10", item10);
}

instead of putting all code in the onSaveInstanceState() method, in order not to accidentally skip call of super.onSaveInstanceState() (it is very hard to notice in a large project).

Is it a bad habit?

\$\endgroup\$
0

2 Answers 2

5
\$\begingroup\$

I think it is a very good practice.

As a side note, if you want to design a method like those, I'd suggest you to make the API method final and let the custom behaviors to be injected with the strategy design pattern (if you want to use composition, which is what I like the most) or with the implementation of an abstract method (if you want to use inheritance).

In that way it won't be possible to skip, even on purpose, the call to the superclass method.

\$\endgroup\$
3
\$\begingroup\$

Not at all. Sounds like an excellent practice to me.

And in similar methods that we typically override and call the super method before or after the real action, such as onCreate, onResume, I think it's good to split into two, to make the distinction explicit, and easy to see, loud and clear.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.