Single Responsibility Principle

Firstly, what is the Single Responsibility Principle?

Definition: An object should have a single responsibility.

In practice, to adhere to this principle, an object is a class and that class’s functionality is grouped around a single idea or unit of responsibility. Robert C Martin defined responsibility as a reason to change.

This means that a class should only have one reason to change. An example of how this might work is with a class that compiles and formats a report. This class has two responsibilities and two reasons the class might change. One change might be the cosmetic look of the report and the other content.

To adhere to the single responsibility principle, this class should be split up to two different classes, each with a single responsibility and a single reason to change. One to create the content of the report and the other to format it cosmetically.

Separation of concerns

It could be said that the original class had two concerns. There is another principle called ‘separation of concerns’. It follows the same idea as the single responsibility principle, in that a class should have a single concern. The separation of concerns can be used with a wider meaning also, to be applied to projects, services and layers in architecture.

Finally, now you know about this principle, read about the other SOLID principles of Object Orientated design here.

Leave a Comment

Your email address will not be published. Required fields are marked *

Free eBook: Give Your Customers What They Need! Your Free Guide to Continuous Value Delivery

X