Design Principles – Single Responsibility Principle vs Cohesion

cohesioncouplingdesign-patternssingle-responsibility

I've read several articles on SRP and cohesion, and they seem to contradict each other as far as low coupling is concerned.

Articles on cohesion argue that putting closely related responsibilities together in a class Highly_Cohesive_Class reduces coupling, while articles on SRP would argue that we'd reduce coupling by removing these closely related responsibilities from class Highly_Cohesive_Class into separate classes ( such that each class only has single responsibility/reason to change ).

Don't the two claims contradict each other? Namely,

BTW – I'm aware of the fact that class adhering to SRP principle is also considered highly cohesive class, but in this post the term highly cohesive refers to a class that has several closely related responsibilities.

Best Answer

I think the confusion is that high cohesion does not necessarily mean you want to put all of the "closely related responsibilities" in one class, but rather that all of the items in a class should correspond to closely related responsibilities.

For example, if you have a Kitchen class, you wouldn't want bathroom logic in it; however, you don't HAVE to also have oven and kitchen sink logic in it too, just because they are related. Although it is a kitchen appliance, the Oven probably deserves its own class, and would end up relating to the Kitchen through composition. Likewise the KitchenSink would be related to the Kitchen through composition.

So, look at a highly cohesive as NOT HAVING unrelated logic in it, and look a SRP as the call to delegate responsibilities to objects that serve that one responsibility.

Related Topic