Search code examples
design-patternscouplingcohesion

Coupling of objects


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?


Solution

  • 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.