The Single Responsibility Principle is one of many ways to determine if code is clean and well designed. It states that every class or module has a single responsibility. That’s it.
It sounds simple enough to adhere to and it is to a certain extent but what it entails is that you really need to think about and scrutinise your code, asking yourself does this really belong here?
Let’s try to put this in some context. In the scenario where you are tasked to create an image processing library, the first thing that might jump out is that we’ll need a class Image.
I would say no. We the Image class which is the image model containing the image data, that’s one responsibility. We also have the class saving the data out to a file and loading it from a file, this could be two responsibilities or one depending. Then finally we have the resizing of the image. The Single Responsibility Principle states each
Ok so let’s move each of these responsibilities into their own class and add an interface to them so that we can do things like allowing for the image to be saved to file in different formats, allowing resizing of images using different methods.
Looks better, done. Well … no. The ImageContainer still has two responsibility, encode/decode the image and save/load it from disk. Let’s have another crack at it.
Does this now satisfy the Single Responsibility Principle? It’s a lot better than what we started out with but we can do better with the ImageContainer. What would you do?
- Allows for loosely coupled design
- Reduces bloat within each class
- Makes DRY (Don’t repeat yourself) code easier
- Testing becomes easier with clear boundaries to test and mock.
- Potentially easier code to understand
Check out Robert C Martins Blog the founder of the Single Responsibility Principe: