should I call super.xxxx() before my custom code or after when I override a method?
android
Solution
The short answer: It Depends.
The long answer: You need to understand what the implementation of the method in the parent class does.
- There are cases when the super method does some "initialization" work required for the overridden method to function smoothly. In such cases, the `super.myMethod()` call should be the first line in the method.
- In some other cases, the implementation of the method in the parent class could be responsible for some clean up (or some sort of finalization) operations. Thats when you would need to make the call to `super` the last line in your overridden implementation.
- Then there are situations where the order doesn't matter, but you must call the super method because the implementation in the base class performs some operation which are necessary; although the order of these operations doesn't matter. Most of the `Activity` life cycle methods fall in this category. Which is why you must call though to `super.onCreate()` although you can do it at any point in your `onCreate()`.
- Finally, there are also cases where the call to the super method is not required. The base class has a default implementation which you may choose to use or ignore. You might also end up doing an if-else here: For instance, you might call through to the super implementation. If it returns a `null`, you might create a new object and return that instead.
Is there some skills to Identify?
- Read the method documentation and see if there is any mention of the order in which the `super` method must be called.
- Go through the source code of the base class and see if you can figure out whether it does anything that necessitated calling it in a particular order.
Problem
should I call super.xxxx() before my custom code or after when I override a method? Is there some skills to Identify?