Overriding right, right ??

Do I need to call base.METHOD after overriding it, and if so – when is it the right time ?



Well, I’m glad you’ve asked; I had some chat with my co-worker about the subject when he did some overriding to the Form (WinForm) methods and he wasn’t sure about when is it smart to call the base method and if so, should he call base.METHOD before implementing his code, or maybe after. To clarify, quick example:


public class MyForm : Form
{
   protected override void OnLoad(EventArgs e)
   {
      //OK, what here ???!!


      // Custom code here ?
      //base.OnLoad(e); // should I ?
      // Or maybe – Custom code here… ?

   }

}


After thinking for a few seconds, I came up with this explanation – sort of my “best practice” to the issue:


When do I call base.METHOD:



  1. If you don’t know the implementation in the method you’ve just override: assume that it does some “magic” stuff which is important to the correct flow of the application; But This doesn’t mean that you must call the base method.

    • If you want to stop the logic flow, it makes sense to override the appropriate method and write your code which will change the flow according to your need. In this scenario there is no need to call the base method.
    • If you don’t want to change the logic flow, or you’re not sure – call the base method.

  2. If you know the implementation in the method you’ve just override: no “magic” stuff so this is an easy call – if you need the code in the base method, call it – otherwise – leave it out.

Do I call base.METHOD after my custom code, or maybe before:


This is a tricky one and there is not straight answer – my way of thinking and tackling this question is simply by Explore, Run & Learn “process” – meaning, try to Explore about the base method original purpose and try to figure out the logic; This will give you some logical direction whether you need to call the base method or not. For example – if you override the Render method, you can tell (by MSDN or by Reflector) that its rendering the entire object graph so you probably should call it (eventually). Now that you have some feeling about whether you need to write your code before or after the base.METHOD call, Run it and exam the results:



  • Does the page behaves as you expected?
  • Can you mess it up so it won’t work in some scenarios – how can you deal with it ?
  • Grab the nearest programmer available, can he think about something which will mess it up ? if so – how can you deal with it ?

According to the results and the answers about the given questions, you should now have a clear vision about your decision. Make the required adjustments, place some important remarks(to describe your thinking at the moment) and feel good about your code, you did your best to get a good result. And most important – Learn from the process so it will be more natural on the next time you’ll have to face this decision.