The Single Responsibility Principle (Part 3)
Today we’re wrapping up our journey into the first of the SOLID Principles – The Single Responsibility Principle (SRP). You can read the prior two articles explaining the SRP here, and how to overcome SRP violations here.
SRP is about Cohesion
Cohesion refers to the extent to which elements in a module belong together. When it comes to module design, higher cohesion is better. In our original example, the methods on the Employee class are utilised by three distinct actors – the people from the Accounting, Operations and IT departments. Therefore, class Employee has low cohesion.
In contrast, here is a high cohesion class, ShoppingCart:
For ShoppingCart, all the public methods concern the manipulation of the CartItems array; We can add to them, remove from them, clear out all items from the cart. The cart can also list the contained items for us and calculate a total amount to pay. Who is the actor using these methods? Only the Shopper. This class has high cohesion. High cohesion classes are preferable since they tend to be more robust, more reusable, more understandable. High cohesion modules have focus; they have only one responsibility.
The SRP & Components
To make class Employee SRP-compliant, we broke it up into smaller, cohesive classes: PayCalculator, HoursReporter and EmployeeSaver. These ‘belong’ to different actors – The Accounting, Operations and IT departments respectively. They must not reference and call one another, or the SRP-violation will reoccur.
So, how do we prevent PayCalculator, HoursReporter and EmployeeSaver from calling one another? Answer: We could put these classes into separate components (projects in .NET):
In .NET, project referencing is uni-directional only, which means that there is at least a limited amount of protection from these classes calling each other indiscriminately. Naming projects after the contained actors or responsibilities might also help to prevent developers from creating undesirable dependencies: Why would I want to reference the Operations project in the Accounting project? What do they have to do with one another?
We’re getting a little bit ahead of ourselves – we’re starting to touch on the Component Principles, the next level up from the SOLID Principles. We’ll explore the Component Principles after the SOLID Principles.