SOLID Principles #1: Single Responsibility Principle
In each part I will describe and analyze one of these principles. In the last part, expect summary of the entire series containing a few tips and thoughts.
Let’s start. What are SOLID Principles? There are five general design principles of object-oriented programming intended to make software more understandable, extendable, maintainable and testable.
-
Single responsibility principle (SRP)
Today, more about first principle - Single Responsibility Principle.
Single Responsibility Principle
“Class (object) should have one and only one responsibility (and this responsibility should be fully encapsulated)”.
or
“A class should have only one reason to change”.
To simplify it even more, we can say that a class should do only one thing.
But how to define responsibility of a class? How to define this “reason to change”? Answer to this question is crucial and not so easy.
Consider the following sentence: “There should be no more than one reason to modify (rewrite) a class” (modifying class code in a file, not object memory state). We will try to determine this reason in this article.
Example: Suppose that we want to create an user. The first thing we need to do is to validate data. Let’s make it in service object. Such a class can see similar to this: