Dezign Patterns

Dependency Inversion Principle (DIP)

📜 Definition : High-level modules should not depend on low-level modules. Both should depend on abstractions.
🎯 Intent : Avoid writing code which tightly coupled and hard to maintain, compromises flexibility .

❌ Dependency Inversion Principle Violation Example

🧠 General Rule of Thumb:
Don't use interfaces unless absolutely necessary, it's probably violating DIP. 👀

  • Avoid premature abstraction.
  • Don't create interfaces for every single class, especially when there's only one implementation and no variation in behavior.
  • Keep things simple until flexibility is actually needed.


        class MySQLDatabase {
            void save() {}
        }

        class OrderService {
            MySQLDatabase db = new MySQLDatabase(); // Direct dependency
        }
    
✅ Better with DIP:

        interface Database {
            void save();
        }

        class MySQLDatabase implements Database {
            public void save() {}
        }

        class OrderService {
            Database db;

            OrderService(Database db) {
                this.db = db;
            }
        }

    
Now you can easily swap databases (e.g., MySQL, PostgreSQL, NoSQL, etc.) — it's loosely coupled