Single Responsibility
What is it
Class should have only one job.
- therefore, have only one reason for change.
Why use it
Because many different teams can work on the same project and edit the same class for different reasons, conflicting definition/changes could lead to incompatible modules.
Fewer merge conflicts and easier version control by design.
Illustration
Suppose you have a class called Car and another class called Invoice at a car dealership.
class Invoice takes in a Car class and has methods calculateTotal, printInvoice, and saveToDatabase.
printInvoice changes the printing logic.
- Having printInvoiceas a method ofInvoiceclass is considered a violation of single responsibility principle because theInvoiceclass should only contain methods related to business logic, not printing logic.
The printInvoice method should be extracted out to a separate InvoicePrinter class.
saveToDatabase is another violation.
- saveToDatabasemethod is a persistence logic, not a business logic on- Invoiceclass.
saveToDatabase method should be extracted out to a separate
InvoicePersistence class.