0

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
user478636
  • 3,304
  • 15
  • 49
  • 76
  • Tell us more; what does doA() actually do in relation to the A class? Does it create an A or consume an A or update an A or what? – Jacob Mattison Apr 20 '11 at 16:34
  • Class A is the information expert. It is a Board object. doA() represents the getSquare() method. and Class B represents the Square object. – user478636 Apr 20 '11 at 16:39

1 Answers1

1

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.

Mike Valenty
  • 8,941
  • 2
  • 30
  • 32