Open Closed Principle¶
Code should be open for extension but closed for modification.¶
This simply means that you should be able to add new behavior without changing the existing code.
π½οΈ Imagine a restaurant menu:¶
β Bad Design¶
Every time you add a new dish:
- You rewrite the whole menu
- Reprint everything
- Risk breaking old items
β Good Design with Open Closed Principle¶
Menu is structured like:
- Base menu stays the same
- You can add new dishes as extensions
You donβt touch old items!¶
You just add new ones!¶
π§βπ³ In software:¶
β Bad Design¶
class Menu {
void showMenu() {
System.out.println("1. Pasta");
System.out.println("2. Pizza");
}
}
showMenu method, which can lead to bugs and maintenance issues.
β Good Design with Open Closed Principle¶
abstract class MenuItem {
abstract void show();
}
class Pasta extends MenuItem {
void show() {
System.out.println("1. Pasta");
}
}
class Pizza extends MenuItem {
void show() {
System.out.println("2. Pizza");
}
}
MenuItem without modifying existing code. This way, the existing menu remains unchanged and you can easily add new items without risking bugs in the old code.