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()
}
1
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.
2
Use constructors for this instead.
public class Foo
{
public Foo()
{
// initialization code here
}
}
public class Bar : Foo
{
public Bar()
: base() // base (Foo) constructor gets called first.
{
// initialization code for Bar goes here
}
}
There are many reasons why, but the most compelling one is that newing up an object this way guarantees that you get back an object that is fully initialized on construction.
9
Well, this is going to be easier if you can call Process from the derived class, and work your way up the inheritance tree instead of down:
public class Bar: Foo
{
public override void Process()
{
base.Process(); // optional
// Process Derived Rule here.
}
}
5
The name of the method should say what the method does, instead of just saying where the method appears. Possible names would be:
ProcessRuleSpecifics
ProcessAfterInitialization
ResumeProcess
TerminateProcess
and so on
2