聚合类扩展基类 - 违反 LSP?

发布于 2024-10-13 06:17:37 字数 744 浏览 6 评论 0原文

维基百科上的里氏替换原理 (LSP)


假设我有一个外星人具有 numFingers 属性*的类。有时,我需要从数据库中提取 numFingers 的总和,并按其他字段值进行分组。在这些情况下,我不需要单独操作每个记录,但我确实需要访问它们的许多功能——能够获取属性、对它们执行一些基本逻辑等。这可能包括从数千个记录中汇总的数据记录,因此当数据库查询可以为我完成求和工作时,实例化数千个 Alien 对象就没有意义了。

我想创建一个名为 AlienAggregate 的扩展类,其属性是从分组的 & 中设置的。汇总查询。这个类允许我调用 Alien 的任何方法。这两个类的功能之间的唯一区别是GetID()。聚合类没有 ID,因为它的数据是从任意数量的记录中派生的。因此,在 AlienAggregate 上调用 GetID() 会引发异常。

这是否违反了里氏替换原则?是否有更好的方法来处理对 GetID() 的调用?有没有更好的方法来设计 AlienAlienAggregate 类之间的关系?

*实际姓名可能已更改,因为我可以。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

oО清风挽发oО 2024-10-20 06:17:37

我认为您没有违反 LSP 因为该原则仅适用于 AlienAlienAggregate 的子类型(或反之亦然) 。这里不存在关系(更多的是Alien的聚合,因为您已经适当地命名了它们)。

相反,听起来 AlienAlienAggregate 可能都实现了 LooksAlien 接口。 Alien 类只有一个附加方法 GetID()。

...只需小心 AlienAggregate 上邪恶的 BeginInvasion 方法。

I don't think you're violating LSP since the principle only applies when Alien is a subtype of AlienAggregate (or the other way around). There is no is a relationship here (more of an aggregation of Alien's as you've appropriately named them).

Instead, it sounds like both Alien, and AlienAggregate probably implement a LooksAlien Interface. The Alien class just has an additional method, GetID().

...just beware of the nefarious BeginInvasion method on AlienAggregate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文