S — Single Responsibility Principle — SOLID Principles with Examples
Lesson 1 of 8 in the free SOLID Principles with Examples course on DevLadder. "A class should have one, and only one, reason to change." — Robert C. Martin "Reason to change" = one actor or stakeholder. A class that formats invoices and saves them and emails them changes when finance, DBAs or the email provider change. // ❌ Violates SRP — three reasons to change public class InvoiceService {…
The Single Responsibility Principle (SRP) asserts that a class should possess only one reason to change. This implies that each class should have one cohesive job, with no more than one compelling motive for alteration. Changing the class responsible for formatting invoices, saving them, and emailing them simultaneously violates SRP. Altering the invoice formatting method, the data storage mechanism, or the email delivery service would all necessitate modifications to the class.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.