Class should have only one job.
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.
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.
printInvoice
as a method of Invoice
class is considered a violation of single responsibility principle because the Invoice
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 on Invoice
class.saveToDatabase
method should be extracted out to a separate
InvoicePersistence
class.