Naming convention for non-virtual and abstract methods

前端 未结 8 1137
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 02:49

I frequently find myself creating classes which use this form (A):

abstract class Animal {
  public void Walk() {
    // TODO: do something before walking

    /         


        
8条回答
  •  抹茶落季
    2021-02-05 03:20

    Good question. The pattern is valid and I use it a lot. I also agree that WalkInternal is not an ideal name.

    In this example I believe you are not framing the problem correctly.

    Rather than renaming the 'internal' method, look at your 'external' public method. It's called Walk, but it has code snippets (//do something before walking and //do something after walking) which clearly shows that it contains more than just the logic for 'Walking'. Maybe this method should be called Exercise or GoToTheShops - or whatever creative name you can think of that describes what you are doing. Whatever the method is, it's definitely a superset of Walking + some other pre / post walking actions.

    A similar example that I've recently developed had a public method called Complete, and a virtual called Save, so that:

    • Every class needed to 'Complete'
    • Different implementations would have their own 'Save' method
    • 'Complete' would also perform some validation, notification, etc

    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.


    edit: If the Walk class doesn't add any significant value or logic to the WalkInternal class then I would question whether it is required. If it does add logic, then it should be renamed to reflect its new function.

提交回复
热议问题