January 15, 2014
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 a 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’ and 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.