-
Notifications
You must be signed in to change notification settings - Fork 0
The SOLID Design Principles π¨βπ
Lyes S edited this page Jun 25, 2022
·
9 revisions
Table Of Contents
- Single Responsibility Principle
- Open/Closed Design Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
Ref: Martin, Robert C. (2000). "Design Principles and Design Patterns"
- Each class should be responsible for a single part or functionality of the system.
public class Entity {
public void printTooMuchDetails() {}
public void calculateEstimate() {}
public void addEntityToDatabase() {}
}
The Entity class has three separate responsibilities: reporting, calculation, and database. This violate the SRP principle.
A better approach would be to separate the above class into three classes with separate responsibilities.
- A module should be open for extension but closed for modification
public class Pizza {
public double getPrice (Pizza pizza) {
if (pizza instanceof Vegetarian) {
return pizza.getPrice() * 0.9;
if (pizza instanceof meatFeastPizza) {
return pizza.getPrice() * 0.5;
}
}
If we want to add another subclass, there is need to modify the above class by adding another if statement. This violate the Open-Closed Principle.
A better approach would be to override getPrice() in each subclass that extends Pizza.
Β© 2024 | Lyes Sefiane All Rights Reserved | CC BY-NC-ND 4.0