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
printInvoice
as a method ofInvoice
class is considered a violation of single responsibility principle because theInvoice
class 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.
saveToDatabase
method is a persistence logic, not a business logic onInvoice
class.
saveToDatabase
method should be extracted out to a separate
InvoicePersistence
class.