Reputation: 31
I was asked today how Liskov's Substitution Principle might conflict with the Open/Closed principle, any ideas?
Does it have to do with extending the parent class with OC principle and then not being able to step in as a substitute with Liskov's principle?
Upvotes: 3
Views: 669
Reputation: 19702
Suppose you have a library containing a class A with some functionality, and you would like to change the behavior of (a part of) this class.
If you would like to adhere to the Open/Close principle, you should create a subclass which derives from A and which behaves differently (because this principle prohibits you to change class A)
If you would like to adhere to the Liskov principle, you are not allowed to create a subclass which has different behavior, so you should change the original class.
This means adhering to both principles in this case is not possible.
Example
A class 'StorageController' has a function Store() which stores your project as an XML file. Now you would like to change this so it stores a JSON file instead.
Open/Close principle says you would have to create a subclass 'JsonStorageController' which overrides this method to store json instead of xml. However, this violates the Liskov Principle, as the StorageController can not be simply replaced by the JsonStorageController.
Of course there are other solutions which dodn't break these principles, like for example overriding the base class and adding an extra method 'StoreToJson', however these could break other principles, like for example the Single Responsibility Principle (giving two different responsibilities to the subclass).
Upvotes: 2