开发者

Coupling of objects

开发者 https://www.devze.com 2023-02-27 03:31 出处:网络
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(

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消