SOLID
Loading
Loading
SOLID
The two that do the most work, and the two most often quoted without their qualifier.
By the end of this chapter
Concept
A class should have one reason to change — meaning one source of change requests. Not one method, not one job loosely defined: one constituency whose decisions force this file open.
Consider a class that formats an invoice as HTML and also computes its tax. Two different people change those: a designer and an accountant. Their changes arrive on different schedules for unrelated reasons, and every time one of them touches the file, the other's work is in the diff. That is the cost SRP names.
// Three constituencies in one class.final class Invoice { Money total() { ... } // accounting changes this String toHtml() { ... } // design changes this void save(Connection c) { ... } // infrastructure changes this}final class Invoice { // the accounting rules Money total() { ... }} final class InvoiceHtmlView { // the presentation String render(Invoice invoice) { ... }} interface InvoiceStore { // the persistence seam void save(Invoice invoice);}Concept
Open for extension, closed for modification — along a specific, named axis. New behaviour of that kind should arrive as new code, not as an edit to existing code.
The qualifier is everything. Closed against what? A class cannot be closed against all change; asking it to be is how you get an abstraction for every field. Name the axis: new payment methods, new export formats, new vehicle types. Then close against that one and leave the rest open to ordinary editing.
// Open against new export formats: adding CSV is a new class.interface Exporter { String export(Report report);} final class ReportService { private final Map<Format, Exporter> exporters; String export(Report report, Format format) { return exporters.get(format).export(report); }}Compare that with a switch inside ReportService. The switch is not wrong — for two formats that have not changed in three years it is clearer. It becomes wrong when the same switch appears in four places and adding a format means finding all of them.
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for: