HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

onSaveInstanceState() - ensuring a call to super instance

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
supercallinstanceonsaveinstancestateensuring

Problem

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?

Solution

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.

Context

StackExchange Code Review Q#60022, answer score: 5

Revisions (0)

No revisions yet.