Cohesion vs Single Responsibility

740 views Asked by At

I've started to study concepts like Cohesion and principles like Single Responsibility Principle. I am very confused about the difference between them.

The web has a lot of information, but I find it very difficult to filter out the correct comparison.

What is the relationship between Cohesion and Single Responsibility? Is it possible for a class to have only one responsibility but low cohesion?

2

There are 2 answers

0
Ricardo Costeira On BEST ANSWER

Cohesion can be seen a software quality metric, while SRP is more of a subjective software quality principle. As the Pragmatic Programmers describe it, cohesive code happens when things that belong together and depend on one another stay together.

For instance, if a class's instance variables or properties are all used by its methods and its methods alone, but the methods also do not use any external data or methods from other objects, that class is said to be highly cohesive. However, if that class happens to be reading and writing from a file, that class can be seen as not adhering to the Single Responsibility Principle, as reading and writing can be viewed as two very distinct tasks. Regardless, you can also see the class's main task as "do IO operations with the file system", so SRP is somewhat open to interpretation depending on the context it's applied.

0
progmatico On

This concepts are described in a concise manner in Wikipedia here and here.

One responsability is still an abstract concept. If the responsability is to build a report, it is one task, but still a task with several steps and data parts. So there is some space for low cohesion to happen in the class. Just making a calculation, if simple, is much more "atomic" and high cohesion.

If you see SRP as having a single reason to change the class, I think that helps too.