The Dependency Inversion Principle (DIP) is a fundamental concept in object-oriented programming that states:
This principle promotes a design where high-level and low-level modules communicate through well-defined abstractions, reducing coupling and increasing flexibility.
Consider a scenario where a class directly depends on a low-level implementation:
class MySQLDatabase { void save(String data) { System.out.println("Saving data to MySQL database"); } } class Application { private MySQLDatabase database = new MySQLDatabase(); void storeData(String data) { database.save(data); } }
This design violates DIP because the Application
class depends directly on the MySQLDatabase
implementation. To adhere to DIP, introduce an abstraction:
interface Database { void save(String data); } class MySQLDatabase implements Database { public void save(String data) { System.out.println("Saving data to MySQL database"); } } class Application { private Database database; Application(Database database) { this.database = database; } void storeData(String data) { database.save(data); } }
Now, the Application
class depends on the Database
interface, allowing flexibility to switch to a different implementation (e.g., PostgreSQL, MongoDB) without modifying the application logic.
By following the Dependency Inversion Principle, you create software systems that are more modular, testable, and adaptable to changes in requirements or technology.