The Single Responsibility Principle (SRP) states that a class should have only one reason to change. In other words, a class should have only one responsibility.
Let’s look at a class which is not following this principle:
It seems to have several responsibilities:
Calculating the total amount - If the pricing logic changes, the Invoice class would need to be modified.
Saving data to a database - If you decide to change the database technology or the way data is saved, the Invoice class would need to be modified.
Printing the invoice - If the printing mechanism changes (e.g., from a physical print to digital format), you would need to modify the Invoice class.
Let’s segregate these responsibilities in separate classes.
Invoice.java
Product.java
InvoiceCalculator.java
InvoicePersistence.java
InvoicePrinter.java
Each class has a single responsibility and can be developed, tested, and modified independently.