C# – Derived Class Method Naming

cdesignnamingnaming-standardsobject-oriented-design

I'm having a hard time coming up with a good naming convention for methods in derived classes that serve the same purpose as the methods in the base class. For example, if both the base class, and the derived class, need to initialize:

public class Foo()
{
    public void Initialize()
    {
        // base class initialization code here
        InitializeDerived();
    }

    // force derived classes to implement their own initialize method
    protected abstract void InitializeDerived();
}

public class Bar() : Foo
{
    protected override void InitializeDerived()
    {
        // initialization code here
    }
}

InitializeDerived() seems clunky. The only other option I can think of is to make the base class Initialize() method virtual. Then the derived class could override it, using the same name, and call the base class Initialize() method first.

Is there a better way? A better naming convention?


This may be a better example, because constructors won't solve the problem here. In this example, we have a rules engine where the client code polymorphically calls Process() on each rule:

public class RuleBase()
{
    public void Process()
    {
        // base class processing code here
        ProcessDerived();
    }

    // force derived classes to implement their own process method
    protected abstract void ProcessDerived();
}

public class RuleValidateHeight() : RuleBase
{
    protected override void ProcessDerived()
    {
        // derived class processing code here
    }
}

The consuming code:

foreach (Rule rule in rules)
{
    rule.Process()
}

Best Answer

In game programming I'm pretty used to the prefix 'On' so that you can think of the base class generating an 'event' when something is about to happen.

protected override void OnInitialize() { /*code here*/ }
protected override void OnProcess() { /*code here*/ }

This is called the Template Method Pattern, by the way.

As Martin comments below, other useful 'event' prefixes include Pre and Post. In a game context you'd typically have PreUpdate OnUpdate PostUpdate.

Related Topic