Naming convention for non-virtual and abstract met

2019-03-14 09:23发布

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?

7条回答
ら.Afraid
2楼-- · 2019-03-14 09:54

I prefer to name my virtual or abstract methods with the suffix Core, to indicate, that the method should contain the core logic to do something.

All argument checks and raising possible events I do in the method, that calls the Core-Methods.

  abstract class Animal {
    public void Walk() {
      // TODO: do something before walking 
      // possible Argument checks and event raising

      // custom logic implemented by each subclass
      WalkCore();

      // TODO: do something after walking
    }

    protected abstract void WalkCore();
  }

  class Dog : Animal {
    protected override void WalkCore() {
      // TODO: walk with 4 legs
    }
  }

  class Bird : Animal {
    protected override void WalkCore() {
      // TODO: walk with 2 legs
    }
  }

I think there is no offical naming guideline for this, and it´s up to you. But it should be consistent for all classes and virtual/abstract methods you define.

The "Framework Design Guidelines" suggest to use the Core suffix if you follow the Template Method and want to provide extensibility points.

查看更多
登录 后发表回答