Skip to content

The SOLID Design Principles πŸ‘¨β€πŸŽ“

Lyes S edited this page Jun 25, 2022 · 9 revisions

Table Of Contents

Ref: Martin, Robert C. (2000). "Design Principles and Design Patterns"

Single Responsibility Principle

  • 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.

Open/Closed Design Principle

  • 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.

Liskov Substitution Principle

Interface Segregation Principle

Dependency Inversion Principle

Clone this wiki locally