Cohesion is a measure of how well the parts of an object support the same purpose. Cohesion measures two factors:
- how well-defined the purpose of the object is, and
- whether every part of the object contributes directly to fulfilling the purpose.
High cohesion means that an object has one well-defined purpose and everything in the object contributes directly to that purpose. Low cohesion means that either the purpose of the object is ambiguous (as when an object has multiple jobs or a poorly defined job) or not all the parts of the object contribute directly to the object's purpose, or both.
To describe how objects work, I often refer to the way people work. The similarities are strong and the principles work very much the same. So I will use the example of an employee's job description and then compare it with a class description to illustrate the significance of these two factors in measuring cohesion.
When you hire a person to do a job, it is very important that the job be clearly defined.
When the job is not clear, a lot of time is wasted trying to figure out what the person is supposed to do.
Many of us have been in this position and know how frustrating and inefficient it can be.
To avoid this problem we often write a job description such as "Java Developer", for example.
The job description starts with a few lines about the purpose of the job, such as, "A Java developer is responsible for creating quality software solutions to company needs on time and within budget".
Next, the job description lists duties that a person in that position must perform to fulfill the purpose of the job.
The list might include gathering requirements, researching those requirements, designing and constructing a solution to those requirements, testing the solution, putting it into production based on the Software Life Cycle.