Single-Responsibility Principle
- Principle :
A class should have one and only one reason to change, meaning that a class should have only one job.
Benefits that help to build better software -
1.Testing – A class with one responsibility will have far fewer test cases.
2.Lower coupling – Less functionality in a single class will have fewer dependencies.
3.Organization – Smaller, well-organized classes are easier to search than monolithic ones.
Example:
The above Invoice class violates the SRP because it has multiple responsibilities – it is responsible for calculating the total amount, printing the invoice, and saving the invoice to the database. As a result, if the calculation logic changes, such as the addition of taxes, the calculateTotal() method would require modification. Similarly, if the printing or database-saving implementation changes at any point, the class would need to be changed. There are several reasons for the class to be modified, which could lead to increased maintenance costs and complexity.
Here's how you can modify the code to follow the SRP:
In this refactored example, we have split the responsibilities of the Invoice class into three separate classes: Invoice, InvoiceDao, and InvoicePrinter.
The Invoice class is responsible only for calculating the total amount, and the printing and saving responsibilities have been delegated to separate classes. This makes the code more modular, easier to understand, and less prone to errors.