2

So recently I was working on a project where I had a base class that provided some common functionality. It had several virtual (overridable in vb) functions. I noticed that some of these methods expected the override method to call them first before doing any work, and others expected the work to be done before the virtual method was called.

Is there a standard way of indicating this? Naming convention? Something else?

Sam Axe
  • 243

1 Answers1

3

One solution is to not give the derived class a choice by having a non-virtual method in the base class and also a virtual empty method, which is called from the non-virtual method at the right time.

The code for the two cases could look like this:

class Base
{
    public void BaseBeforeDerived()
    {
        // do base work here

        BaseBeforeDerivedImpl();
    }

    protected virtual void BaseBeforeDerivedImpl()
    {
    }

    public void DerivedBeforeBase()
    {
        DerivedBeforeBaseImpl();

        // do base work here
    }

    protected virtual void DerivedBeforeBaseImpl()
    {
    }
}

Now, when a derived class overrides a method, it does not matter when does it call the base method (or even if it calls it).

svick
  • 10,137
  • 1
  • 39
  • 53