What is an example of the Single Responsibility Principle?

Check out the Solid description.

Unless you ask for something more specific, it will be hard to help more.

Single responsibility is the concept of a Class doing one specific thing (responsibility) and not trying to do more than it should, which is also referred to as High Cohesion.

Classes dont often start out with Low Cohesion, but typically after several releases and different developers adding onto them, suddenly you’ll notice that it became a monster or God class as some call it. So the class should be refactored.

Its hard to think of a good example, but one I can think of recently would be a class we have that manages different packet processing stages, a type of Chain of Responsibility. The initial intention of this class was to maintain a list of stages and to orchestrate calling packetProcess() on them. Well, it ended up that everybody added anything to do with the processing stages (since the manager class was an easy place to access the stages) to this manager class, especially stage configuration. The manager class no longer had a Single Responsibility, but instead was also responsible for making calls to the stages for configuration changes: thus the Cohesion had been reduced.

We ended up having to refactor the manager class, ripping out all the stage configuration and putting it in a factory, thus leaving the manager to do what it was intended to do.

Leave a Comment