Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
1  
Thanks for accepting! I don't know if you saw @mariosangiorgio's answer, I think that's better and you should accept that instead of mine! –  janos Aug 14 at 14:06
    
@janos thanks for the answer and for the comment. I did as you said. –  Vadim Karimov Aug 14 at 14:08

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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