Reputation: 35225
I've seen many frameworks and helper classes which require you to call their base.MethodName()
in your inherited class override of a some MethodName()
. However, some of them require it to be the last call in a overriden method, while others reqire it to be first call. It is not always obvious which way it should be called and usually is figured out only by reading a docs or samples.
So, am I right in conclusion that where it no some best practices in that area, and call to method base
location in overriden methods depends on framework designer will only? Or there is and I should prefer some design over another? Personally I find calling to base first much more natural, like in constructors (there this design is enforced). Or there is some circumstances (or areas) which force developers to use specific call order?
UPDATE. With help of @Attila I can see now, that most of the base
class calls can be redesigned. Instead of this:
// FRAMEWORK
public virtual void SomeMethod()
{
// framework code
}
// USAGE
public override void SomeMethod()
{
base.SomeMethod();
// user code
}
Do this:
// FRAMEWORK
public void SomeMethod()
{
// framework code
// you can place UserSomeMethod where you want,
// you can change it position in new versions of a fremework
// without breaking user code
this.SomeMethodUserCode();
}
protected abstract void SomeMethodUserCode();
// USAGE
protected override void SomeMethodUserCode()
{
// user code
}
User looses some flexibility (can be read as "have fewer options to break, or make your framework work wrong") but usage is straightforward.
Upvotes: 3
Views: 475
Reputation: 28762
The exact place and order in which you need to call the base methods depends entirely on the logic of the base class (how it is designed to work). Therefore, there is no "one way" that is always correct. You will have to keep reading the specs and docs
Perhaps a better design is to not require any calls back to base: the base performs the methods as it sees fit and allows deriverd classes to provide custom functionality via abstract methods that the base calls when needed; thus relieving the client from having to know the exact ordering of the calls.
Upvotes: 4