Override methods should call base method?

Posted by Trevor Pilley on Programmers See other posts from Programmers or by Trevor Pilley
Published on 2012-12-02T16:36:46Z Indexed on 2012/12/02 17:20 UTC
Read the original article Hit count: 206

I'm just running NDepend against some code that I have written and one of the warnings is Overrides of Method() should call base.Method().

The places this occurs are where I have a base class which has virtual properties and methods with default behaviour but which can be overridden by a class which inherits from the base class and doesn't call the overridden method.

For example, in the base class I have a property defined like this:

protected virtual char CloseQuote
{
    get
    {
        return '"';
    }
}

And then in an inheriting class which uses a different close quote:

protected override char CloseQuote
{
    get
    {
        return ']';
    }
}

Not all classes which inherit from the base class use different quote characters hence my initial design.

The alternatives I thought of were have get/set properties in the base class with the defaults set in the constructor:

protected BaseClass()
{
    this.CloseQuote = '"';
}

protected char CloseQuote { get; set; }

public InheritingClass()
{
    this.CloseQuote = ']';
}

Or make the base class require the values as constructor args:

protected BaseClass(char closeQuote, ...)
{
    this.CloseQuote = '"';
}

protected char CloseQuote { get; private set; }

public InheritingClass()
    base (closeQuote: ']', ...)
{
}

Should I use virtual in a scenario where the base implementation may be replaced instead of extended or should I opt for one of the alternatives I thought of? If so, which would be preferable and why?

© Programmers or respective owner

Related posts about object-oriented-design