“消息链"vs“中间人" [英] "Message Chains" vs "Middle Man"

查看:105
本文介绍了“消息链"vs“中间人"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Fowler 的重构书,对这两种代码味道有点困惑.

I'm reading through Fowler's refactoring book and am a bit confused about those two code smells.

消息链"是类似于 a.getB().getC().getValue() 的调用.

"Message Chains" are calls like a.getB().getC().getValue().

中间人"是一种类似的方法

"Middle Man" is a method like

class A
{
    object getCValue()
    {
        return b.getCValue();
    }
}

我对这两部分的理解是,如果您有消息链",则可以通过引入中间人"来缩短它们.如果你有中间人",你可以把他们变成消息链"......

The way I understand the two section is that if you've got "Message Chains" you shorten them by introducing "Middle Men". And If you've got "Middle Men" you turn them into "Message Chains"...

现在显然必须对此有一些限制,否则您将拥有程序员的旋转木马.我应该在什么时候偏爱一个?

Now obviously there has to be some limitation to this or you'd have a programmer's merry-go-round. At what point should I favor one over the other?

一种是将类耦合到不相关的类,另一种是将类耦合到结构.所以理论上我的方法是检查任何给定的变化是否减少了一种耦合,而不是增加了另一种耦合.但是一种耦合是不是更糟,应该权衡更多?IE.能去掉X结构的耦合就只加一类耦合?

One is coupling the class to unrelated classes, the other is coupling the class to the structure. So in theory my approach would be to check if any given change reduces one kind of coupling more than it increases the other kind of coupling. But is one kind of coupling worse and should be weighed more? I.e. only add one class coupling if you can remove X structural couplings?

推荐答案

偏向中间人而非消息链也被称为法律Demeter,可以概括为仅与您的直接依赖项对话".

Preferring middle men over message chains is also known as the Law of Demeter, which can be summarized as "only talk to your direct dependencies".

使用中间人而不是消息链的一个好处是在进行单元测试时你必须提供更少的模拟.当您不仅必须为它们的直接依赖项而且还必须为它们的间接依赖项提供模拟时,类变得非常难以测试.

One benefit of using middle men instead of message chains is that you have to provide fewer mocks when doing unit testing. Classes become really hard to test when you have to provide mocks not only for their direct dependencies but also their indirect ones.

它还有助于分离关注点,因为具有 A 并且想要 C 的代码不应该知道有一个 B> 涉及.这有助于模块化.

It also helps with separation of concerns, as code that has an A and wants a C should not have to know that there's a B involved. This helps modularity.

消息链的主要论点是您不必在中间编写样板,这在某些情况下可能有意义,但我认为经验法则应该是首选中间人.

The main argument for message chains is that you don't have to write the boilerplate in the middle, and it might make sense in some cases, but I think the rule of thumb should be to prefer middle men.

这篇关于“消息链"vs“中间人"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆