Liskov substitution principle - no overriding/virtual methods?

后端 未结 5 1354
旧巷少年郎
旧巷少年郎 2020-12-07 09:33

My understanding of the Liskov substitution principle is that some property of the base class that is true or some implemented behaviour of the base class, should be true fo

5条回答
  •  一生所求
    2020-12-07 10:24

    I think that you're literally correct in the way you describe the principle and only overriding pure virtual, or abstract methods will ensure that you don't violate it.

    However, if you look at the principle from a client's point of view, that is, a method that takes a reference to the base class. If this method cannot tell (and certainly does not attempt to and does not need to find out) the class of any instance that is passed in, then you are also not violating the principle. So it may not matter that you override a base class method (some sorts of decorators might do this, calling the base class method in the process).

    If a client seems to need to find out the class of an instance passed in, then you're in for a maintenance nightmare, as you should really just be adding new classes as part of your maintenance effort, not modifying an existing routine. (see also OCP)

提交回复
热议问题