# LSP: Liskov substitution principle ---- ### Core concept What is wanted here is something like the following substitution property: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T. --- ## GUIDING THE USE OF INHERITANCE ![](https://i.imgur.com/sQ498SS.png) ---- This design conforms to the LSP because the behavior of the Billing application does not depend, in any way, on which of the two subtypes it uses. Both of the subtypes are substitutable for the License type. --- ## THE SQUARE/RECTANGLE PROBLEM ![](https://i.imgur.com/x6k6PDu.png) ---- ![](https://i.imgur.com/hSUYczh.png) --- ## LSP AND ARCHITECTURE The best way to understand the LSP from an architectural viewpoint is to look at what happens to the architecture of a system when the principle is violated ---- we might have several Ruby classes that share the same method signatures. Or we might have a set of services that all respond to the same REST interface --- ## EXAMPLE LSP VIOLATION Assume that we are building an aggregator for many taxi dispatch services. Customers use our website to find the most appropriate taxi to use, regardless of taxi company. Once the customer makes a decision, our system dispatches the chosen taxi by using a restful service ---- ``` purplecab.com/driver/Bob ``` ``` purplecab.com/driver/Bob /pickupAddress/24 Maple St. /pickupTime/153 /destination/ORD ``` ---- Clearly, this means that all the dispatch services, for all the different companies, must conform to the same REST interface. They must treat the pickupAddress, pickupTime, and destination fields identically. ---- ``` if (driver.getDispatchUri().startsWith("acme.com"))… ``` ---- | URI | Dispatch Format | | -------- | --------------------------------------- | | Acme.com | /pickupAddress/%s/pickupTime/%s/dest/%s | |\*.* | /pickupAddress/%s/pickupTime/%s/destination/%s | --- ## Conclusion The LSP can, and should, be extended to the level of architecture. A simple violation of substitutability, can cause a system’s architecture to be polluted with a significant amount of extra mechanisms.
{"metaMigratedAt":"2023-06-15T14:23:22.227Z","metaMigratedFrom":"YAML","title":"LSP: Liskov substitution principle","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"5525761c-1b39-465d-9c80-28d23b552681\",\"add\":8612,\"del\":6262}]"}
    190 views