Skip to main content
InterviewHubPRO
Section Overview
Q2

Question 2 of 50

Part 1: Core SOLID Principles & Fundamentals (1 - 10)

4%
SOLID & OOP Principles (50 Qs)•Part 1: Core SOLID Principles & Fundamentals (1 - 10)

How do you implement the Single Responsibility Principle (SRP) in practice?

junior LevelCode Examplesolid-principlesCore SOLID Principles

In Simple Words: A class should focus on a single concern:

  • Violation: An Invoice class that calculates taxes, prints invoices to PDF, and saves invoices to a PostgreSQL database (3 reasons to change!).
  • Refactoring:
    • Invoice: Manages line items and calculations.
    • InvoicePdfGenerator: Handles PDF formatting.
    • InvoiceRepository: Handles database persistence.
typescript
// SRP Refactored:
class Invoice {
  constructor(public items: LineItem[]) {}
  calculateTotal(): number { /* business logic */ }
}

class InvoiceRepository {
  save(invoice: Invoice): Promise<void> { /* SQL INSERT */ }
}