0

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?

jaco0646
  • 15,303
  • 7
  • 59
  • 83
Rapidistul
  • 406
  • 4
  • 9
  • 19
  • Piggybacking on the answer from @RicardoCosteira, you might say that cohesion is a syntactic feature, whereas SRP is semantic. Cohesion can be measured by a code quality analysis tool; but SRP can only be assessed by a human. – jaco0646 Feb 12 '19 at 14:56
  • https://stackoverflow.com/questions/11215141/is-high-cohesion-a-synonym-for-the-single-responsibility-principle – Hamza Belmellouki Nov 11 '19 at 11:55

2 Answers2

1

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.

Ricardo Costeira
  • 3,171
  • 2
  • 23
  • 23
0

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.

progmatico
  • 4,714
  • 1
  • 16
  • 27