SOLID, Part 1 — Single Responsibility and Open/Closed
Marketing asked for a new font on Shelfwise's weekly sales report. The change went out, and on Monday finance found the revenue numbers were wrong: the layout code and the revenue maths lived in the same class, and the edit disturbed both. SOLID is five design principles that prevent exactly this kind of collateral damage. This lesson covers the first two letters.
The rule
One reason to change per class; add behaviour by adding code, not editing it.
S — Single Responsibility Principle (SRP). A class should have one reason to change. The most useful way to read "reason" is actor: the person or team who asks for changes. Organise code by the actor it serves.
class SalesReport:
def revenue(self): ... # finance's rules
def render_pdf(self): ... # marketing's layout
def email_monday(self): ... # operations' scheduleThree actors, three reasons to change, one class: any team's request can break another team's feature. Split it into RevenueCalculator, ReportLayout and ReportMailer, and each change touches only its own class.
O — Open/Closed Principle (OCP). Code should be open for extension, closed for modification. When a new variation arrives, you should be able to add it as new code, without editing code that already works and is already tested.
class ReportLayout(ABC):
@abstractmethod
def render(self, figures): ...
class PdfLayout(ReportLayout): ...
class CompactLayout(ReportLayout): ... # new request = new classThe report code calls layout.render(figures) and never changes when a layout is added. Polymorphism, from the previous section, is what makes this possible. Fixing a genuine bug in PdfLayout is still allowed; "closed" protects working behaviour from feature edits, not from repairs.