principletypescriptMajor
SOLID — Open/Closed Principle: Open for Extension, Closed for Modification
Viewed 0 times
open closed principleOCPSOLIDextension without modificationabstractionstrategy pattern
Problem
Adding new behavior (a new payment method, a new export format) requires modifying existing, working, tested code. Each modification risks breaking existing behavior and requires retesting all cases.
Solution
Design classes to be extended via new code rather than by editing existing code. Use abstractions (interfaces, abstract classes) as extension points.
// Bad: every new format requires editing ExportService
class ExportService {
export(data: unknown, format: string) {
if (format === 'csv') { /* csv logic */ }
else if (format === 'json') { /* json logic */ }
// Adding 'xml' requires editing here
}
}
// Good: add new formats without editing ExportService
interface Exporter {
export(data: unknown): string;
}
class CsvExporter implements Exporter { export(data: unknown) { return '...csv...'; } }
class JsonExporter implements Exporter { export(data: unknown) { return JSON.stringify(data); } }
class XmlExporter implements Exporter { export(data: unknown) { return '<xml/>'; } }
class ExportService {
constructor(private exporter: Exporter) {}
run(data: unknown) { return this.exporter.export(data); }
}Why
OCP protects existing tested code from being broken by new requirements. Extension via new classes means new code adds new tests rather than changing existing ones.
Gotchas
- You cannot make a class truly OCP until you know what dimensions it will vary along. Premature abstractions often miss the actual variation points.
- OCP and Strategy pattern are closely related — Strategy is often the mechanism that implements OCP.
- OCP does not mean never modify a class. It means design common variation points as extension hooks up front.
Revisions (0)
No revisions yet.