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?

  • "This is sort of problems intended to be dealt with using Template method pattern..." (Derive from a base class but not include a condition in the base class's method) – gnat May 29 '16 at 17:03
  • 2
    Virtual methods are only really useful when called from a base class pointer, and once you have a base class pointer you probably no longer care which methods are virtual and which aren't, so there's no real need. The people implementing derived classes will have to consult the documentation no matter what to know what methods to override and what contract they need to uphold, so a naming convention won't help them very much. – Ixrec May 29 '16 at 17:47
  • 2
    I would argue that it's bad design to have to call a base method inside of your override at all. If you need to delegate to another implementation, and can't just simply override, then what should really be done is using composition to delegate to a class that has the functionality you need. – RubberDuck May 29 '16 at 18:43
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).

  • The template pattern in action. +1. – radarbob May 30 '16 at 19:43
  • In practice you may want to keep the "base" method private, but this is a very nice solution. ++ – RubberDuck May 30 '16 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.