0
1.3kviews
Code for Cohesion.
1 Answer
0
1views

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 Email Message 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 Email Message { 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 Email Message { 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.

Please log in to add an answer.