Coding Notes

Ideas and thoughts from Seth Long

Coupling and Cohesion

My blog is now located at http://www.WhoIsSethLong.com

One of my biggest pet peeves as a programmer are other programmers who create giant “do all” general classes rather then creating a few smaller specialized classes.  So, I thought it would be a good idea to write a little bit about the Object Oriented principles of Coupling and Cohesion that deal specifically with this issue.

Coupling refers to how tightly different classes are connected to one another.  Tightly coupled classes contain a high number of interactions and dependencies.  Loosely coupled classes are the opposite in that their dependencies on one another are kept to a minimum and instead rely on the well defined public interfaces of each other

Ok, I know it’s hard to understand coupling if you’ve never heard about it before, so I think the best way to explain it is with an example.  I read a great description of coupling a while back that I’m going to share here.  I think it will really help people better understand the concept of coupling.  It was in a reply post on the Sun Developer’s Network forums and just does a great job of describing coupling in easy to understand terms.

Legos, the toys that SNAP together would be considered loosely coupled because you can just snap the pieces together and build whatever system you want to. However, a jigsaw puzzle has pieces that are TIGHTLY coupled. You can’t take a piece from one jigsaw puzzle (system) and snap it into a different puzzle, because the system (puzzle) is very dependent on the very specific pieces that were built specific to that particular “design”. The legos are built in a more generic fashion so that they can be used in your Lego House, or in my Lego Alien Man. 

The code example below shows two very simple classes that are tightly coupled to one another.  It was inspired by actual code from the Ektron CMS my previous employer so dearly loved.  It is not the actual code but is in the exact same format.

class TightCoupling
{
    public void ShowWelcomeMsg(string type)
    {
        switch (type)
        {
            case “GM”:
                Console.WriteLine(“Good Morning”);
                break;
            case “GE”:
                Console.WriteLine(“Good Evening”);
                break;
            case “GN”:
                Console.WriteLine(“Good Night”);
                break;
        }
    }
}
class TightCoupling2
{
    public TightCoupling2()
    {
        TightCoupling example = new TightCoupling();
        example.ShowWelcomeMsg(“GE”);
    }
}

In the above example, the ShowWelcomeMsg function can not be called without knowing the inner-workings of that function making it nearly useless for other systems.  Secondly, if another developer in the future decides to change the switch statement in the ShowWelcomeMsg function, it could inadvertently effect other classes that call that function.

It shouldn’t be too hard to see that loosely coupled classes offer much greater code reuse and flexibility then tightly coupled classes.  Any changes to tightly coupled classes run the high risk of inadvertently effecting other classes and their dependence on other specific classes making them worthless outside the system they are in.  With loosely coupled classes we use well defined public interfaces.  This give us the flexibility to modify the internals of the class in the future without effecting other classes and allow us to reuse the code in other systems.  So, next time you are writing a class, think to yourself: Am I writing a Lego or am I writing a puzzle piece?

Cohesion is often mentioned with Coupling since they usually go hand-in-hand.  Cohesion refers to how closely related methods and class level variables are in a class.  A class with high cohesion would be one where all the methods and class level variables are used together to accomplish a specific task.  On the other end, a class with low cohesion is one where functions are randomly inserted into a class and used to accomplish a variety of different tasks.  Generally tight coupling gives low cohesion and loose coupling gives high cohesion.

The code below is of an EmailMessage class that has high cohesion.  All of the methods and class level variables are very closely related and work together to accomplish a single task.

class EmailMessage
{
    private string sendTo;
    private string subject;
    private string message;
    public EmailMessage(string to, string subject, string message)
    {
        this.sendTo = to;
        this.subject = subject;
        this.message = message;
    }
    public void SendMessage()
    {
        // send message using sendTo, subject and message
    }
}

Now here is an example of the same class but this time as a low cohesive class.  This class was originally designed to send an email message but sometime in the future the user needed to be logged in to send an email so the Login method was added to the EmailMessage class.

class EmailMessage
{
    private string sendTo;
    private string subject;
    private string message;
    private string username;
    public EmailMessage(string to, string subject, string message)
    {
        this.sendTo = to;
        this.subject = subject;
        this.message = message;
    }
    public void SendMessage()
    {
        // send message using sendTo, subject and message
    }
    public void Login(string username, string password)
    {
        this.username = username;
        // code to login
    }
}

The Login method and username class variable really have nothing to do with the EmailMessage class and its main purpose.  This class now has low cohesion and is probably not a good example to follow.

So that’s a brief overview of Coupling and Cohesion.  Remember, if you want easy to maintain and reusable code, stick to loose coupling and high cohesion in your objects.  I should also mention that there are times where tight coupling is desirable but it’s rare that I’ll leave that up to you to read more about on your own.  Also, I really recommend reading up on Cohesion and Coupling on Wikipedia.  They have a lot more detail and information there then what I’ve written here.

– Seth Long

Advertisements

February 14, 2008 - Posted by | Architecture and Design Patterns

2 Comments »

  1. finally got cohesion.
    thanks!!

    Comment by afr0 | November 6, 2010 | Reply

  2. Thanks for the explanation! I needed just a rough idea of the two terms and your post made it all clear.

    Comment by Helen | May 21, 2011 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: