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?
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters.
In summary, the abstract method should be called Walk , and instead you should rename your public method to something that more accurately describes the 'do something / Walk / do something' process.
An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes. public abstract void MyMethod(); The implementation is provided by a method override, which is a member of a non-abstract class.
Normally, there is no suffix/prefix used when naming abstract classes, unlike interfaces, which have the prefix "I". Just give your class a name that describes what it is for, in a short precise way.
I'm not sure if there is a standard naming convention for this. Besides WalkInternal
, other alternatives might be DoWalk
or WalkImpl
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With