聚合类扩展基类 - 违反 LSP?
维基百科上的里氏替换原理 (LSP)
假设我有一个外星人
具有 numFingers
属性*的类。有时,我需要从数据库中提取 numFingers 的总和,并按其他字段值进行分组。在这些情况下,我不需要单独操作每个记录,但我确实需要访问它们的许多功能——能够获取属性、对它们执行一些基本逻辑等。这可能包括从数千个记录中汇总的数据记录,因此当数据库查询可以为我完成求和工作时,实例化数千个 Alien 对象就没有意义了。
我想创建一个名为 AlienAggregate
的扩展类,其属性是从分组的 & 中设置的。汇总查询。这个类允许我调用 Alien 的任何方法。这两个类的功能之间的唯一区别是GetID()
。聚合类没有 ID,因为它的数据是从任意数量的记录中派生的。因此,在 AlienAggregate
上调用 GetID()
会引发异常。
这是否违反了里氏替换原则?是否有更好的方法来处理对 GetID()
的调用?有没有更好的方法来设计 Alien
和 AlienAggregate
类之间的关系?
*实际姓名可能已更改,因为我可以。
The Liskov Substitution Principle (LSP) on Wikipedia
Say I have a Alien
class with an numFingers
attribute*. Occasionally, I need to pull the sum of the numFingers
from the database, grouped by other field values. In these cases, I have no need to manipulate each record individually, but I do need access to a lot of their functionality -- be able to get attributes, perform some basic logic on them, etc. This may include data summed from thousands of records, so it makes little sense to instantiate thousands of Alien
objects when the database query can do the work of summing for me.
I would like to make an extension class called AlienAggregate
, whose attributes are set from the grouped & summed query. This class would allow me to call any of Alien
's methods. The only difference between functionality of the two classes, is GetID()
. The aggregate class has no ID, since its data has been derived from any number of records. Because of this, calling GetID()
on AlienAggregate
throws an exception.
Is this a violation of the Liskov Substitution Principle? Is there a better way to handle a call to GetID()
? Is there a better way to design the relationship between the Alien
and AlienAggregate
classes?
*Actual names may have been changed just because I can.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您没有违反
LSP
因为该原则仅适用于Alien
是AlienAggregate
的子类型(或反之亦然) 。这里不存在是
关系(更多的是Alien
的聚合,因为您已经适当地命名了它们)。相反,听起来
Alien
和AlienAggregate
可能都实现了LooksAlien
接口。Alien
类只有一个附加方法 GetID()。...只需小心
AlienAggregate
上邪恶的BeginInvasion
方法。I don't think you're violating
LSP
since the principle only applies whenAlien
is a subtype ofAlienAggregate
(or the other way around). There is nois a
relationship here (more of an aggregation ofAlien
's as you've appropriately named them).Instead, it sounds like both
Alien
, andAlienAggregate
probably implement aLooksAlien
Interface. TheAlien
class just has an additional method, GetID()....just beware of the nefarious
BeginInvasion
method onAlienAggregate
.