特质是好是坏?

发布于 2024-09-08 21:33:34 字数 167 浏览 7 评论 0原文

这是一个开放式问题,但我想征求 SO 社区关于 Traits 的一些意见;您认为 Squeak/Pharo 中的 Traits 是一件好事,还是应该远离它们并使用组合和委托?我问这个问题是因为虽然我知道如何使用它们(感谢 Pharo 的书),但我不太确定使用它们的可接受性如何,或者什么地方可以使用它们,什么地方不可以。

This is an open-ended question, but I would like to solicit some opinions from the SO community on Traits; do you think Traits in Squeak/Pharo are a good thing, or should you stay away from them and use composition and delegation instead? I ask because while I know how to use them (thanks to the Pharo book), I am not really sure how acceptable it is to use them or where it is OK to use them and where it isn't.

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

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

发布评论

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

评论(2

风启觞 2024-09-15 21:33:34

我不喜欢特征,因为它们在代码中引入了强烈的依赖关系。这些依赖关系可能是显而易见的(一个导入特征的类,一个需要方法的特征),但也非常微妙(一个隐藏超级方法/实例变量的特征)。此外,没有足够的工具支持特征。

根据我的经验,委托在像 Smalltalk 这样的动态类型面向对象语言中提供了更好、更可重用的设计。

I do not like traits because they introduce strong dependencies into code. These dependencies can be obvious (a class that imports a trait, a trait that expects methods), but also very subtle (a trait that shadows super methods/instance variables). Furthermore there is no adequate tool support for traits.

In my experience delegation gives a much better and more reusable design in a dynamically typed object-oriented language like Smalltalk.

誰ツ都不明白 2024-09-15 21:33:34

事物都有其优点和缺点。 Lukas 正确地提到了许多缺点:

  • 在代码中引入强依赖性。
  • 没有足够的工具支持。

虽然第二个可能有一天会消失,但第一个不会。

特征的目的是防止当两个不共享除 Object 之外的超类的类共享实例方法时发生代码重复。现在,有时授权可以解决这个问题,但很多时候却不能。所以,traits 的优点是:

  • 减少代码重复。

我的结论是弊大于利。我认为,从今天到永远,代码重复必然会发生。当委托不起作用时,我什至可以想象代码重复并不是那么有害,因为它通常先于复制的代码片段的发散演化。

我认为,截至目前,最好的做法是自动跟踪代码重复,并始终监控何时出现重复代码一端改变,而另一端不变。我目前正在编写一个工具来跟踪此类链接,甚至跨存储库。当它准备好时,我会在我的博客中报告它。

Things have their pros and cons. Lukas rightly mentions many of the cons:

  • Introduce strong dependencies into code.
  • no adequate tool support.

While the second may go away some day, the first will not.

The purpose of traits is to prevent code duplication that occurs, when two classes that don't share a superclass other than Object, share an instance method. Now, sometimes delegation can fix that, but oftentimes it cannot. So, the pro of traits is:

  • Reduced code duplication.

My verdict here is that the disadvantages overweigh. I think that, today and forever, code duplication is bound to occur. And when delegation won't do, I can even imagine that code duplication isn't all that harmful, as it often precedes the divergent evolution of the copied code snippets.

I think, the best thing to do, as of today, is to keep automated track of code duplication, and always monitor when one end changes while the other doesn't. I'm currently writing a tool that'll keep track of such links, even across repositories. I'll report on it in my blog when it's ready.

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