|
| 1 | +--- |
| 2 | +layout: default |
| 3 | +title: "Single Responsibility" |
| 4 | +nav_order: 2 |
| 5 | +permalink: /01-single-responsibility/ |
| 6 | +--- |
| 7 | + |
| 8 | +{: .note } |
| 9 | +> **Language:** **English** | [O'zbek]({{ site.baseurl }}/uz/01-single-responsibility/) |
| 10 | +
|
| 11 | +# Single Responsibility Principle (SRP) |
| 12 | + |
| 13 | +> A class should have only one reason to change. |
| 14 | +
|
| 15 | +Each class or module should encapsulate a **single responsibility**. |
| 16 | +When a class handles multiple concerns (e.g. business logic, persistence, formatting), a change in any one area forces the entire class to be modified and re-tested. |
| 17 | + |
| 18 | +## Diagram |
| 19 | + |
| 20 | +<p align="center"> |
| 21 | + <img src="{{ site.baseurl }}/assets/01-single-responsibility.png" width="700" alt="SRP class diagram" /> |
| 22 | +</p> |
| 23 | + |
| 24 | +## Violation |
| 25 | + |
| 26 | +In [`violation.py`](violation.py) the `Order` class handles three unrelated responsibilities: |
| 27 | + |
| 28 | +- **Price calculation** — computing the order total |
| 29 | +- **Discount logic** — applying business discount rules |
| 30 | +- **Persistence** — saving the order to a database |
| 31 | + |
| 32 | +```python |
| 33 | +class Order: |
| 34 | + def __init__(self, items: list[Item]) -> None: |
| 35 | + self.items = items |
| 36 | + self.total_price = self.calculate_total() |
| 37 | + self.total_price = self.apply_discount(self.total_price) |
| 38 | + self.save() |
| 39 | +``` |
| 40 | + |
| 41 | +Any change to discount rules, pricing formulas, or storage backends forces modification of this single class. |
| 42 | + |
| 43 | +## Correct |
| 44 | + |
| 45 | +In [`correct.py`](correct.py) each responsibility is extracted into its own class: |
| 46 | + |
| 47 | +| Class | Responsibility | |
| 48 | +|-------|---------------| |
| 49 | +| `Order` | Holds order data | |
| 50 | +| `PriceCalculator` | Computes the total price | |
| 51 | +| `DiscountApplier` | Applies discount rules | |
| 52 | +| `OrderRepository` | Handles persistence | |
| 53 | + |
| 54 | +```python |
| 55 | +@dataclass |
| 56 | +class Order: |
| 57 | + items: list[Item] = field(default_factory=list) |
| 58 | + total_price: float = 0.0 |
| 59 | + |
| 60 | + def finalize(self) -> None: |
| 61 | + self.total_price = PriceCalculator.total(self.items) |
| 62 | + self.total_price = DiscountApplier.apply(self.total_price) |
| 63 | + OrderRepository.save(self) |
| 64 | +``` |
| 65 | + |
| 66 | +Now each class has exactly **one reason to change**, and they can be tested, extended, or replaced independently. |
0 commit comments