OOP设计:在哪里放置对象特定的“比较”方法?

发布于 2024-09-29 19:31:55 字数 428 浏览 6 评论 0原文

我有一些来自存储在测试集合对象中的一系列测试运行的测量对象实例。我还有一些逻辑可以比较两个测试结果对象实例并告诉我它们是否“足够接近”。

这个逻辑应该放在哪里呢?

  1. 将对象作为方法?例如:instance.approximately_equal(other)
  2. 在对象的类上作为类/静态方法? class.approximately_equal(a,b)
  3. 在集合对象上作为方法? collection.approximately_equal(a,b)

正确的面向对象设计是什么?

(我问,因为虽然#1似乎是正确的解决方案,但我永远不会问某个实例是否近似等于另一个实例。只有当“某组对象”彼此相等时。这让我思考。 ..)

谢谢

I have some measurement object instances from a series of test runs stored in a test collection object. I also have some logic that can compare two test result object instances and tell me if they are "close enough".

Where should this logic be placed?

  1. On the object as a method? Like: instance.approximately_equal(other)
  2. On the object's class as a class/static method? class.approximately_equal(a,b)
  3. On the collection object as a method? collection.approximately_equal(a,b)

What is the correct OO design for this?

(I ask, since although #1 would seem the correct solution, I'd never be asking if some one instance is approximately_equal to a different instance. Only if "some group of objects" are equal to each other. It got me thinking...)

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

孤凫 2024-10-06 19:31:56

我读过的面向对象设计书籍建议将跨类功能放入服务提供者对象中。这将使两个对象解耦并降低复杂性,但如果您的项目很小,则可能有点过大了。

The object oriented design books I have read suggest putting cross class functionality into service provider objects. This will decouple the two objects and reduce complexity, but may be overkill if your project is small.

冰雪之触 2024-10-06 19:31:56

我会使用选项 1(实例方法),因为这使您能够细化派生类中的比较逻辑(如果需要)。

I would use option 1 (instance method) since that enables you to refine the comparison logic in derived classes (if needed).

耀眼的星火 2024-10-06 19:31:56

我发现#3 是最不引人注目的,并且可以减少臃肿的代码,因为它往往会迫使您使这些方法尽可能灵活/可重用。例如,在 C++ 中,您可能只使用运算符重载来处理它;如果您有一个实用程序类(或者,如果您计划扩展本机数据类型),则最终效果是相同的,只是表现形式不同。

I've found #3 is the least obtrusive and leads to less bloated code, because it tends to force you to make those methods as flexible/reusable as possible. For example, in C++, you'd potentially just use operator overloading to handle it; if you have a utility class (or, if you plan on extending a native data type), the net effect is the same, just with a different presentation.

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