Open Closed Principle
Topic | Source |
---|---|
๐งน Clean Code | Clean Code - Udemy |
A class should be open for extension but closed for modification.
The goal is to avoid classes from growing each time a new functionality is added.
This is a bad example of a printer class, that handles all different possibilities:
class Printer {
printPDF(data: any) {
// ...
}
printWebDocument(data: any) {
// ...
}
printPage(data: any) {
// ...
}
verifyData(data: any) {
// ...
}
}
This is suboptimal because if something in the way printing works is changed, you have to change it in all those functions.
Instead, you should create specific classes that can be extended when needed:
interface Printer {
print(data: any);
}
class PrinterImplementation {
verifyData(data: any) {}
}
class WebPrinter extends PrinterImplementation implements Printer {
print(data: any) {
// print web document
}
}
class PDFPrinter extends PrinterImplementation implements Printer {
print(data: any) {
// print PDF document
}
}
class PagePrinter extends PrinterImplementation implements Printer {
print(data: any) {
// print real page
}
}
The base printer class can be closed for modification. Instead, you can extend it by different subclasses.
This ensures small classes instead of growing classes, keeping the code DRY.