对象的耦合

发布于 2024-11-02 16:27:51 字数 168 浏览 1 评论 0原文

假设我分别有 A、B 和 C 类的 doA()、doB() 和 doC() 方法。

除非我错了,否则 doA() 方法应该属于 A 类。它必须从 A 类执行。如果 B 类中存在为 A 负责的方法 doA() ,那么 A 类就会耦合到 B 的服务。这也代表了低内聚,高耦合,

我的推理正确吗?

Assuming I have methods of doA(), doB() and doC() of classes A,B and C respectively.

Than unless I am wrong, doA() method should belong to class A. It must be executed from Class A. If a method doA() that does the responsibilities for A, exists in Class B. than class A is coupled to B's services. This also represents low cohesion, and high coupling

is my reasoning correct?

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

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

发布评论

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

评论(1

你的他你的她 2024-11-09 16:27:51

如果一个类的所有方法都对其所有成员变量进行操作,则该类具有最大内聚性

public class MyClass
{
    private int value1;
    private int value2;
    private int value3;

    public int Method1()
    {
        return value1 + value2;
    }

    public int Method2()
    {
        return value1 - value2;
    }

    // doesn't belong on this class
    public int Method3()
    {
        return value3 * 2;
    }
}

耦合有两种形式:

  1. 一个类在内部使用另一个类。这是耦合,但还好,因为它是组合优于继承的示例

示例:

public class MyClass
{
    public void Method1()
    {
        var c = new MyOtherClass();
        c.DoSomething();
    }
}
  1. 更糟糕的耦合如下所示,通常称为 违反德墨忒尔法则

示例:

public class MyClass
{
    public void Method1()
    {
        var c = new MyOtherClass();
        var size = c.Members.Size;
        ...
    }
}

在本例中,MyClass 不仅与 MyOtherClass 耦合,而且还与 MyOtherClass结构耦合,这是当你遇到麻烦并且你的代码变得僵化和脆弱时。

A class has maximum cohesion if all its methods operate on all it's member variables.

public class MyClass
{
    private int value1;
    private int value2;
    private int value3;

    public int Method1()
    {
        return value1 + value2;
    }

    public int Method2()
    {
        return value1 - value2;
    }

    // doesn't belong on this class
    public int Method3()
    {
        return value3 * 2;
    }
}

Coupling comes in two forms:

  1. A class uses another class internally. This is coupling but is kind of okay in that it's an example of composition over inheritance

Example:

public class MyClass
{
    public void Method1()
    {
        var c = new MyOtherClass();
        c.DoSomething();
    }
}
  1. Worse coupling looks like this and is often referred to as a Law of Demeter violation.

Example:

public class MyClass
{
    public void Method1()
    {
        var c = new MyOtherClass();
        var size = c.Members.Size;
        ...
    }
}

In this case, MyClass is coupled not only to MyOtherClass, but the structure of MyOtherClass and this is where you get into trouble and your code gets rigid and fragile.

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