S like Single responsibility principle

By | February 15, 2020

Single responsibility principle

Every class should have only one reason to change.

Every class should have:

  • Only one goal of existence.
  • Only one responsibility.
  • Only one task to do.
  • Only one reason for the modification.

This rule can be applied to methods, functions, classes, modules and packages.

 

Bestseller dnia w księgarni Złote Myśli

Advantages

  • More readable code.
  • More understandable code.
  • Lack of god-classes — classes, which do everything (or too much) and change with every change in the application.
  • Easier software modification and maintenance.
  • A small software change only affects one class.
  • The modification only affects the area you want to change. A changer does not touch other areas.
  • Less error-prone.

Disadvantages

  • Many classes.

Examples

  1. E-mail address validator in a separate class (not with user data).
  2. Phone number validator in a separate class (not with user data).
  3. Database writer in a separate class (not with saving data).
  4. Class with address a separate class (not with client data).

All posts from mini project: Learn SOLID and OOP principles:

Sources

Main image

Materials

Leave a Reply

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