pjxiao
pjxiao

Reputation: 135

Does adding public method to subclass violate LSP (Liskov substitution principle)?

If I add public method to subclass and a client program calls added method, client programs can't use parent object instead of subclass.

import unittest

class BaseClass(object):

    def doSomething(self):
        pass


class SubClass(BaseClass):

    def doStuff(self):
        pass

class Client(object):

    def __init__(self, obj):
        self.obj = obj

    def do(self):
        self.obj.doStuff()

class LSPTestCase(unittest.TestCase):

    def test_call_subclass_method(self):
        client = Client(SubClass())
        client.do()

    def test_call_baseclass_method(self):
        client = Client(BaseClass())
        with self.assertRaises(AttributeError):
            client.do()

if __name__ == '__main__':
    unittest.main()

This case violates LSP?

Upvotes: 6

Views: 1142

Answers (2)

juliaaano
juliaaano

Reputation: 1387

Adding a method to a subclass does not violate LSP. However, it does violate if you invoke that method by downcasting from a parent class.

Robert C. Martin states right in the beginning of his LSP / SOLID paper that:

select a function based upon the type of an object

(...) is an example of a simple violation of the Liskov Substitution Principle.

Generally, if you end up in situations where you need to downcast or use the instanceof operator, it's better to revisit the use of inheritance in favor of other approaches like composition.

Upvotes: 3

dkatzel
dkatzel

Reputation: 31648

No as long as all the methods inherrited from the parent class follow the same contract as the parent then LSP is preserved.

the whole point of LSP is to be able to pass around a subclass as the parent class without any problems. It says nothing about not being able to downcast for additional functionality.

Upvotes: 5

Related Questions