Mid
From PDF
SOLID
Design Patterns & SOLID
Can you give an example of refactoring code to follow SRP?
Short answer: Before (SRP Violation): public class Invoice
Example code
{
public void GenerateInvoice() { /* logic */ }
public void SaveToDatabase() { /* logic */ }
public void SendEmail() { /* logic */ }
} This class has 3 responsibilities: generating, saving, and emailing. After (SRP-compliant): public class InvoiceGenerator
{
public void Generate() { /* logic */ }
}
public class InvoiceRepository
{
public void Save(Invoice invoice) { /* logic */ }
}
public class EmailService
{
public void Send(Invoice invoice) { /* logic */ }
} Now each class has a single reason to change.
Real-world example (ShopNest)
Open/Closed in ShopNest: add a new payment method by adding a class, not by editing a giant switch in CheckoutService.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png