Alex Rivera | Logout

How to "properly" override a base class method?

Asked 2010-06-30T20:08:12.293
36

Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices.

1) Call base.Method(), and then provide my implementation.

2) Provide my implementation and then call base.Method()

3) Just provide my implementation.

Recently while using a library i have realized few bugs that were introduced because of not implementing the method as expected by the library. I am not sure if that is bad on part of library, or something wrong in my understanding.

I will take one example.

public class ViewManager {
     public virtual void Customize(){
        PrepareBaseView();
     }
}

public class PostViewManager {
     public override void Customize(){
        base.Customize();
        PreparePostView();
     }
}


public class PreViewManager {
     public override void Customize(){
        PreparePreView();
        base.Customize();
     }
}


public class CustomViewManager {
     public override void Customize(){
        PrepareCustomView();
     }
}

My question here is that how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class? Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?

Edit
Report

1 Answer

1

The short answer is no. You can't enforce in what order the child calls the base method, or if it calls it at all.

Technically this information should be included in the base object's documentation. If you absolutely must have some code run before or after the child class' code than you can do the following:

1) Create a non-virtual function in the base class. Let's call it MyFunction

2) Create a protected virtual function in the base class. Let's call it _MyFunction

3) Have deriving classes extend the _MyFunction method.

4) Have MyFunction call _MyFunction and run the code it needs to run before or after calling it.

This method is ugly and would require a lot of extra code, so I recommend just putting a notice in the documentation.

answered 2010-06-30T20:10:20.880

Your Answer