githubEdit

Dependency Inversion

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Explanation: Instead of directly depending on concrete implementations, depend on abstractions (interfaces).

Java Example

Bad Design (Violating DIP)

class MySQLDatabase {
    void connect() {
        System.out.println("Connecting to MySQL...");
    }
}

class Application {
    MySQLDatabase database = new MySQLDatabase();

    void start() {
        database.connect();
    }
}

Here, Application is tightly coupled to MySQLDatabase, making it hard to switch to another database.

Good Design (Following DIP)

Now, Application depends on the Database interface, making it flexible to use any database.


Python Example

Bad Design (Violating DIP)

👎 Problem: The Application class is tightly coupled to MySQLDatabase. Switching to another database requires modifying the application.

Good Design (Following DIP)

👍 Fix: Now, Application depends on the Database interface, making it easy to switch databases.

Last updated