Learning Single Responsibility Principle
Introduction to SOLID Principles
Robert C. Martin introduced the SOLID principles of object-oriented programming in 2000. SOLID is an acronym for:
-
S: Single Responsibility
-
O: Open/Closed
-
L: Liskov Substitution
-
I: Interface Segregation
-
D: Dependency Inversion
These principles, like design patterns, aim to help write maintainable, scalable, and flexible software. They’re designed to make apps easy to test, avoid code smells, prevent regression, and make code refactoring easier. These are software design principles that apply to mobile app development. They’re language agnostic and ensure high code quality.
Single Responsibility Principle
This principle states that a class should have only one responsibility and, consequently, only one reason to change. For example, if you have a Book class that needs to be updated because you’re updating a Pencil class, then you’re not following this rule.
Consider a Swiss Army knife and a regular kitchen knife. The Swiss Army knife is more difficult to repair because it has multiple knives and multiple functions, unlike the regular kitchen knife. Similarly, if a store has its security officers doubling as sales representatives, there’s a high chance they’ll be ineffective at both duties. This is the idea behind the Single Responsibility Principle.
Advantages of the Single Responsibility Principle
This principle helps to write minimal, focused tests for each class, promotes decoupling, organizes code better, and makes code more readable and understandable. It becomes easy to tell where to find functionality and what a class does.
In the next segment, you’ll implement this principle in your e-commerce app.