SRP (single-responsibility-principle)
Single Responsibility Principle (SRP)
The Single Responsibility Principle (SRP) is one of the five SOLID principles of object-oriented design. It states that a class should have only one reason to change, meaning it should have only one job or responsibility. This principle helps in creating more maintainable and understandable code by ensuring that each class or module focuses on a single functionality.
Key Benefits:
- Maintainability: With SRP, classes are smaller and focused on a single task, making them easier to understand, modify, and extend.
- Reusability: Well-defined responsibilities promote code reuse, as each class encapsulates a distinct piece of functionality.
- Testability: Testing is simplified because classes have a single focus, reducing the complexity of unit tests.
Example:
Consider a class Invoice
that handles both invoice calculations and printing.
Violation of SRP:
public class Invoice {
public void calculateTotal() {
// Code to calculate total
}
public void printInvoice() {
// Code to print invoice
}
}
Adhering to SRP:
public class Invoice {
public void calculateTotal() {
// Code to calculate total
}
}
public class InvoicePrinter {
public void printInvoice(Invoice invoice) {
// Code to print invoice
}
}
In the second example, the Invoice
class is only responsible for calculations, while the InvoicePrinter
class handles printing. This separation of concerns makes each class more focused and adheres to the SRP.
SRP in Product
SRP Product Wise: Focus on core Feature
Keep product focus on the core feature.
-- image from whats app scaling article
Backlinks