Menu

S — Single Responsibility Principle — SOLID Principles with Examples
📰

S — Single Responsibility Principle — SOLID Principles with Examples

DEV Community: dotnet·DIVAKAR UPADHYAY·4 days ago
#NetiW5xR
#devtodotnet#devto#dev#class#change
Reading 0:00
15s threshold

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 { public decimal Calculate ( Invoice i ) => i . Lines . Sum ( l => l . Qty * l . Price ) * 1.18m ; public void Save ( Invoice i ) { using var c = new SqlConnection ( "..." ); /* INSERT ... */ } public void Email ( Invoice i ) { var smtp = new SmtpClient ( "smtp.example.com" ); /* ... */ } }

// ✅ One responsibility each public class InvoiceCalculator { public decimal Total ( Invoice i ) => i . Lines . Sum ( l => l . Qty * l .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.