What is an example of the Liskov Substitution Principle?

What is an example of the Liskov Substitution Principle?

回答1

A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code.

In mathematics, a Square is a Rectangle. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made Square derive from Rectangle, then a Square should be usable anywhere you expect a Rectangle. This makes for some strange behavior.

Imagine you had SetWidth and SetHeight methods on your Rectangle base class; this seems perfectly logical. However if your Rectangle reference pointed to a Square, then SetWidth and SetHeight doesn't make sense because setting one would change the other to match it. In this case Square fails the Liskov Substitution Test with Rectangle and the abstraction of having Square inherit from Rectangle is a bad one.

enter image description here

Y'all should check out the other priceless SOLID Principles Motivational Posters.

 

回答2

The Liskov Substitution Principle (LSP, ) is a concept in Object Oriented Programming that states:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

At its heart LSP is about interfaces and contracts as well as how to decide when to extend a class vs. use another strategy such as composition to achieve your goal.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(156)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-09-22 使用entityframework操作sqlite数据库
2016-09-22 excel在一个图表内,显示折线图和柱状图
2016-09-22 通过NuGet获取sqlite对应的.net的dll
2015-09-22 comparison of floating point numbers with equality operator. possible loss of precision while rounding values
2015-09-22 Formatting is Specified but argument is not IFormattable
2015-09-22 Covariance and Contravariance in C#的搜索条件
2015-09-22 Covariance and Contravariance in C#, Part Two: Array Covariance
点击右上角即可分享
微信分享提示