Single responsibility principle (SRP) – SOLID

In object-oriented programming style, the single responsibility enforces that each class should represent one and only one responsibility and so if it needs to undergo changes, that should be for only one reason, that is, a class should have one and only one reason to change.

When we design a class or refactor a class and if it needs more than one reason to change, split the functionality into as many parts as there are classes and so, each class represents only one responsibility.

Responsibility in this context is any changes to the function/business rules that causes the class to change; any changes to the connected database schema, user interfaces, report format, or any other system should not force that class also to change:

The preceding class diagram depicts a Person class having two responsibilities: one responsibility is to greet the user with their last name or surname, and another responsibility is to validate the email. If we need to apply SRP on the Person class, we can separate it into two; Person has a method greet, and Email has email validation.

The SRP applies not only at the class level, but also on methods, packages, and the modules.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset