I frequently find myself creating classes which use this form (A):
abstract class Animal {
public void Walk() {
// TODO: do something before walking
// custom logic implemented by each subclass
WalkInternal();
// TODO: do something after walking
}
protected abstract void WalkInternal();
}
class Dog : Animal {
protected override void WalkInternal() {
// TODO: walk with 4 legs
}
}
class Bird : Animal {
protected override void WalkInternal() {
// TODO: walk with 2 legs
}
}
Rather than this form (B):
abstract class Animal {
public abstract void Walk();
}
class Dog : Animal {
public override void Walk() {
// TODO: do something before walking
// custom logic implemented by each subclass
// TODO: walk with 4 legs
// TODO: do something after walking
}
}
class Bird : Animal {
public override void Walk() {
// TODO: do something before walking
// custom logic implemented by each subclass
// TODO: walk with 2 legs
// TODO: do something after walking
}
}
As you can see, the nice thing about form A is that every time you implement a subclass, you don't need to remember to include the initialization and finalization logic. This is much less error prone than form B.
What's a standard convention for naming these methods?
I like naming the public method Walk
since then I can call Dog.Walk()
which looks better than something like Dog.WalkExternal()
. However, I don't like my solution of adding the suffix "Internal" for the protected method. I'm looking for a more standardized name.
Btw, is there a name for this design pattern?