里氏替换原则和流 [英] Liskov substitution principle and Streams
问题描述
是否事实,有的流的,不能书面或寻求打破了里氏替换原则派生类
Does the fact that there are Stream derived classes that cannot be written or sought break the Liskov substitution principle?
例如,的的NetworkStream 不能被追捧,它会抛出一个引发NotSupportedException
如果方法寻找
For example, the NetworkStream cannot be sought, it will throw a NotSupportedException
if the method Seek
is called.
还是因为>被调用。 CanSeek
标记的存在,这是确定?
Or because the existence of CanSeek
flag it is ok?
考虑众所周知的例子广场
从长方形
...会增加标志的 DoesHeightAffectsWidth
和 DoesWidthAffectsHeight
到长方形
解决这个问题?
Considering the well known example of Square
inheriting from Rectangle
... would the addition of the flags DoesHeightAffectsWidth
and DoesWidthAffectsHeight
to Rectangle
fix the issue?
难道这不是开门通过添加标志固定的东西呢?
Doesn't this open the door for fixing things by adding flags?
推荐答案
的可以...
方法意味着流
不破LSP。 流
提供的能力的读,写和寻找,但没有的保证的任何实现类将履行它。在可...
方法使这个流
合同明确的特点 - 派生类必须实现他们允许客户端代码来检查由呼叫前派生类中是否实现了某些行为。因此,试图写入流
应检查 CanWrite
之前调用编写任何代码
,例如,这可以用流
的任何正确实现的衍生完成。 。ERGO,他们是可以互换的,因为LSP要求
The Can...
methods mean that Stream
doesn't break LSP. Stream
provides the capability to read, write and seek, but no guarantee that any implementing class will honour it. The Can...
methods make this an explicit feature of the Stream
contract - derived classes must implement them to allow client code to check whether a derived class implements certain behaviour before a call is made. So, any code that attempts to write to a Stream
should check CanWrite
before calling Write
, for example, and this can be done with any correctly-implemented derivative of Stream
. Ergo, they're interchangeable, as LSP requires.
我认为,添加方法标志是否派生类实现特定的功能可能被滥用这是千真万确的 - 如果一队是散漫,他们最终可能会打破ISP一个非常广泛的,臃肿的接口。我认为,流
和的IList< T>
都是精心设计的在这方面的 - 只要不破LSP,他们定义密切相关行为的足够窄的合同留ISP内显然,他们的设计已经考虑。
I think it's certainly true that adding methods to flag whether or not derived classes implement a particular feature could be abused - if a team were undisciplined, they may end up with a very broad, bloated interface that breaks ISP. I think that Stream
and IList<T>
are well-designed in this respect - they don't break LSP, and they define a narrow enough contract of closely-related behaviours to stay within ISP. Clearly, their design has been considered.
我认为,在广场的情况下
从<$ C $继承C>长方形,你当然可以添加 DoesHeightAffectsWidth
和 DoesWidthAffectsHeight
来解决这个问题,但团队必须决定是否这是可以接受的,或增加这些方法是否突破ISP。为 AreAllInternalAnglesEqual
的除了支持梯形太远?在一定程度上,它是由工程师编写代码
I think that in the case of Square
inheriting from Rectangle
, you could certainly add DoesHeightAffectsWidth
and DoesWidthAffectsHeight
to fix the issue, but the team must decide whether that's acceptable, or whether the addition of those methods breaks ISP. Is the addition of AreAllInternalAnglesEqual
to support trapezoids too far? To a certain extent, it's up to the engineers writing the code.
这篇关于里氏替换原则和流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!